Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You can define you own iterator over the columns, so that you can use standard algorithms (like <code>for_each</code>, or <code>transform</code> as mentionned in another answer) to apply you function either to rows or columns of you array by just changing the iterators:</p> <pre><code>#include &lt;iostream&gt; #include &lt;iterator&gt; #include &lt;vector&gt; #include &lt;algorithm&gt; // Custom iterator to iterate over columns // to be adapted to the underlying storage class ColIterator : public std::iterator&lt;std::forward_iterator_tag, double&gt; { public: typedef std::vector&lt;std::vector&lt;double&gt; &gt; MDarray; ColIterator(MDarray &amp; array, int i, int j) : array_(array), i_(i), j_(j) {} ColIterator(const ColIterator&amp; it) : array_(it.array_), i_(it.i_), j_(it.j_) {} ColIterator&amp; operator++() { ++i_; return *this; } ColIterator operator++(int) { ColIterator tmp(*this); operator++(); return tmp; } bool operator==(const ColIterator&amp; rhs) { return &amp;array_==&amp;rhs.array_ &amp;&amp; i_==rhs.i_ &amp;&amp; j_==rhs.j_; } bool operator!=(const ColIterator&amp; rhs) { return !operator==(rhs); } double&amp; operator*() {return array_[i_][j_];} private: MDarray &amp; array_; int i_; int j_; }; // a function void mult2 (double &amp; x) { x *= 2; } int main () { typedef std::vector&lt;double&gt;::iterator RowIterator; int nRows = 5; int nCols = 5; ColIterator::MDarray array (nRows, std::vector&lt;double&gt;(nCols, 1)); // Apply function mult2 to column 3 int col = 3; ColIterator beginCol (array, 0, col); ColIterator endCol (array, nRows, col); std::for_each(beginCol, endCol, mult2); // Apply function mult2 to row 4 int row = 4; RowIterator beginRow (array[row].begin()); RowIterator endRow (array[row].end()); std::for_each(beginRow, endRow, mult2); // Check results for (int i=0 ; i&lt;nRows ; ++i) { for (int j=0 ; j&lt;nCols ; ++j) { std::cout &lt;&lt; " " &lt;&lt; array[i][j]; } std::cout &lt;&lt; std::endl; } return 0; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload