C++ nested iterators

nbubis picture nbubis · Feb 17, 2013 · Viewed 10.1k times · Source

Is it OK to have a nested iterator like the following?

for (vector<type>::iterator i = list.begin(); i != list.end(); ++i) {
    for (vector<type>::iterator j = i; j != list.end(); ++j) {
        ...
    }
}

Note that j starts at i, and not list.begin(). Since the iterator is random access, can I guarantee that both i and j will have the same order? is there a better way of doing this?

Answer

Rafał Rawicki picture Rafał Rawicki · Feb 17, 2013

Your code is correct.

Both iterators will have the same order and incrementing j doesn't affect i as long as you don't make any operation that invalidates iterators (for example erasing from or pushing to vector).