如何std::list写一个iterator
时间: 2024-04-30 10:24:05 浏览: 16
可以使用以下代码来写一个std::list的iterator:
```
template<typename T>
class ListIterator {
public:
using iterator_category = std::bidirectional_iterator_tag;
using value_type = T;
using difference_type = std::ptrdiff_t;
using pointer = T*;
using reference = T&;
ListIterator(pointer ptr) : m_ptr(ptr) {}
reference operator*() const { return *m_ptr; }
pointer operator->() { return m_ptr; }
ListIterator& operator++() {
m_ptr = m_ptr->next;
return *this;
}
ListIterator operator++(int) {
ListIterator iterator = *this;
++(*this);
return iterator;
}
ListIterator& operator--() {
m_ptr = m_ptr->prev;
return *this;
}
ListIterator operator--(int) {
ListIterator iterator = *this;
--(*this);
return iterator;
}
bool operator==(const ListIterator& rhs) const {
return m_ptr == rhs.m_ptr;
}
bool operator!=(const ListIterator& rhs) const {
return m_ptr != rhs.m_ptr;
}
private:
pointer m_ptr;
};
```
这是一个模板类,可以用于任何类型的std::list。它包含了所有必要的iterator运算符,包括++、--、*和->。同时,它还包含了iterator_category、value_type、difference_type、pointer和reference这些类型别名,这些都是STL iterator所必需的。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)