【问题标题】:C++ How to create and return an iterator inside a function?C ++如何在函数内创建和返回迭代器?
【发布时间】:2022-11-02 19:19:44
【问题描述】:

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

功能:

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);
}

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

编码:

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

输出:

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

我究竟做错了什么?

【问题讨论】:

    标签: c++ iterator


    【解决方案1】:

    你需要通过容器引用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
    )
    

    是一个修复。

    【讨论】:

      猜你喜欢
      • 2013-11-08
      • 2015-02-23
      • 1970-01-01
      • 2018-05-20
      • 1970-01-01
      • 2018-04-05
      • 1970-01-01
      • 2012-08-07
      • 1970-01-01
      相关资源
      最近更新 更多