如何在 c++ 中使用对向量的向量进行迭代?

How to iterate using vector of vector of pair in c++?

本文关键字:向量 迭代 c++      更新时间:2023-10-16

我想问你如何迭代对向量的向量? 假设我有以下内容。

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

如果要编辑对,请删除 2consts。


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 个内部向量而不是外部向量,旁边的类型iadjList[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
}
}
}