#include <iostream>
#include <vector>
usingnamespace std;
auto test() {
vector<int> vi = { 2, 4, 6 };
return vi.begin();
}
int main()
{
auto p = test();
cout << *p << endl;
return 0;
}
When we dereference vi.begin();, it gives the value 2, but after sending it to p in main(), dereferencing p doesn't match, while both are pointers to int!
Returning an iterator to a local object is kinda like returning a pointer to a local object.
Once the test function ends, the vector vi no longer exists. Any pointer or iterator to it is invalidated, and shouldn't be used.
When you initialize p, vi has no contents, so vi.begin() is the same as vi.end(). You don't add contents to vi until you check vEnd(). When you do add the contents, p is already at the end of the vector.