简体   繁体   English

函数将迭代器返回到向量

[英]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() . int_begin()值传递对象到int_begin() What you get back is an iterator to a std::vector that does not live past the function call. 你得到的是一个std::vector的迭代器,它不会通过函数调用。 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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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