问题
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.find(500)
gave the result 6. Why am I getting this number?
#include<iostream>
#include<iterator>
#include<set>
#include<map>
int main()
{
int a[] = {1,2,3,4,5};
std::set<int> set1(a,a+sizeof(a)/sizeof(int));
for (std::set<int>::iterator itr=set1.begin();itr!=set1.end();++itr){
std::cout << *itr << std::endl;
}
//std::pair<std::set<int>::iterator, bool> ret;
//ret = set1.insert(1);
//std::cout << *(ret.first) << "first;second" << ret.second << std::endl;
std::set<int>::iterator itr1 = set1.begin();
set1.insert(itr1,100);
std::advance(itr1,3);
std::cout << *itr1 << std::endl;
std::cout << *(set1.find(500)) << std::endl;
std::cout << *(set1.end()) << std::endl;
}
回答1:
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.
回答2:
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.
回答3:
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!
回答4:
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:
来源:https://stackoverflow.com/questions/31351353/odd-values-printed-when-dereferencing-the-end-iterator-of-a-vector