自言自语:其实作者在这之前一直不太能理解迭代器,觉得反思维,不能很好记下来运用,还是习惯于用for,while循环。说白了还是懒,用好了会很方便,且能让代码更美。
1.概述
迭代器用于通过“指向”来访问和迭代数据结构(向量、集合等)的元素。我个人认为迭代器是循环的一种特殊情况,for-each迭代器由于参数特殊性,更偏向于遍历整个数据结构,但我们循环中不仅仅用于遍历结构,还有时候是用于筛查一些特殊值或者进行一些特殊的处理。我们可以简单的吧迭代器理解为指针
2.创建迭代器变量
eg:
#include <iostream>
#include <vector>
using namespace std;
int main() {
// Create a vector called cars that will store strings
vector<string> cars = {"Volvo", "BMW", "Ford", "Mazda"};
// Create an iterator named it
vector<string>::iterator it;//声明一个迭代器 it,用于遍历 vector<string> 类型的容器
// Use the iterator to loop through the vector
for (it = cars.begin(); it != cars.end(); ++it) {
cout << *it << "\n";//*it 解引用操作则可以访问该元素的值。
}
return 0;
}
这里的begin()和end()要区别于front()和back(),可以参考文章begin()和end()还有front()和back()
运行结果:
注意:迭代器的类型必须与它要迭代的数据结构(在我们的例子中)string的类型匹配
auto关键字
在 C++ 11 及更高版本中,你可以使用关键字auto而不是 显式声明和指定迭代器的类型,该关键字允许编译器 自动确定正确的数据类型,从而简化代码和 使其更具可读性
比如你声明一个vector<string>的迭代器变量,需要写很长的前置定义,使用auto关键字可以让代码更简洁,更省事(前提是不乱用),对比一下
eg:vector<string>::iterator it = cars.begin();
auto it = cars.begin();
上面两个定义代码是等价的。作用是相同的
Attention:auto关键字固然好用,省的我们想和敲关键字,但是如果随意或者大篇幅全文件使用auto关键字会导致代码可读性非常差,倒来倒去你也不知道这个变量的类型是啥了,所以大家谨慎使用。
For-Each循环与迭代器
你可以使用for-each循环来遍历数据结构中的元素,如下所示:
eg:
#include <iostream>
#include <vector>
using namespace std;
int main() {
// Create a vector called cars that will store strings
vector<string> cars = {"Volvo", "BMW", "Ford", "Mazda"};
// Print vector elements
for (string car : cars) {
cout << car << "\n";
}
return 0;
}
运行结果:
反向循环容器,
可以用rbegin(),rend(),rbegin()
和 rend()
是 vector
容器提供的用于反向迭代的成员函数,它们可以让你从容器的末尾向前遍历。
rbegin()
返回一个指向容器最后一个元素的反向迭代器。反向迭代器的遍历方向与普通迭代器相反,因此,rbegin()
指向的是向量中最后一个元素
rend()
返回一个反向迭代器,指向容器第一个元素之前的位置(即 rend()
不指向任何实际元素,而是一个边界标志,表示反向遍历结束的点)。
迭代器重用性
vector,deque,set,list,都差不多都是通过*解引用,map的比较特殊,注意:而 stacks 和 queues则不支持迭代器。
eg:
#include <iostream>
#include <map>
using namespace std;
int main() {
map<string, int> people = { {"John", 32}, {"Adele", 45}, {"Bo", 29} };
// Loop through the map with an iterator
for (auto it = people.begin(); it != people.end(); ++it) {
cout << it->first << " is: " << it->second << "\n";
}
return 0;
}
map使用"->"箭头符号访问
迭代器算法
在 C++ 中,迭代器不仅仅用于遍历容器,它们还可以与标准库中的各种算法函数配合使用,如 sort()
、find()
等。通过使用迭代器,这些算法函数能够在不同的数据结构上执行操作,例如对数据进行排序或查找特定的元素。
sort()
函数
sort()
是 C++ 标准库 <algorithm>
提供的一个排序算法,它可以接收两个迭代器作为参数,用来确定需要排序的范围。通常,我们使用容器的 begin()
和 end()
迭代器来表示整个容器的范围。
begin()
: 返回指向容器第一个元素的迭代器。end()
: 返回指向容器最后一个元素之后的迭代器(不指向实际的元素,而是容器范围之外的一个位置,标志结束)。
例如,sort(cars.begin(), cars.end());
将对 cars
容器从第一个元素到最后一个元素进行排序。
#include <iostream>
#include <vector>
#include <algorithm> // 引入 <algorithm> 库
using namespace std;
int main() {
// 创建一个存储字符串的 vector,称为 cars
vector<string> cars = {"Volvo", "BMW", "Ford", "Mazda"};
// 使用 sort() 函数对 cars 按字母顺序进行排序
sort(cars.begin(), cars.end());
// 按照字母顺序输出排序后的 cars
for (string car : cars) {
cout << car << "\n";
}
return 0;
}
运行结果: