迭代器
来源:简书 - https://www.jianshu.com/p/40e40aef2305迭代器 (iterator) 是 C++ 程序中常用的一种设计模式,它最重要的作用是为访问容器提供了统一的接口。
C++ STL 有许多容器,例如 vector、list、deque、map、unordered_map 。
而我们常常对不同的容器有相同的操作,比如在容器中查找一个元素、找出满足条件的所有元素并返回。为了不必为每个容器写一个操作函数,我们希望容器提供一个访问元素的统一接口,从而复用操作函数。
这个接口就是迭代器。
例子:
1 #include <iostream> 2 #include <numeric> 3 #include <vector> 4 #include <string> 5 #include <list> 6 7 int main() { 8 //普通的数组,一旦申请,不能在扩增 9 int ary[5] = {1,2,3,4,5}; 10 11 //容器 -- 动态数组 不用指定大小,会根据数组当前的使用情况进行动态扩容 12 //模板类型 13 std::vector<int> v; 14 15 //插入数据 16 v.push_back(1); 17 v.push_back(2); 18 v.push_back(3); 19 20 //使用迭代器的方式遍历数组 21 std::vector<int>::iterator it; //迭代器,模板类中的内部类 22 for(it = v.begin(); it != v.end(); it++) { 23 std::cout << *it << std::endl; // *it来访问模板类的具体的值 24 } 25 26 //统一的遍历方式 连表 27 std::list<std::string> l; 28 l.push_back("Hello"); 29 l.push_back("world"); 30 31 std::list<std::string>::iterator it2; 32 for(it2 = l.begin(); it2 != l.end(); it2++) { 33 std::cout << (*it2).c_str() << std::endl; 34 } 35 36 return 0; 37 }
改进1:
... //统一的遍历方式 连表 std::list<std::string> l; l.push_back("Hello"); l.push_back("world"); // std::list<std::string>::iterator it2; // for(it2 = l.begin(); it2 != l.end(); it2++) { // std::cout << (*it2).c_str() << std::endl; // } //auto类型推导关键字 解决书写过长的迭代器类型的烦恼 for(auto it2 = l.begin(); it2 != l.end(); it2++) { std::cout << (*it2).c_str() << std::endl; } ...
改进2:
... //统一的遍历方式 连表 std::list<std::string> l; l.push_back("Hello"); l.push_back("world"); for(std::string str : l) { std::cout << str.c_str() << std::endl; } ...
for(元素类型 元素对象:容器对象)
{
循环体
}
用元素对象依次结合容器对象中的每一个元素,每结合一个元素,执行依次循环体,直至容器内的所有元素都被结合完为止.
改进3:
... //统一的遍历方式 连表 std::list<std::string> l; l.push_back("Hello"); l.push_back("world"); for(auto str : l) { //auto自动推导类型 std::cout << str.c_str() << std::endl; } ...