Nathaniel Bubis
Nathaniel Bubis

Reputation: 2295

C++ nested iterators

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?

Upvotes: 2

Views: 12902

Answers (4)

Mikhail Vladimirov
Mikhail Vladimirov

Reputation: 13900

This should work fine. Vector stores elements in order, and both iterators will obey this order.

Upvotes: 1

Joseph Mansfield
Joseph Mansfield

Reputation: 110768

That's perfectly fine. Random access doesn't mean random order. It means that you can jump through the container by using additive operators (+ and -) on your iterator. For example, with a random access iterator it, you can do it + 10. For an non-random access iterator, you would have to do it++ 10 times to achieve the same effect. (the std::advance function will encapsulate this for you though)

Upvotes: 3

us2012
us2012

Reputation: 16263

This is absolutely fine as long as you don't do anything inside the loops that might invalidate iterators.

(As an aside, list is a questionable name for a std::vector in my opinion.)

Upvotes: 3

Rafał Rawicki
Rafał Rawicki

Reputation: 22700

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).

Upvotes: 4

Related Questions