3

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();
}
1
  • 2
    You're returning an iterator of a temporary vector. Commented May 28, 2018 at 5:03

1 Answer 1

3

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();
}
Sign up to request clarification or add additional context in comments.

1 Comment

@BODAPATINIRUPAMASAI, you are welcome. Glad I was able to help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.