【发布时间】: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& 的引用。
-
(为了使引用的非代码部分看起来不像代码,请将它们放在/嵌套在块引号中。您呈现观察到的行为:必需的行为是什么?)