2017-06-03 52 views
-3

我有一个使用矢量迭代第i行中向量的向量

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

'auto&row = vvi [row_index];'然后'row.begin();'等。 – VTT

+0

我收到了一条错误消息。你难以理解这条消息吗? –

+0

@VTT你的代码和我的代码有什么不同?我想我正在做同样的事情。 –

回答

1

在你的代码中,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; } 

如果你不希望使用范围,用于语法,多了一个替代的解决方案可能是:

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进行一些研究。)

最后一句:我在这两个示例中都使用了增量运算符作为前缀(++col)(就像您在第一个示例中那样) :就你而言,不需要后缀版本提供的开销。 (即使这是一个微妙的表现加上,这是没有必要的。)

真的希望我能帮上忙。