如何在 C++ 中迭代向量的向量?

And*_*ea 1 c++ iterator std matrix stdvector

我想知道是否可以std::vector<std::vector<int>> 通过迭代器访问元素:我无法理解为什么这不能编译:

\n
#include<vector> \n#include<iostream> \n\nstd::vector<std::vector<int>> vec {{1,2},{3,4}} ; \n\n// to access the single vector \nauto it = vec.begin() ; \n\n// to access the element of the vector \nauto iit = it.begin() ; \n\n
Run Code Online (Sandbox Code Playgroud)\n

这是我得到的错误:

\n
prova.cpp: In function \xe2\x80\x98int main()\xe2\x80\x99:\nprova.cpp:10:15: error: \xe2\x80\x98class __gnu_cxx::__normal_iterator<std::vector<int>*, std::vector<std::vector<int> > >\xe2\x80\x99 has no member named \xe2\x80\x98begin\xe2\x80\x99\n   10 | auto iit = it.begin() ;\n
Run Code Online (Sandbox Code Playgroud)\n

for*_*818 6

您可以从对内部向量的引用获取内部元素的迭代器。迭代器不是对元素的引用,但您必须取消引用它。改变这个:

// to access the element of the vector 
auto iit = it.begin() ; 
Run Code Online (Sandbox Code Playgroud)

auto iit = it->begin();
Run Code Online (Sandbox Code Playgroud)

不要让事情变得过于复杂。您可以像这样迭代一个向量:

std::vector<T> vect;

for (auto it = vect.begin(); it != vect.end(); ++it) {
     auto& element = *it;
     // element is a reference to the element in the vector
}
Run Code Online (Sandbox Code Playgroud)

或使用基于范围的循环:

for (auto& element : vect) {
     // element is a reference to the element in the vector
}
Run Code Online (Sandbox Code Playgroud)

事情真的没有比这更复杂的了。

当您有一个嵌套向量并且想要迭代内部向量的元素时,您只需要首先获取外部向量的元素,然后获取内部向量的元素:

std::vector<std::vector<T>> vect2;
for (auto& inner_vector : vect2) {
     // inner_vector is reference to element of vect2
     for (auto& element : inner_vector) {
          // element is reference to element of inner vector
     }
}
Run Code Online (Sandbox Code Playgroud)