Reputation: 7357
It's clear why we cannot assign const_iterator to just iterator.
std::vector<int> v;
std::vector<int>::iterator i = v.cbegin(); //no viable convertion
But the fact that they'are compare equal in the !=
operator standpoint seems very confusing.
std::vector<int> v;
for(int i = 0; i < 10; i++)
v.push_back(i);
for(std::vector<int>::const_iterator i = v.cbegin(); i!= v.end(); i++)
std::cout << *i << std::endl; //prints 0-9
what's the reason for such behavior of !=
operator?
Upvotes: 0
Views: 31
Reputation: 5044
Assigning a const iterator to an iterator would break const-correctness of the iterator. Consider:
typedef std::vector<int> seq;
const seq v;
seq::const_iterator = v.cbegin(); // Okay
// seq::iterator = v.begin(); // Not okay, sequence is const
If you could assign a const iterator to a simple iterator the above example would be able to manipulate the content of a const
sequence.
Comparing two iterators just tells you if they point to the same data (or the end/begin) of some sequence.
typedef std::vector<int> seq;
seq v;
const seq& cv = v;
cv.cbegin() == v.begin(); // Okay
cv.cbegin() != v.begin(); // Also okay
Here you have a sequence and a const
view of the same sequence. When comparing iterators of the two, two iterators pointing to the same data should compare equals.
Upvotes: 2