#include <iostream>
// 定义链表节点
template <typename T>
struct MyListNode {
T data;
MyListNode* next;
MyListNode(const T& value) : data(value), next(nullptr) {}
};
// 定义MyList迭代器
template <typename T>
class MyListIterator {
public:
using iterator_category = std::forward_iterator_tag;
using value_type = T;
using difference_type = std::ptrdiff_t;
using pointer = T*;
using reference = T&;
MyListIterator(MyListNode<T>* node) : current(node) {}
T& operator*() const {
return current->data;
}
T* operator->() const {
return &(current->data);
}
MyListIterator& operator++() {
current = current->next;
return *this;
}
MyListIterator operator++(int) {
MyListIterator temp = *this;
++(*this);
return temp;
}
bool operator==(const MyListIterator& other) const {
return current == other.current;
}
bool operator!=(const MyListIterator& other) const {
return!(*this == other);
}
private:
MyListNode<T>* current;
};
// 定义MyList类
template <typename T>
class MyList {
public:
MyList() : head(nullptr) {}
~MyList() {
while (head) {
MyListNode<T>* temp = head;
head = head->next;
delete temp;
}
}
void push_back(const T& value) {
if (!head) {
head = new MyListNode<T>(value);
} else {
MyListNode<T>* current = head;
while (current->next) {
current = current->next;
}
current->next = new MyListNode<T>(value);
}
}
MyListIterator<T> begin() {
return MyListIterator<T>(head);
}
private:
MyListNode<T>* head;
};
确保迭代器满足STL要求的说明
- 迭代器类别:定义了
iterator_category
为std::forward_iterator_tag
,表明这是一个前向迭代器,满足STL对前向迭代器的基本要求,支持++
操作来移动到下一个元素。
- 类型定义:定义了
value_type
、difference_type
、pointer
和reference
,这些类型定义是STL算法使用迭代器时所需要的,保证了与STL算法的兼容性。
- 解引用操作:实现了
operator*
和operator->
,使得可以通过迭代器访问节点中的数据。
- 自增操作:实现了前置
++
和后置++
操作符,用于移动迭代器到下一个节点。
- 比较操作:实现了
operator==
和operator!=
,用于比较两个迭代器是否相等,这在STL算法中用于判断迭代器是否到达末尾等情况。