Iterating through vector of vectors

I've been struggling with this problem for a while, searched extensively for answers without luck, so I hope you can help me.

I am writing a template matrix class in c++ using a stl vector of vectors for storing the matrix values, like this:

std::vector< std::vector< T > > m;

Where capital T is the template class. So far, I have accessed the array using a simple nested for-loop and double brackets [][], as you can see in this overloaded operator:

template< class T >
Matrix<T> Matrix<T>::operator + ( const Matrix<T>& rhs )
{
  Matrix<T> result( rows_, cols_ );

  if( ( rows_ == rhs.rows_ ) && ( cols_ == rhs.cols_ ) )
  {
    for ( unsigned int i = 0 ; i < rows_ ; i++ )
    {
      for ( unsigned int j = 0 ; j < cols_ ; j++ )
      {
        result.m[i][j] = m[i][j] + rhs.m[i][j];
      }
    }
  }
  return result;
}

Everything worked fine until I decided it would be cleaner and safer to use the built-in stl iterator for vectors. It currently looks like this:

template< class T >
Matrix<T> Matrix<T>::operator - ()
{
  Matrix<T> result( rows_, cols_, 0.0);

  for 
  (
    typename std::vector< std::vector< T > >::iterator
    iRow = m.begin() ;
    iRow < m.end()   ;
    iRow++
  )
  {

    for 
    (
      typename std::vector< T >::iterator
      iCol = iRow->begin() ;
      iCol < iRow->end()   ;
      iCol++
    )
    {
      result.m[iRow][iCol] = -( m[iRow][iCol] );
    }
  }
  return result;
}

Now I get: error: no match for '[] operator' and a very extensive list of lengthy candidates. However, after having tried for some time to understand the problem and rewriting the code, it still does not compile. Please point me in the right direction.

Regards, Michael

Upvotes: 1

Views: 208

Answers (1)

That's not how iterators work. An iterator is not an index, it's more like a pointer. So you would need iterators over both the source and the destination matrix. I'd say that in your case, indices are actually the better choice.

But if you want to use iteratos, you'd do it like this:

  for 
  (
    typename std::vector< std::vector< T > >::iterator
    iRowS = m.begin(), iRowD = result.m.begin();
    iRowS != m.end();
    ++iRowS, ++iRowD
  )
  {
    for 
    (
      typename std::vector< T >::iterator
      iColS = iRowS->begin(), iColD = iRowD->begin();
      iColS != iRowS->end();
      ++iColS, ++iColD
    )
    {
      *iColD = - *iColS;
    }
  }

Upvotes: 6

Related Questions