c ++我不知道为什么这个迭代器不能在我的代码中工作

时间:2016-12-10 07:10:49

标签: c++ c++14

#include <iostream>
#include <cstddef>

template <typename T>
class list
{
    struct Node
    {
        T data;
        Node* next;
        Node(T d, Node* n)
            : data(d), next(n)
        {}
    };

    Node* head;

public:
    list()
        : head(nullptr)
    {}

    void push_front(T d)
    {
        head = new Node(d, head);
    }

    class iterator
    {
        Node* current;

    public:
        typedef T value_type;

        iterator(Node* init = nullptr)
            : current(init)
        {
//            std::cout<<"init iterator"<<std::endl;
//            std::cout<<current->data<<std::endl;
        }


        iterator& operator++()
        {
            current = current->next;
            return *this;
        }

        T& operator*()
        {
            current->data;
        }

        bool operator!=(const iterator& i)
        {
            return (current != i.current);
        }

        bool operator==(const iterator& i)
        {
            return (current == i.current);
        }
    };

    iterator begin()
    {
        return iterator(head);
    }

    iterator end()
    {
        return iterator(nullptr);
    }

};

int main(void)
{

    list<int> a;
    for(int i = 1; i<=10; ++i) {
        a.push_front(i);
    }

    for(auto it = a.begin(); it != a.end(); ++it) {
        std::cout<<*it<<std::endl;
    }

    return 0;
}

输出:

15393072
15393040
15393008
15392976
15392944
15392912
15392880
15392848
15392816
15392784

&#34; a.push_front(ⅰ);&#34;没关系。

但是,也许迭代器是错误的.... 为什么这段代码错了?帮帮我〜

我使用c ++ 14编译器和linux

1 个答案:

答案 0 :(得分:0)

T& operator*()
    {
        current->data;
    }

应该是

T& operator*()
    {
        return current->data;
    }

一切都解决了〜