在矢量向量中迭代我的行

时间:2017-06-03 20:10:07

标签: c++ multidimensional-array vector iterator

我使用矢量矢量

创建了一个2d数组
vector< vector<int> > vvi;

我可以用下面的迭代器迭代这整个向量:

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

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

我不需要遍历整个2d数组,而是需要遍历任何第i行,但它不起作用

std::vector< std::vector<int> >::iterator row; 
std::vector<int>::iterator col;
row = vvi[i];
for (col = row->begin(); col != row->end(); col++) {
        std::cout << *col;          
}

我该如何解决这个问题。非常感谢你的帮助!!

1 个答案:

答案 0 :(得分:0)

在您的代码中,row是一个迭代器,因此您无法为其分配vvi[i]。 在您的情况下,这可以工作:

#include <iterator>
// ...
std::vector<std::vector<int> >::iterator row = vvi.begin();
std::advance(row, i);

for (std::vector<int>::iterator col = row->begin(); col != row->end(); ++col) {
  std::cout << *col << std::endl;
}

你也可以做一些简单的事情(如下面的C ++ 11):

for (auto const& x : vvi[i]) { std::cout << x << std::endl; }

如果您不想使用range-for语法,可以选择另一种解决方案:

auto const& row = vvi[i];
for (auto col = row.cbegin(); col != row.cend(); ++col)
{
  std::cout << *col << std::endl;
}

请注意,我在这里使用cbegin()cend()代替begin()end()。 (如果您不确定差异,请对迭代器和const_iterators进行一些研究。)

最后一句话:我在两个例子中使用了increment运算符作为前缀(++col)(就像你在第一个例子中所做的那样):在你的情况下,不需要后缀的开销版本提供。 (即使这是一个微妙的表现加上,也没有必要。)

真的希望我能提供帮助。