Re: strange behaviour of vector iterator
nicolaennio@gmail.com wrote:
i was using vector template when i found out a strange thing, i
managed to restrict the 'bug' in this code:
#include <cstdlib>
#include <iostream>
#include <vector>
using namespace std;
vector<int>::iterator _begin(vector<int> v){
You pass the vector by value. A copy is made. It's local to
the function. As soon as the function returns, it's destroyed.
BTW, the name "_begin" is reserved. You should not use it.
return v.begin();
Here you're trying to hold onto an iterator to a temporary vector.
As soon as this function returns, the iterator is invalid.
}
int main(int argc, char *argv[])
{
vector<int> v;
v.push_back(4);
vector<int>::iterator b = _begin(v);
printf("%d\n",*b);
Your program has undefined behaviour here since you're trying
to dereference an invalid iterator.
printf("%d\n",*_begin(v));
system("PAUSE");
return EXIT_SUCCESS;
}
actually output is the following:
0
4
while i was expecting:
4
4
i can't understand what happen wrong in the assignment
Nothing is wrong except that the value of the iterator you're
getting back from '_begin' is unusable.
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]