Reputation: 97
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.
Upvotes: 0
Views: 1245
Reputation: 118007
You could use range-based for-loops and structured bindings:
for(auto& inner : adjList) {
for(auto& [first, second] : inner) {
first = ...;
second = ...;
}
}
Upvotes: 4
Reputation: 7100
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
}
}
}
Upvotes: 1
Reputation: 33944
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.
Upvotes: 2
Reputation: 680
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
}
}
Upvotes: 1