与来自STL的列表相比,怪异的自己的迭代器behviour

时间:2016-05-31 11:21:54

标签: c++ stl

您好我已经实现了自己的列表和迭代器。

我的主要代码是:

List<int> myList;
myList.push_back(1);
myList.push_back(2);
myList.push_back(3);

cout << std::string(30, '-') << endl;
//this shows 1 2
for(List<int>::iterator it = myList.begin() ; it != myList.end() ; ++it){
    cout << *it << " ";
}
cout << endl;

//The same using stl shows 1 2 3 !!!???
list<int> myListSTL;
myListSTL.push_back(1);
myListSTL.push_back(2);
myListSTL.push_back(3);
cout << std::string(30, '-') << endl;
for(list<int>::iterator it = myListSTL.begin() ; it != myListSTL.end() ; ++it){
    cout << *it << " ";
}
cout << endl;

我为自己的迭代器实现了所有方法。 对于我自己的实现输出是:1 2 对于来自STL实现的列表,输出为:1 2 3

1)我的begin()方法:

template<class T>
typename List<T>::iterator List<T>::begin(){
    return iterator(head);
}

2)我的end()方法:

  template<class T>
typename List<T>::iterator List<T>::end(){
    Node * current = head;
    while(current->next)
        current = current->next;
    return iterator(current);
}

3)重载运算符!=

template<class T>
const bool List<T>::iterator::operator!=(const iterator & it){  
    return (node != it.node);
}

4)重载preincrement运算符:

template<class T>
typename List<T>::iterator List<T>::iterator::operator++(){
    if(node->next){
        node = node->next;      
    }
    return iterator(node);
}

我整整分析这一天,我不知道我能做错什么。 Thak You提前获得任何帮助!

3 个答案:

答案 0 :(得分:0)

你的end迭代器需要指向超出数据最后一个元素的东西,以便与STL的end概念保持一致(所以目前你只是一个简称)。

答案 1 :(得分:0)

您的end函数应该返回一个超过列表中结束项的迭代器。目前它返回最后一项,因此您不会看到所有列表项。

迭代器的正确修复应该依赖于节点类的实现。例如,gcc版本如下所示:

  iterator
  end() _GLIBCXX_NOEXCEPT
  { return iterator(&this->_M_impl._M_node); }

答案 2 :(得分:0)

你的end方法应该返回列表的结尾的迭代器(不是最后一个元素的迭代器),所以通常:

template<class T>
typename List<T>::iterator List<T>::end(){
    Node * current = head;
    while(current->next)
        current = current->next;
    return iterator(current);
}

应该简单地成为这个:

template<class T>
typename List<T>::iterator List<T>::end(){
    return iterator(0);
}

然后移除operator++中的签入,以便++it如果您在最后一个元素(这是您想要的)上,则会iterator(0)

template<class T>
typename List<T>::iterator List<T>::iterator::operator++(){
    node = node->next;      
    return iterator(node);
}