iterator迭代器怎么写
时间: 2023-10-13 22:14:24 浏览: 48
迭代器是一种访问容器中元素的方法,它允许用户遍历容器中的元素。在C++中,迭代器是一个类,它包含一些方法,用于访问容器中的元素。下面是一个简单的迭代器类的示例:
```
template<typename T>
class Iterator {
public:
Iterator(T* ptr) : ptr_(ptr) {}
Iterator operator++() {
ptr_++;
return *this;
}
bool operator!=(const Iterator& other) const {
return ptr_ != other.ptr_;
}
T& operator*() {
return *ptr_;
}
private:
T* ptr_;
};
```
上述迭代器类中包含了三个运算符重载函数:
- `operator++`:用于将迭代器指向容器中的下一个元素。
- `operator!=`:用于比较两个迭代器是否相等。
- `operator*`:用于获取当前迭代器指向的元素。
这个迭代器类的构造函数接受一个指向容器中元素的指针,并将它存储在迭代器类中。在使用迭代器时,用户可以通过调用`operator++`方法将迭代器指向容器中的下一个元素,然后使用`operator*`方法获取当前元素的值。当迭代器到达容器的末尾时,`operator!=`方法将返回false,从而停止迭代。
使用上述迭代器类,我们可以遍历一个容器,例如一个向量:
```
#include <iostream>
#include <vector>
int main() {
std::vector<int> vec = {1, 2, 3, 4, 5};
Iterator<int> begin(&vec[0]);
Iterator<int> end(&vec[vec.size()]);
for (Iterator<int> it = begin; it != end; ++it) {
std::cout << *it << " ";
}
return 0;
}
```
在上述代码中,我们首先创建一个包含一些整数的向量。然后,我们创建了两个迭代器,一个指向向量的第一个元素,另一个指向向量的末尾。最后,我们使用for循环遍历整个向量,并使用迭代器类中的方法获取每个元素的值。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)