what is the best way of returning an iterator for the below code?In the below code it is not giving correct output for this line
cout<<*p<<endl;
#include<iostream>
#include<vector>
using namespace std;
vector <int> :: iterator int_begin(vector <int> V);
int main()
{
vector <int> V;
V.push_back(3);
V.push_back(1);
vector <int> :: iterator p=int_begin(V);
cout<<*p<<endl;
return 0;
}
vector <int> :: iterator int_begin(vector <int> V)
{
cout<<*V.begin()<<endl;
return V.begin();
}
You are passing the object by value to int_begin(). What you get back is an iterator to a std::vector that does not live past the function call. Hence, in the calling function, the iterator is invalid.
Pass the object by reference.
vector <int> :: iterator int_begin(vector <int>& V) // Passed by reference
{
cout<<*V.begin()<<endl;
return V.begin();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With