c++ - 增量运算符/迭代器实现

标签 c++ iterator linked-list post-increment

我想在这里弄清楚几件事:

  1. 如何为具有指向下一个节点的指针的节点类编写递增运算符?
  2. 如何为如下类实现迭代器?

    #include <iostream>
    #include <vector>
    using namespace std;
    
    template <typename T>
    class Node {
    public:
        Node(int i=0):val(i) {}
        Node*& operator++(int i=0) {return next;};
    
        T val;
        Node *next;
    };
    
    //================================================
    int main() {
    
        Node<int> *head, *tmp1, *tmp2;
    
        tmp1 = new Node<int>(0); 
        head = tmp1;
    
        for (int i=1; i<10; ++i) {
    
            tmp2 = new Node<int>(i);
            tmp1->next = tmp2;
            tmp1 = tmp2;
        }
    
        while (head != NULL) {
    
            cout << head->val << " '";
            head = head->operator++(0);    //How do I make it work with ++head;?
        }
    }
    

这不是演示运算符重载或迭代器的好例子。

最佳答案

您没有为 Node 类实现 operator++;你为迭代器实现它。迭代器类应该是一个单独的类。

请不要通过假设破坏您的模板(因为 val 是一个 T,您的构造函数应该接受一个 T,不是 int)。另外,不要像那样忽略 operator++ 的 int 参数:它是一个虚拟变量,用于区分预增量实现和后增量实现。

template <typename T>
struct Node {
    T val;
    Node *next;

    Node(const T& t = T()) : val(t) {}
};

template <typename T>
struct node_iter {
    Node<T>* current;
    node_iter(Node<T>* current): current(current) {}

    const node_iter& operator++() { current = current->next; return *this; }
    node_iter operator++(int) {
        node_iter result = *this; ++(*this); return result;
    }
    T& operator*() { return current->val; }
};

int main() {
    // We make an array of nodes, and link them together - no point in
    // dynamic allocation for such a simple example.
    Node<int> nodes[10];
    for (int i = 0; i < 10; ++i) {
        nodes[i] = Node<int>(i);
        nodes[i].next = (i == 9) ? nodes + i + 1 : 0;
    }

    // we supply a pointer to the first element of the array
    node_iter<int> test(nodes);
    // and then iterate:
    while (test.current) {
        cout << *test++ << " ";
    }
    // Exercise: try linking the nodes in reverse order. Therefore, we create 
    // 'test' with a pointer to the last element of the array, rather than 
    // the first. However, we will not need to change the while loop, because
    // of how the operator overload works.

    // Exercise: try writing that last while loop as a for loop. Do not use
    // any information about the number of nodes.
}

距离提供适当的数据封装、内存管理等还有很长很长的路要走。制作一个适当的链表类并不容易。这就是为什么标准库提供了一个。不要重新发明轮子。

关于c++ - 增量运算符/迭代器实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4329677/

相关文章:

c++ - boost::intrusive::list with the auto-unlink hook:我可以使用列表中的值来确定列表是否只有一个元素吗?

c++ - 如何使用 C++ 在 Windows 和 Linux 中获取 iSCSI 启动器名称

c++ - 类 SUP 和在 C++ 的 SUP 中定义的类 SUB 之间有什么关系?

java - 按值传递 链表

java - 如何处理自定义链表中的对象?

c++ - 试图创建一个对象 vector

c++ - 如何在C++上独立运行函数

php - 是否可以将 Doctrine2 批处理与 Twig 的 for 标签无缝使用?

python - 在Python中跳过yield

c - C 中的链表,链表构造正确吗?