 <p>You could also write an iterator for your matrix. This is not complete but gives you an idea:</p> <pre><code>#include &lt;vector&gt; #include &lt;algorithm&gt; template&lt; class _T &gt; class Matrix { public: std::vector&lt; std::vector&lt; _T &gt; &gt; m_matrix; void alloc( size_t rows, size_t cols ) { m_matrix.resize( rows ); std::for_each( m_matrix.begin(), m_matrix.end(), [cols](std::vector&lt;_T&gt; &amp;t){t.resize(cols);}); } class iterator { public: iterator( std::vector&lt; std::vector&lt; _T &gt; &gt; &amp; v ): m_vbegin( v.begin() ), m_vi( v.begin() ), m_i( m_vi-&gt;begin() ), m_vend( v.end() ) {} iterator&amp; operator++() { if ( ++m_i == m_vi-&gt;end() ) { if ( ++m_vi != m_vend ) m_i = m_vi-&gt;begin(); } return (*this); } void gotobegin() { m_vi=m_vbegin; m_i=m_vi-&gt;begin(); } void gotoend() { m_vi=m_vend; } _T &amp; operator*() { return *m_i; } bool operator==(const iterator &amp; rhs ) { if ( m_vi==rhs.m_vi &amp;&amp; (m_vi==m_vend || m_i==rhs.m_i) ) return true; return false; } bool operator!=(const iterator &amp; rhs ) { return !( *this == rhs ); } private: typename std::vector&lt; std::vector&lt; _T &gt; &gt;::iterator m_vi; const typename std::vector&lt; std::vector&lt; _T &gt; &gt;::iterator m_vbegin; const typename std::vector&lt; std::vector&lt; _T &gt; &gt;::iterator m_vend; typename std::vector&lt; _T &gt;::iterator m_i; }; iterator begin(){ return iterator(m_matrix); } iterator end(){ iterator ret(m_matrix); ret.gotoend(); return ret;} }; int main( void ) { Matrix&lt;double&gt; matrix; matrix.alloc( 4000, 4000 ); std::for_each( matrix.begin(), matrix.end(), []( double &amp;t){ t=1.0;} ); std::for_each( matrix.begin(), matrix.end(), []( double &amp;t){ t+=1.0;} ); return 0; } </code></pre>