赞
踩
迭代器(iterator)是一种用于遍历数据集合的的对象。它提供了一种访问数据集合中元素的方式,而无需暴露数据集合内部的细节。使用迭代器,我们可以对数据集合中的每个元素进行处理,而无需将整个数据集合加载到内存中。这样可以节省内存空间,并且在处理大型数据集合时可以提高处理效率。
C++ STL(标准模板库)中的容器类都提供了迭代器,用于访问容器内部的元素。迭代器是一个类或者一个指针,它可以指向容器中的一个元素,然后遍历容器中的所有元素。
C++ STL中的迭代器通常具有以下五个成员函数:
operator*()
:用于返回当前迭代器指向的元素的引用。operator->()
:用于返回当前迭代器指向的元素的指针。operator++()
:用于将迭代器移动到下一个元素。operator--()
:用于将迭代器移动到上一个元素。operator==()
和 operator!=()
:用于比较两个迭代器是否相等。C++ STL中的容器类,如vector、list、map、set等都提供了迭代器,可以通过调用容器的成员函数begin()和end()获取指向容器第一个元素和最后一个元素的迭代器。
- #include <iostream>
- #include <vector>
-
- using namespace std;
-
- int main()
- {
- vector<int> v = {1, 2, 3, 4, 5};
-
- // 遍历vector中的所有元素
- for (auto it = v.begin(); it != v.end(); ++it)
- {
- cout << *it << " ";
- }
- cout << endl;
-
- return 0;
- }

该代码定义了一个vector<int>对象v,并使用auto关键字定义了一个迭代器it来遍历vector中的所有元素。在每次迭代中,使用*it访问迭代器指向的元素。最后输出所有元素的值。
vector是一个动态数组容器,可以使用迭代器来访问其元素。vector有两种类型迭代器:正向迭代器和反向迭代器。
正向迭代器遍历:
- #include<iostream>
- #include<vector>
- using namespace std;
- int main() {
- vector<int> v = { 1,2,3,4,5 };
- vector<int>::iterator it;
- for (it = v.begin(); it != v.end(); ++it) {
- cout << *it << " ";
- }
- return 0;
- }
输出结果:1,2,3,4,5
在上面的示例中,我们首先创建一个vector对象v,并使用v.begin()和v.end()方法获取迭代器的起始和结束位置。然后我们使用一个迭代器it来遍历vector的每个元素。通过使用*it来获取迭代器指向的元素的值。
我们也可以使用auto关键字来简化迭代器的定义:
- #include<iostream>
- #include<vector>
- using namespace std;
- int main() {
- vector<int> v = { 1,2,3,4,5 };
- for (auto it = v.begin(); it != v.end(); ++it) {
- cout << *it << " ";
- }
- return 0;
- }
反向迭代器遍历:
反向迭代器遍历vector的方法与正向迭代器类似,只需使用rbegin()和rend()方法获取反向迭代器的起始和结束位置。以下是一个使用反向迭代器遍历vector数组的示例:
- #include<iostream>
- #include<vector>
- using namespace std;
- int main() {
- vector<int> v = { 1,2,3,4,5 };
- vector<int>::reverse_iterator it;
- for (it = v.rbegin(); it != v.rend(); ++it) {
- cout << *it << " ";
- }
- return 0;
- }
输出结果:5,4,3,2,1
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。