【发布时间】:2021-08-26 04:51:20
【问题描述】:
我想知道是否可以通过迭代器访问std::vector<std::vector<int>> 的元素:我不明白为什么这不会编译:
#include<vector>
#include<iostream>
std::vector<std::vector<int>> vec {{1,2},{3,4}} ;
// to access the single vector
auto it = vec.begin() ;
// to access the element of the vector
auto iit = it.begin() ;
这是我得到的错误:
prova.cpp: In function ‘int main()’:
prova.cpp:10:15: error: ‘class __gnu_cxx::__normal_iterator<std::vector<int>*, std::vector<std::vector<int> > >’ has no member named ‘begin’
10 | auto iit = it.begin() ;
【问题讨论】:
-
这段代码没有出现。你的意思是
(*it).begin()而不是it.begin()? -
我建议使用ranged
forloops 而不是显式使用迭代器。 -
auto iit = it->begin()或auto iit = (*it).begin()(假设it不是结束迭代器)。请注意,iit将仅引用其中一个包含向量的元素(例如{1,2}或{3,4},而不是两者)。 -
@Someprogrammerdude 为什么推荐使用 ranged base for 循环?
-
从您接受的答案中可以看出,它们非常易于使用。 :)
标签: c++ matrix iterator std stdvector