C++ 如何在函数内创建和返回迭代器?

Cs *_*ast 3 c++ iterator

我尝试编写一个函数,该函数接收列表和索引,并将迭代器返回到从该索引开始的列表。

功能:

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);
}
Run Code Online (Sandbox Code Playgroud)

当我调用函数来获取迭代器时,我确实在正确的索引处获得了我想要的第一个元素,但是当我在迭代器上执行“++”时,它只是跳出了列表,而不是转到下一个元素。

代码:

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

输出:

20
74211408
Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

Bat*_*eba 7

您需要通过引用来传递容器begin_it_at_index。否则,将进行值复制,并且返回的迭代器将无效,因为list_to_iterate_on函数中的局部超出范围。

那是,

template<class T>
typename std::list<T>::iterator begin_it_at_index(
    list<T>& list_to_iterate_on,
    const int index
)
Run Code Online (Sandbox Code Playgroud)

是一个修复。