当我尝试尊重常量迭代器时出现错误。我希望能够在findntoLast迭代器中返回迭代器,而不是通过从新引用到链表的末尾进行迭代来显示链表的值。

//Main.cpp
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
#include <list>
#include <cstdlib>
#include <forward_list>

using std::forward_list;
typedef std::forward_list<int>::const_iterator constListIt;

#include "LinkedListQ2.h"

int main()
{
    forward_list<int> myList;
    for ( size_t i = 0; i < 20; i++)
    myList.push_front(i);
    constListIt myListIt = myList.begin();
    for( myListIt; myListIt !=  myList.end(); myListIt++)
    cout << *myListIt << endl;
    constListIt newListIt = findntoLast(myList, 5);

    while(newListIt != myList.end())
    {
        cout << *newListIt << endl;
    newListIt++;
    }
    return 0;
}

/* LinkedListQ1.h*/
#ifndef LINKED_LIST_Q1_H_
#define LINKED_LIST_Q1_H_
#include <iterator>
using std::next;
#include <cstdlib>
#include <forward_list>
using std::forward_list;

template<typename T>
typename std::forward_list<T>::const_iterator findntoLast( forward_list<T> sList,  size_t count )
{
     typedef std::forward_list<T>::const_iterator sListIterator;
         sListIterator newList = sList.begin();

    for(size_t increment = 0; increment < count -1; increment++)
    {
        newList++;
    }

    return newList;
}
#endif

最佳答案

template<typename T>
typename [...]::const_iterator findntoLast( forward_list<T> sList, [...])


该参数按值传递。这意味着您的findntoLast在原始列表的副本上可用。函数返回时,该副本将被销毁。因此,引用它的所有迭代器都将变为无效。

通过const引用获取列表,该问题应该消失了。

您还缺少typedef中的typename

typedef typename std::forward_list<T>::const_iterator sListIterator;


最后,看一下std::advance,它已经完成了您需要的工作(如果您更改了基础的集合类型,它将利用随机访问迭代器)。

10-06 10:43
查看更多