【问题标题】:C++ Own Iterator [closed]C ++自己的迭代器[关闭]
【发布时间】:2015-02-12 06:16:51
【问题描述】:

我的 C++ 代码有点问题。我有链接列表(下图),我需要为自己的(学校作业)制作一个迭代器..

list http://www.attanon.eu/list.png

我在列表变量中包含头、最后和实际节点。

我的类迭代器是这样的

class iterator
{
    Node* _node;
public:
    iterator(Node* node) : _node(node){}
    ~iterator(){ _node = nullptr; }

    iterator& operator=(const iterator& other)
    {
        _node = other._node;
        return *this;
    }
    bool operator==(const iterator& other)
    {
        if (_node == nullptr || other._node == nullptr)
        {
            return false;
        }
        else
        {
            return _node->_data == other._node->_data;
        }
    }
    bool operator!=(const iterator& other)
    {
        if (_node == nullptr || other._node == nullptr)
        {
            return false;
        }
        else
        {
            return _node->_data != other._node->_data;
        }
    }

    iterator& operator++() // prefix
    {
        if (_node != nullptr)
        {
            _node = _node->_next;
        }
        return *this;
    }
    iterator operator++(int) // postfix
    {
        iterator temp(*this);
        ++(*this);
        return temp;
    }
    T& operator*() // dereference
    {
        return _node->_data;
    }
    T* operator->() // šipková notace
    {
        return &*(List<T>::iterator)*this;
    }
};

我需要让方法开始和结束以遍历列表。

我尝试过这种方式,但是通过这个实现我没有得到列表的最后一个节点。

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

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

谁能帮我制作这两种方法?

附:对不起我的英语,我知道这不好。

感谢您的帮助

已编辑:

我的 Node 类是这样的

class Node
{
public: 
    T _data;
    Node* _next;
};

我用这个循环进行测试..

for (List<int>::iterator it = list->begin(); it != list->end(); it++)
{
    std::cout << *it << std::endl;
}

【问题讨论】:

    标签: c++ linked-list iterator


    【解决方案1】:

    结束迭代器应该指向“过去的”元素,而不是实际的最后一个元素。所以你真的应该有:

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

    然后将operator== 实现为:

    bool operator==(const iterator& other) { return _node == other._node; }
    bool operator!=(const iterator& other) { !((*this) == other); }
    

    让它接受nullptr

    【讨论】:

    • 我找到了这种方式,但是我可能需要重新设计我的迭代器运算符,因为它没有显示任何想法。
    • @JAttanonRadar “它什么也没显示”是什么意思?
    • 如果我使用测试功能,它不会打印列表中的数据..
    • 如果我使用你的实现操作符,它是循环的。
    • @JAttanonRadar 请go here,粘贴您的整个代码(包括main)并在此处分享链接。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-20
    • 2010-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-13
    • 2015-05-26
    相关资源
    最近更新 更多