如何在 c++ 中使用对向量的向量进行迭代?
How to iterate using vector of vector of pair in c++?
我想问你如何迭代对向量的向量? 假设我有以下内容。
typedef pair<int,int> Pair;
vector<vector<Pair> > adjList;
然后我尝试使用以下代码进行迭代:
vector<vector<Pair> > :: iterator i;
vector<Pair> :: iterator it;
for(i = adjList[N].begin(); i != adjList[N].end(); ++i)
{
for(it = adjList[N].begin(); it != adjList[N].end(); ++it)
//and the rest of the code
但是它返回错误
'no match for ‘operator=’ (operand types are ‘std::vector > >::iterator {aka __gnu_cxx::__normal_iterator >*, std::vector > > >}’ and ‘std::vector >::iterator {aka __gnu_cxx::__normal_iterator*, std::vector > >}’)'.
有人知道吗?谢谢。
您可以使用基于范围的 for 循环和结构化绑定:
for(auto& inner : adjList) {
for(auto& [first, second] : inner) {
first = ...;
second = ...;
}
}
您的问题是您在这里使用第一个元素,外部列表的迭代器:
for(i = adjList[N].begin(); i != adjList[N].end(); ++i)
你的意思显然是让i
成为外部列表的迭代器。您可能打算这样做:
for(i = adjList.begin(); i != adjList.end(); ++i)
但为了方便和可读性,请使用基于范围 for 循环:
for (const auto& row : adjList) {
for (const auto& pair : row) {
// print pair.second or whatever
如果要编辑对,请删除 2const
s。
vector<vector<Pair> > :: iterator i;
vector<Pair> :: iterator it;
for(i = adjList.begin(); i != adjList.end(); ++i)
{
for(it =(*i).begin(); it != (*i).end(); ++it){}
}
如果您的项目使用 C++11 或更高版本,请使用auto
来简化typedef
;
for(auto i = adjList.begin(); i != adjList.end(); i++){
for(auto itr = (*i).begin(); itr != (*i).end(); itr++){
}
}
此外,对于范围:
for(auto & i:adjList){
for(auto &j: i){
// xxxx
}
}
for(i = adjList[N].begin(); i != adjList[N].end(); ++i)
这迭代了第 n 个内部向量而不是外部向量,旁边的类型i
与adjList[N].begin()
类型和N
不一致。
#include <utility>
#include <vector>
typedef std::pair<int,int> Pair;
int main() {
std::vector<std::vector<Pair> > adjList;
std::vector<std::vector<Pair> >::iterator i;
std::vector<Pair>::iterator it;
for (i = adjList.begin(); i != adjList.end(); ++i)//iterating over the outer vector
{
for (it = i -> begin(); it != i -> end(); ++it)//over the inner ones
{
it -> first = ...;//assign to the first of the pair
it -> second = ...;//assign to the second of the pair
}
}
}
相关文章:
- std::向量迭代器和调整大小/保留的奇怪/有趣行为
- 如何取消引用向量迭代器
- Map中的(字符串的)向量迭代器
- C++将向量迭代器转换为索引
- yaml-cpp到std::向量迭代的怪异行为
- 使用索引与迭代器将向量迭代到倒数第二个元素
- 无法取消引用超出范围的向量迭代器 - 有什么问题?
- 向量迭代器不兼容的错误,用于保存另一个向量的迭代器的向量
- C++向量迭代器nth_element编译错误
- 无法查找值初始化的向量迭代器?
- C++向量迭代:常量 vs. 常量自动 vs. 无常量
- 向量迭代编译为非常不同的指令
- STD ::向量迭代器类型和允许的操作
- 如何通过尺寸未知的2D向量迭代
- 向量迭代器 < 或 !=
- 如何通过共享_ptr向量迭代
- 如何通过向量迭代作为指针
- 通过向量迭代,而其他线程可能会对其进行修改
- 我如何通过C 中的字符串向量迭代
- 向量迭代器在新对象的 push_back() 之后不兼容