03.12.2012 Views

C++ for Scientists - Technische Universität Dresden

C++ for Scientists - Technische Universität Dresden

C++ for Scientists - Technische Universität Dresden

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

124 CHAPTER 4. GENERIC PROGRAMMING<br />

void insert(int r, int c, Value v)<br />

{<br />

assert(r < nr && c < nc);<br />

row index.push back(r);<br />

col index.push back(c);<br />

data.push back(v);<br />

}<br />

void sort() {}<br />

int nnz() const { return row index.size(); }<br />

int num rows() const { return nr; }<br />

int num cols() const { return nc; }<br />

int begin row(int r) const<br />

{<br />

unsigned i= 0;<br />

while (i < row index.size() && row index[i] < r) ++i;<br />

return i;<br />

}<br />

template friend struct coo col;<br />

template friend struct coo row;<br />

template friend struct coo const value;<br />

template friend struct coo value;<br />

private:<br />

int nr, nc;<br />

std::vector row index, col index;<br />

std::vector data;<br />

};<br />

The matrix is supposed to be sorted lexicographically (although we omitted the implementation<br />

of the sort function <strong>for</strong> the sake of brevity). For any offset i the i th entry in each of the vectors<br />

row index, row index and data represent row, column and value of one non-zero entry in the matrix.<br />

The traversal over all non-zeros of the matrix can be realized with a cursor that contains just<br />

this offset.<br />

struct nz cursor<br />

{<br />

typedef int key type;<br />

nz cursor(int offset) : offset(offset) {}<br />

nz cursor& operator++() { offset++; return ∗this; }<br />

nz cursor operator++(int) { nz cursor tmp(∗this); offset++; return tmp; }<br />

key type operator∗() const { return offset; }<br />

bool operator!=(const nz cursor& other) { return offset != other.offset; }<br />

protected:<br />

int offset;<br />

};

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!