I have a vector storing {1,2,3,4,5}. I tried to print *(vec.end())
and got back the result 6. I don\'t know how to explain this. Similarly, calling vec.fi
Never try to use end()
of any stl container because it does not point to a valid data. It always point to a chunk of memory that is located after the actual data. Use end()
only to check whether your iterator has come to end or not. This image clearly explains where end()
is located in default (non-reversed) range:
In C++ containers, the end
iterator gives an iterator one past the end of the elements of the container. It's not safe to dereference the iterator because it's not actually looking at an element. You get undefined behavior if you try to do this - it might print something sensible, but it might just immediately crash the program.
Hope this helps!
vec.end()
does not point to the last element, but somewhat "behind" the last one.
You are not accessing the last element in the vector. Instead you are dereferencing an "invalid" iterator, which is undefined behaviour and turns out to be an invalid index in the vector in this case.
vec.find
returns the end iterator if the searched element can not be found.
This line invokes undefined behavior:
std::cout << *(set1.end()) << std::endl;
It is undefined behavior to dereference the end()
iterator. Thus anything can be expected.