C++链表迭代器类
C++ Linked List Iterator Class
我为一个项目创建了一个单独的链表,现在需要创建一个自定义的Iterator类。我的链表中有一个嵌套类,它定义了我的迭代器。我已经编写了大部分课程,但对如何实现一些函数感到困惑。我的问题如下:
-请看我的end()函数。我将其设置为Iterator类的默认构造函数,因此迭代器中的currentNode变量默认为NULL。这是否正确实施?
-我应该如何重载Iterator类中的->运算符?
class SSLL_Iter : public std::iterator<std::forward_iterator_tag, T>
{
public:
typedef T value_type;
typedef std::ptrdiff_t difference_type;
typedef T& reference;
typedef T* pointer;
typedef std::forward_iterator_tag iterator_category;
typedef SSLL_Iter self_type;
typedef SSLL_Iter& self_reference;
private:
Node* currentNode;
public:
explicit SSLL_Iter( Node* start = NULL) : currentNode( start ) {} //****************complete
SSLL_Iter( const SSLL_Iter& src ) : currentNode( src.currentNode ) {} //****************complete
reference operator*() const { //****************complete
T& temp = (currentNode->data);
return temp;
}
pointer operator->() const {} //*******??????????????????
self_reference operator=( const SSLL_Iter& src ) { //****************complete
this->here = src.here;
return *this;
}
self_reference operator++() { // preincrement //****************complete
currentNode = currentNode->next;
return *this;
}
self_type operator++(int) { // postincrement //****************complete
self_type temp = (*this);
++(*this);
return temp;
}
bool operator==(const SSLL_Iter& rhs) const { //****************complete
return (this->currentNode == rhs.currentNode);
}
bool operator!=(const SSLL_Iter& rhs) const { //****************complete
return (this->currentNode != rhs.currentNode);
}
}; // end SSLL_Iter
typedef std::size_t size_t;
typedef T value_type;
typedef SSLL_Iter iterator;
//typedef Const_SSL_Iter const_iterator;
SSLL() {}
SSLL(const SSLL& src ) {
for(int i = 0; i < src.size(); ++i) { // populate this SSLL with copies of the other SSLL's contents
this->push_back(src.item_at(i));
}
}
~SSLL() {
if(!is_empty()) {
clear();
}
}
iterator begin() { return SSLL_Iter( head ); }
iterator end() { return SSLL_Iter(); }
return &*(*this);
是一个不错的operator->
。
您的SSLL
类可能没有有效的at
,所以不要在复制构造函数中使用它。相反,创建一个SSLL
template<class Iterator> void append(Iterator s, Iterator f)
,并根据它实现SSLL(const SSLL& src)
如果您支持C++11,请考虑将Node
的next
节点替换为std::unique_ptr<Node>
。对指向SSLL
根目录中第一个Node
的指针执行相同操作。现在,内存管理几乎是自动处理的。更改后,您可能需要在迭代器中使用.get()
。这也消除了析构函数的主体,使移动构造函数=default
正确(除非你在计算节点)等。
相关文章:
- 我当前实现的双向链表类是否需要重构迭代器 end() 功能?
- C++嵌套的迭代器类(在链表类中)Insert_After函数
- std::filesystem::directory_迭代器链接器问题(C++17)
- C++链表最后一个元素的迭代器?
- 如何实现双向链表的迭代器?
- 使用迭代从链表向后打印字符串
- 迭代器关系运算符出错(带单独链接和迭代器的自定义哈希表)
- 在链表上实现随机访问迭代器
- 后缀运算符链表泛型节点迭代器
- 链表迭代器实现C++
- 迭代器作为 C++ 中链表类之外的单独类
- 链表常量迭代器
- 双链表迭代器实现的问题
- 链表迭代器模板中的编译错误
- 迭代器实现 -(链表队列)
- 返回链表的正确迭代器类型
- C++链表迭代器类
- 需要帮助编码迭代器的循环链表在c++
- C++通用链表和迭代器
- 自定义双链表迭代器