iterator 迭代器
迭代器是一种抽象的设计概念,在设计模式中iterator模式被定义为:提供一种方法,可以按序访问某一聚合物(容器)所含元素,且不暴露该聚合物的内部表达方式。
在STL中,迭代器又起着将容器与算法联合到一起的作用。
迭代器:设计模式–》元素访问的一种设计模式
所有容器都需要遵循相同的设计规范
所有容器迭代器的是使用方法都是相同的
怎末使用迭代器?
迭代器的指针方式和指针类似
设计规范:
1.begin迭代器:指向第一个元素的位置
2.end迭代器:指向最后一个元素的后一个位置
正向迭代器的解引用
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27void test() { //正向迭代器 string str = "123456"; //起始位置的迭代器 string::iterator it = str.begin(); for (; it != str.end(); ++it) { //迭代器的解引用 cout << *it << " "; //可以通过迭代器进行内容的修改 *it = 'a'; cout << *it << " "; } const string str2 = "asdfg"; //只读迭代器 string::const_iterator it2 = str2.begin(); while (it2 != str2.end()) { cout <<*it2 << " "; //只读迭代器不能修改内容 //*it2 = '1'; ++it2; } } int main(){ test(); return 0; }
3.访问数据:通过解引用,即*或者->两种方式
4.迭代器移动:++移动到下一个元素的位置,–移动到下一个元素的位置
5.位置的判断:支持!=,==
有些容器具有反向迭代器
6.rbegin迭代器:指向最后一个元素的位置
7.rend迭代器:指向第一个元素的前一个位置
反向迭代器的解引用
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27void test() { //反向迭代器 string str = "123456"; //最后一个元素的位置 string::reverse_iterator it = str.rbegin(); while (it != str.rend()) { cout << *it << " "; *it = 'a'; it++; } //只读迭代器 const string str2 = "asdfgh"; //最后一个元素的位置 string::const_reverse_iterator it2 = str2.rbegin(); while (it2 != str2.rend()) { cout << *it2 << " "; //*it2 = 'a';//const 无法进行修改 it2++; } } int main(){ test(); return 0; }
8.范围for实际上是通过迭代器实现的
支持迭代器访问的自定义类型都可以支持范围for
最后
以上就是清脆麦片最近收集整理的关于STL迭代器的全部内容,更多相关STL迭代器内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复