简体   繁体   中英

Function returning iterator to vector

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM