如何为自定义 class 实现迭代器?

How to implement an iterator for a custom class?

对于作业,我们必须创建自定义列表 class。其中一个功能是将一个元素插入到列表的中间。到目前为止,

 template<class T>
 class MyList : public list<T> {
 public:
   void addInMiddle(const T&);
   void insertInSortedOrder(const T&);
   void printList();
 };


template<class T>
void MyList<T>::addInMiddle(const T& x) {

 list<T>::iterator it = this->begin();

 int location = (this->size()) / 2;     //where we want to insert the new element
 for (int i = 0; i < location; i++) {
     it++;
 }
 this->insert(it,x);
}


 int main()
{
MyList<int> list1;
list1.push_back(1);
list1.push_back(2);
list1.push_back(3);
list1.push_back(4);
list1.addInMiddle(5);
list1.printList();
return 0;
}

程序编译显示1,2,3,4。它实际上应该显示 1,2,5,3,4。我不认为迭代器在工作。有什么想法吗?

一旦我在 list<T>::iterator 前面添加 typename,您的代码对我来说工作正常,因为迭代器的类型取决于 T 模板参数的类型,例如:

typename list<T>::iterator it = this->begin();

Online Demo

Where and why do I have to put the "template" and "typename" keywords?

或者,您可以(并且应该)只使用 auto 代替:

auto it = this->begin();

Online Demo


话虽这么说,标准 C++ 容器并不打算继承(没有虚拟析构函数等)。你应该使用封装而不是继承,例如:

template<class T>
class MyList {
private:
    list<T> m_list;
public:
    void addToBack(const T&);
    void addInMiddle(const T&);
    void insertInSortedOrder(const T&);
    void printList();
};

template<class T>
void MyList<T>::addToBack(const T& x) {
    m_list.push_back(x);
}

template<class T>
void MyList<T>::addInMiddle(const T& x) {

    list<T>::iterator it = m_list.begin();
    // or: auto it = m_list.begin();

    int location = m_list.size() / 2;     //where we want to insert the new element
    for (int i = 0; i < location; i++) {
        it++;
    }

    m_list.insert(it, x);
}

int main()
{
    MyList<int> list1;
    list1.addToBack(1);
    list1.addToBack(2);
    list1.addToBack(3);
    list1.addToBack(4);
    list1.addInMiddle(5);
    list1.printList();
    return 0;
}

Online Demo