如何为自定义类实现迭代器?
对于作业,我们必须创建自定义列表类。其中一个功能是将元素插入列表的中间。到目前为止,
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。我认为迭代器不起作用。有什么想法吗?
For an assignment, we had to create custom list class. One of the functions is to insert an element into the middle of the list. So far I have,
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;
}
The program compiles and shows 1,2,3,4. It should actually show 1,2,5,3,4. I don't think the iterator is working. Any thoughts?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一旦我在
list::iterator
前面添加typename
,您的代码就可以正常工作,因为迭代器的类型取决于的类型>T
模板参数,例如:在线演示
参见我必须在哪里以及为什么必须放置“template”和“typename”关键字?
或者,您可以(并且应该)只使用 < code>auto 改为:
在线演示
话虽这么说,标准 C++ 容器并不打算被继承来自(无虚拟析构函数等)。您应该使用封装而不是继承,例如:
在线演示
Your code works fine for me once I add
typename
in front oflist<T>::iterator
, since the type of the iterator is dependent on the type of theT
template parameter, eg:Online Demo
See Where and why do I have to put the "template" and "typename" keywords?
Alternatively, you can (and should) just use
auto
instead:Online Demo
That being said, standard C++ containers are not intended to be inherited from (no virtual destructor, etc). You should use encapsulation instead of inheritance, eg:
Online Demo