简体   繁体   中英

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

i would like to ask how do you iterate over vector of vector of pair? supposed i have the following.

typedef pair<int,int> Pair;
vector<vector<Pair> > adjList;

and then i tried to iterate using the following code:

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

however it returns an error

'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 > >}’)'. 

anyone knows? thanks.

You could use range-based for-loops and structured bindings:

for(auto& inner : adjList) {
    for(auto& [first, second] : inner) {
        first = ...;
        second = ...;
    }
}

Your issue is you are using the first elements, iterator for the outer list here:

for(i = adjList[N].begin(); i != adjList[N].end(); ++i)

where you clearly meant for i to be an iterator over the outer list. You probably meant to do this:

for(i = adjList.begin(); i != adjList.end(); ++i)

But for ease and readability, use a range based for loop:

for (const auto& row : adjList) {
    for (const auto& pair : row) {
       // print pair.second or whatever

Remove the 2 const s if you want to edit the pair.

for(i = adjList[N].begin(); i != adjList[N].end(); ++i)

This iterates over the nth inner vector not over the outer vector beside i type is not consistent with the type of adjList[N].begin() and what's that 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
        }
    }

}

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){}
}

And if your project uses C++11 or later, use auto to simplify typedef ;

for(auto i = adjList.begin(); i != adjList.end(); i++){
   for(auto itr = (*i).begin(); itr != (*i).end(); itr++){
  }
}

Moreover, with for-range:

for(auto & i:adjList){
  for(auto &j: i){
    // xxxx
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM