我是一个初学者,现在我正在尝试实现包含函数begin()的类链接列表。该函数很好地返回了列表中的第一个元素,但是我想做的是在下一个位置返回迭代器,例如:
List<int>::iterator iter2 = a.begin() + 2; // or iter2 = iter2 + 1; cout <<iter2->data;
[输出像21213123这样是垃圾的地方。
所以在这里我想我应该使用运算符重载+,这是我的功能:
template<class T> Node<T>* operator+(const Node<T>& iter, const int& pos) { cout << "in"; for testing, but seems that doesnt even entry here return NULL; }
那么有人可以帮助我吗?非常感谢]]
P.S:这是类Node
template<class T> class Node { public: T data; Node* next; Node() :data(0), next(NULL) {} Node(T val, Node<T>* pointer = NULL) :data(val), next(pointer) {} };
和列表类
template<class T> class List { public: typedef Node<T>* iterator; typedef const Node<T>* const_iterator; //constructors List() { item = NULL; counter = 0; } explicit List(int val) :counter(1) { item = new Node<T>(val); } ~List() { // to be made } //public functions int size() { return counter; } iterator begin() { return item; } iterator end() { iterator last = item; while (last->next != NULL) { last = last->next; } return last; } void push_front(const int& val) { iterator newNode = new Node<T>(val, item); item = newNode; counter++; } void append(const int& val) { iterator newnode = new Node<T>(val); newnode->next = NULL; iterator last = item; if (item == NULL) { item = newnode; return; } while (last->next != NULL) last = last->next; last->next = newnode; counter++; } int operator[](const int&); private: iterator item; int counter; };
我是一个初学者,现在我正在尝试实现包含函数begin()的类链接列表。该函数很好地返回了列表中的第一个元素,但是我想做的是...
让我们来看看您的begin
函数:
typedef Node<T>* iterator;
iterator begin() {
...
}
iterator
对于链接列表不能是指针,它需要是这样的:
struct iterator
{
typedef int difference_type;
typedef T* pointer;
typedef T& reference;
typedef iterator_category std::bidirectional_iterator_tag
iterator();
iterator& operator++();
iterator& operator--();
iterator operator++(int);
iterator operator--(int);
T& operator*();
T* operator->();
bool operator==(iterator rhs) const;
bool operator!=(iterator rhs) const;
private:
iterator(Node*);
Node* node;
};