Reputation: 13
I recently started learning about C++ iterators and pointers, and while messing around with some basic exercises I came upon a situation which I think is really unusual.
#include <iostream>
#include <vector>
#include <time.h>
#include <list>
#include <array>
using namespace std;
template<typename ITER>
void print_with_hyphens(ITER begin, ITER end){
cout << "End: " << *(end) << endl;
cout << "Begin: " << *begin << endl;
for(ITER it = begin; it != end; it++){
cout << *it << endl;
}
cout << endl << "Finished" << endl;
}
int main()
{
vector<int> v { 1, 2, 3, 4, 5};
list<int> l { 1, 2, 3, 4, 5};
print_with_hyphens(v.begin(), v.end());
print_with_hyphens(l.begin(), l.end());
// print_with_hyphens(a.begin(), a.end());
return 0;
}
And when I run it like this, I get this unusual result:
Now, the vector is returning a weird (random, if I'm not mistaken) value, because it's trying to access a value that doesn't exist, hence, "past the end" iterator. And it should be the same for lists, yet, the list is returning the value 5. Shouldn't it also return a "past the end" iterator?
Upvotes: 0
Views: 1523
Reputation: 385108
The phrase "past-the-end" in this context is abstract. It means the iterator is off the end of the logical sequence of elements in the container. It does not mean there is some literal bit of data located just after the container in memory that you can access and read.
Because it's "past-the-end" and doesn't refer to any actual element, dereferencing the end iterator is not permitted. By doing so, you get weird behaviours.
Upvotes: 2
Reputation: 4654
Things such as dereferencing an invalid iterator or accessing an out-of-bounds array index produce undefined behavior.
This means the C++ standard does not specify what should happen if you do it. Anything might happen, such as a segmentation fault, or getting a random value, depending on things like your standard library implementation and compiler.
Needless to say, programs should not rely on undefined behavior.
Upvotes: 2