blu*_*kin 6 c++ iterator linked-list post-increment
我想弄清楚这里有几件事:
如何为下面的类实现迭代器?
#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;?
}
}
Run Code Online (Sandbox Code Playgroud)这不是演示运算符重载或迭代器的好例子.
Kar*_*tel 11
您没有operator++
为Node类实现; 你为迭代器实现它.迭代器类应该是一个单独的类.
并且,请不要通过做出假设破坏你的模板(因为val
是T
,你的构造函数应该接受a T
,而不是a int
).另外,不要忽略int
operator ++ 的参数:它是一个用于区分预增量实现和增量后实现的虚拟对象.
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.
}
Run Code Online (Sandbox Code Playgroud)
从提供适当的数据封装,内存管理等方面来说,这还有很长的路要走.制作一个合适的链表类并不容易.这就是标准库提供的原因.不要重新发明轮子.