Reputation: 33
I get a problem when I was doing some practice of "c++ prime", there is something wrong with iterator end(). So I write a test file, and its code is below:
int main (void)
{
vector<int> v(10);
auto c = v.end();
return 0;
}
What makes me surprise is the value of c is not 10, but a strange number. Here is my debug result:
What's the reason of this problem? Is it due to the compiler? I use "g++ -g -Wall -std=c++14" to compile.
Upvotes: 0
Views: 1714
Reputation: 234645
The type of v.end()
is a std::vector<int>::iterator
. Essentially a vector iterator is a pointer to an element of that vector.
v.end()
points to memory one element past the end of the vector. C++ allows you to store that value (due to the one-past-the-array-rule) and compare it with other pointers in your vector. That's why you can use it as a stopping point in your for
loop.
What you see in your output is essentially a cout
-style stringification which is the pointer address.
C++ does not allow you to deference v.end()
. That would be undefined behaviour.
Upvotes: 3
Reputation: 9619
The iterator::end
points to a location one past the last element in the container. So the address that it points to, in your case, is the one which is after the address that stores the 10th element of your vector
.
Moreover, looks like you are trying to access the value of the iterator, which is the address in the memory it is pointing to. You need to dereference
it in order to get the value it points to (not applicable for iterator::end
).
Upvotes: 7