【问题标题】:c++ i don't know why this iterator not working in my codec++ 我不知道为什么这个迭代器在我的代码中不起作用
【发布时间】:2016-12-10 07:10:49
【问题描述】:
#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

"a.push_front(i);"没问题。

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

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

【问题讨论】:

  • 您的操作员*返回对数据 T& 的引用。
  • (为了使引用的非代码部分看起来不像代码,请将它们放在/嵌套在块引号中。您呈现观察到的行为:必需的行为是什么?)

标签: c++ c++14


【解决方案1】:
T& operator*()
    {
        current->data;
    }

应该是

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

一切都解决了~

【讨论】:

    猜你喜欢
    • 2021-03-11
    • 2020-09-19
    • 2014-01-17
    • 2020-01-11
    • 1970-01-01
    • 1970-01-01
    • 2021-10-19
    • 1970-01-01
    • 2011-05-22
    相关资源
    最近更新 更多