Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
}
like image 444
BODAPATI NIRUPAMA SAI Avatar asked May 14 '26 01:05

BODAPATI NIRUPAMA SAI


1 Answers

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();
}
like image 55
R Sahu Avatar answered May 15 '26 15:05

R Sahu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!