Reputation: 455
I'm trying to create a set of loops with iterators and I'm having trouble with some iterator arithmetic (that I thought was possible but is not working).
Below is some code:
for (list<Term>::iterator itr = final.begin(); itr != final.end(); itr++) {
for(list<Term>::iterator j = itr + 1; j != final.end(); j++) {
cout << itr->term << " " << j->term;
if(itr->term == j->term) {
//Do stuff
}
}
}
What I am trying to do is have j start at the next place in the queue along from itr. The reason for this is I don't want to check the first item against itself. The error itself comes from the part in the code where I have specified itr + 1
. Now I was sure with pointers you could do arithmetic like this, why is it not working with the list iterator (which is essentially the same thing?)
The error I am getting from my IDE is as follows: main.cpp:237:48: error: no match for ‘operator+’ in ‘itr + 1’
. Again I thought you could do this sort of arithmetic on iterators so I'm not really sure what to do to make this work, is there an alternate implementation I could try?
Upvotes: 2
Views: 6707
Reputation: 55897
list
has bidirectional iterators, that doesn't support operator +
. You can use std::advance
, or std::next
in C++11.
for (list<Term>::iterator j = next(itr); j != final.end(); ++j)
or
list<Term>::iterator j = itr;
advance(j, 1); // or ++j
for (; j != final.end(); ++j)
Upvotes: 6
Reputation: 1078
list
iterators are not random access so you cannot do +
with them. They are bidirectional iterators so the only movement operations you can do are --
and ++
. You can either make a copy and use ++
on it, or make a copy and std::advance(it, 1)
.
For C++11 there is also std::next
which gives you it + 1
, without you having to explicitly make a named copy like you do with the others.
Upvotes: 7