Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it valid to compare iterators which are got from the container separately?

Tags:

c++

stl

For example, it this expression valid in semantic?

container.begin() == container.begin();
like image 612
Thomson Avatar asked Jul 21 '10 02:07

Thomson


2 Answers

Yes, so long as neither iterator has been invalidated.

For example, the following would not be valid:

std::deque<int> d;

std::deque<int> begin1 = d.begin();
d.push_front(42);                   // invalidates begin1!
std::deque<int> begin2 = d.begin();
assert(begin1 == begin2);           // wrong; you can't use begin1 anymore.
like image 118
James McNellis Avatar answered Oct 05 '22 07:10

James McNellis


Yes, begin() will return the same iterator given a container instance, unless you change the container in some way (end() has this property as well). For example, std::vector::push_back() may cause the array to be reallocated to accommodate new elements.

like image 44
In silico Avatar answered Oct 05 '22 05:10

In silico