Jonathan Bouchard Jonathan Bouchard - 24 days ago 10
C++ Question

Return an iterator in reference

I'm trying to return an iterator in reference

void class::foo(vector<bar>::iterator& iterBar)
{
vector<bar> copy = GetVecBar();
iterBar = min_element(copy.begin(), copy.end(), [](const bar& a, const bar& b) { return a.GetInt() < b.GetInt(); });
}


This works but when it returns to main, the iterator points to something random.

In main:

vector<bar>::iterator iterBar;
Object.foo(false, iterBar);


Thanks for helping

Answer
vector<bar> copy = GetVecBar();

This declares a local object named copy in your function. This object gets destroyed when the function returns, like all objects in the function scope.

The function is then returning an iterator referencing some value in this vector. However, since the vector itself gets destroyed, when the function returns, the iterator is referring to a destroyed object, hence the results you are seeing.

It is not clear what GetVecBar() is from the code shown, but whatever it is, you need to change your code to search the actual vector, instead of a copy of it.

If your GetVecBar() is declared as returning a vector<bar> &, then this should be as simple as

vector<bar> &copy = GetVecBar();