【问题标题】:Iterating through a 2d Vector row遍历二维向量行
【发布时间】:2013-11-01 01:03:09
【问题描述】:

我正在为我的 C++ 课做家庭作业。

我正在尝试遍历二维多维向量。我在大小为 7x70-6 by 0-6 的 2d 向量中拥有所有数据。

问题是我需要按照alphaV[0][0], alphaV[1][0], alphaV[2][0],等的顺序输出二维向量的内容。

当我尝试使用嵌套的For 循环来处理这个向量时,我遇到了向量的行不会迭代的问题,也就是说它们保持在索引 0 处。

所以它不断重复 alphaV[0][0], alphaV[0][0], alphaV[0][0], 等。

如何迭代该模式中的列[0][0], [1][0], [2][0] ...?

【问题讨论】:

  • 你能告诉我们你到目前为止的代码吗?嵌套的 for 循环应该可以正常工作。
  • 我现在没有代码在我面前,但它类似于 for(i=0; i
  • 编辑问题以包含代码,不要将其添加到评论中。如果您没有可用的代码,请立即发布,因为查看您正在使用的实际代码很重要。

标签: c++ vector iteration


【解决方案1】:

遍历向量,这是遍历容器的标准方式:

void printVector(const std::vector< std::vector<int> > & vec)
{ 

    std::vector< std::vector<int> >::const_iterator row; 
    std::vector<int>::const_iterator col; 

    for (row = vec.begin(); row != vec.end(); ++row)
    { 
         for (col = row->begin(); col != row->end(); ++col)
         { 
            std::cout << *col; 
         } 
    } 

} 

更多关于迭代器的信息可以在这里找到:http://www.cplusplus.com/reference/iterator/

【讨论】:

    【解决方案2】:

    仅用于为 AngelCastillo 的回答提供完整示例

    #include <iostream>
    #include <vector> 
    
    using namespace std; //to stop using std every time
    
    int main(){
        vector<int> vts;
        vector<vector<int>> vec; //multidimensional vector
        
    //simple vector iteration
        vts.push_back(10);
        for(vector<int>::iterator itv = vts.begin();itv != vts.end(); ++itv ){
            cout << *itv << "\n";
        }
    
    //how to add multidimensional objects
        vector<int> tmp;
        tmp.push_back(20);
        vec.push_back(tmp);
        
        vector<vector<int>>::const_iterator row; 
        vector<int>::const_iterator col; 
    
        for (row = vec.begin(); row != vec.end(); ++row)
        { 
             for (col = row->begin(); col != row->end(); ++col)
             { 
                cout << *col << "\n"; 
             } 
        } 
        
    //same iteration another way
        for(vector<vector<int>>::iterator row = vec.begin();row != vec.end(); ++row ){
            for(vector<int>::iterator col = row->begin();col != row->end(); ++col ){
                cout << *col << "\n"; 
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2014-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-09
      • 1970-01-01
      • 2016-09-04
      相关资源
      最近更新 更多