Home > Software engineering >  C How to create and return an iterator inside a function?
C How to create and return an iterator inside a function?

Time:11-03

I tried to write a function that receives a list and an index and returns an iterator to the list that starts at that index.

The function:

template<class T>
typename std::list<T>::iterator begin_it_at_index(list<T> list_to_iterate_on, const int index)
{
  return next(list_to_iterate_on.begin(), index);
}

When I called the function to get the iterator, I did get the first element I wanted at the correct index, but when I did " " on the iterator it just jumped out of the list instead of going to the next element.

The code:

list<int> temp = {10,20,50,100};
  for (auto it = begin_it_at_index(temp, 1); it != temp.end();   it)
  {
    cout << *it << endl;
  }

The output:

20
74211408
Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)

What am I doing wrong?

CodePudding user response:

You need to pass the container by reference to begin_it_at_index. Otherwise a value copy is taken, and the returned iterator is invalidated as the local list_to_iterate_on in the function goes out of scope.

That is,

template<class T>
typename std::list<T>::iterator begin_it_at_index(
    list<T>& list_to_iterate_on,
    const int index
)

is a fix.

  • Related