2

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?

nbubis
  • 2,304
  • 5
  • 31
  • 46

4 Answers4

4

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

Community
  • 1
  • 1
Rafał Rawicki
  • 22,324
  • 5
  • 59
  • 79
3

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

us2012
  • 16,083
  • 3
  • 46
  • 62
  • 3
    +1 for mentioning the choice of the name of a standard container as the name of a variable. I've been seeing this very often lately (`array`, `list`, `map`, etc.). – Andy Prowl Feb 17 '13 at 18:41
  • the actual name is of course not list, just shortened it so that it would be easier to read in this forum. – nbubis Feb 17 '13 at 18:49
3

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)

Joseph Mansfield
  • 108,238
  • 20
  • 242
  • 324
1

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

Mikhail Vladimirov
  • 13,572
  • 1
  • 38
  • 40