C++ list iterator arithmetic?

2020-07-26 15:36发布

问题:

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?

回答1:

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)


回答2:

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.