Let's say I have an unordered_set<int> S
.
I know I can iterate through S with:
void iterate(){
for (const auto& elem: S) {
cout<<elem<<endl;
}
}
My question is: if I call iterate()
and it prints a certain sequence of numbers, is it guaranteed that if I call iterate()
as many times as I want, it will always print the same sequence?
Yes, as long as S
is not modified. [container.requirements.general]p6:
begin()
returns an iterator referring to the first element in the container.
The use of the definite article "the" implies that there's only one such "first element". Therefore, multiple calls to begin()
on the same (unchanged) container must return iterators referring to the same element.
Additionally, all container iterators are required to be at least forward iterators (see Table 64 in the same subclause).
The rest falls out the forward iterator requirements in [forward.iterators], in particular:
Since you start with equal iterators, every step of the iteration must produce equal iterators, which must refer to the same element in the container.