【问题标题】:Iterating through vector of vectors遍历向量的向量
【发布时间】:2014-08-26 08:58:00
【问题描述】:

我一直在为这个问题苦苦挣扎,在没有运气的情况下广泛搜索了答案,所以我希望你能帮助我。

我正在 c++ 中编写一个模板矩阵类,使用 stl 向量来存储矩阵值,如下所示:

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

其中大写 T 是模板类。到目前为止,我已经使用简单的嵌套 for 循环和双括号 [][] 访问了数组,正如您在这个重载运算符中看到的那样:

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;
}

一切都很好,直到我决定将内置的 stl 迭代器用于向量会更清洁、更安全。目前看起来是这样的:

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;
}

现在我得到:错误:不匹配“[] 运算符”和一个非常广泛的冗长候选列表。但是,在尝试了一段时间了解问题并重写代码后,它仍然无法编译。请指出正确的方向。

问候,迈克尔

【问题讨论】:

    标签: c++ templates vector stl


    【解决方案1】:

    迭代器不是这样工作的。迭代器不是索引,它更像是一个指针。因此,您需要在源矩阵和目标矩阵上都使用迭代器。我想说,在你的情况下,索引实际上是更好的选择。

    但如果你想使用迭代器,你会这样做:

      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;
        }
      }
    

    【讨论】:

    • 非常感谢 Angew,这是一个非常有用的答案。是的,当然每个矩阵都需要自己的迭代器,我现在明白了。问题解决了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-23
    相关资源
    最近更新 更多