我試圖撰寫一個函式,它接收一個串列和一個索引,并將一個迭代器回傳到從該索引開始的串列。
功能:
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)
我究竟做錯了什么?
uj5u.com熱心網友回復:
您需要通過參考來傳遞容器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
)
是一個修復。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/525555.html
標籤:C 迭代器
上一篇:通過安全地最小化填充來優化類布局
