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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

4.10. CURSORS AND PROPERTY MAPS 127<br />

Its implementation is almost the same as nz cursor and with some refactoring one could certainly<br />

combine it in one implementation that serves both cursors as base class. For the sake of<br />

simplicity we refrain from it here. The two main differences to nz cursor are<br />

• The lack of operator∗ because the cursor is not intended to be dereferred; and<br />

• The functions begin and end to provide the inter loop traversal.<br />

The according functions to provide a right-open interval of row cursors are straight <strong>for</strong>ward:<br />

template <br />

row cursor row begin(const Matrix& A)<br />

{<br />

return row cursor(0, A);<br />

}<br />

template <br />

row cursor row end(const Matrix& A)<br />

{<br />

return row cursor(A.num rows(), A);<br />

}<br />

We can now write begin and end functions that take a row cursor (instead of a matrix) as<br />

argument and give the right-open interval of the rows non-zeros:<br />

template <br />

nz cursor nz begin(const row cursor& c)<br />

{<br />

return c.begin();<br />

}<br />

template <br />

nz cursor nz end(const row cursor& c)<br />

{<br />

return c.end();<br />

}<br />

For the inner loop we can reuse nz cursor and only need to determine the right intervals within<br />

each row. This is per<strong>for</strong>med with the begin and end function from row cursor which in turn uses<br />

begin row from the matrix. That is why the row cursor needs a matrix reference.<br />

A two-dimensional traversal is realized as follows:<br />

<strong>for</strong> (row cursor< coo matrix > c= row begin(A), end= row end(A); c != end; ++c) {<br />

std::cout ≪ ”−−−−−\n”;<br />

<strong>for</strong> (nz cursor ic= nz begin(c), iend= nz end(c); ic != iend; ++ic)<br />

std::cout ≪ ”A[” ≪ row(∗ic) ≪ ”][” ≪ col(∗ic) ≪ ”] = ” ≪ value(∗ic) ≪ ”\n”;<br />

}<br />

std::cout ≪ ”−−−−−\n”;<br />

The outer loop iterates over all rows of the matrix and the inner loop over all non-zeros in this<br />

row.<br />

Résumé The technique is more complicated and less readable than accessing entries with<br />

operator[] and needs some familiarization. However, it allows <strong>for</strong>

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

Saved successfully!

Ooh no, something went wrong!