| 迭代器函数 | 功能 |
|---|---|
| begin() | 返回指向容器中第一个元素的双向迭代器(正向迭代器)。 |
| end() | 返回指向容器中最后一个元素所在位置的下一个位置的双向迭代器。(正向迭代器)。 |
| rbegin() | 返回指向最后一个元素的反向双向迭代器。 |
| rend() | 返回指向第一个元素所在位置前一个位置的反向双向迭代器。 |
| cbegin() | 和 begin() 功能相同,只不过在其基础上,正向迭代器增加了 const 属性,即不能用于修改元素。 |
| cend() | 和 end() 功能相同,只不过在其基础上,正向迭代器增加了 const 属性,即不能用于修改元素。 |
| crbegin() | 和 rbegin() 功能相同,只不过在其基础上,反向迭代器增加了 const 属性,即不能用于修改元素。 |
| crend() | 和 rend() 功能相同,只不过在其基础上,反向迭代器增加了 const 属性,即不能用于修改元素。 |
表 1 中各个成员函数的功能如图 2 所示。除此之外,C++ 11 新添加的 begin() 和 end() 全局函数也同样适用于 list 容器。即当操作对象为 list 容器时,其功能分别和表 1 中的 begin()、end() 成员函数相同。
从图 2 可以看出,这些成员函数通常是成对使用的,即 begin()/end()、rbegin()/rend()、cbegin()/cend()、crbegin()/crend() 各自成对搭配使用。其中,begin()/end() 和 cbegin/cend() 的功能是类似的,同样 rbegin()/rend() 和 crbegin()/crend() 的功能是类似的。注意,list 容器的底层实现结构为双向链表,图 2 这种表示仅是为了方便理解各个迭代器函数的功能。
下面这个程序演示了如何使用表 1 中的迭代器遍历 list 容器中的各个元素。有关迭代器类别和功能的具体介绍,可阅读 《C++ STL迭代器》一节。
#include <iostream>
#include <list>
using namespace std;
int main()
{
//创建 list 容器
std::list<char> values{'h','t','t','p',':','/','/','c','.','b','i','a','n','c','h','e','n','g','.','n','e','t'};
//使用begin()/end()迭代器函数对输出list容器中的元素
for (std::list<char>::iterator it = values.begin(); it != values.end(); ++it) {
std::cout << *it;
}
cout << endl;
//使用 rbegin()/rend()迭代器函数输出 lsit 容器中的元素
for (std::list<char>::reverse_iterator it = values.rbegin(); it != values.rend();++it) {
std::cout << *it;
}
return 0;
}
输出结果为:
http://c.biancheng.net
ten.gnehcnaib.c//:ptth
注意,程序中比较迭代器之间的关系,用的是 != 运算符,因为它不支持 < 等运算符。另外在实际场景中,所有迭代器函数的返回值都可以传给使用 auto 关键字定义的变量,因为编译器可以自行判断出该迭代器的类型。
#include <iostream>
#include <list>
using namespace std;
int main()
{
//创建 list 容器
std::list<char> values{'h','t','t','p',':','/','/','c','.','b','i','a','n','c','h','e','n','g','.','n','e','t'};
//创建 begin 和 end 迭代器
std::list<char>::iterator begin = values.begin();
std::list<char>::iterator end = values.end();
//头部和尾部插入字符 '1'
values.insert(begin, '1');
values.insert(end, '1');
while (begin != end)
{
std::cout << *begin;
++begin;
}
return 0;
}
运行结果为:
http://c.biancheng.net1
可以看到,在进行插入操作之后,仍使用先前创建的迭代器遍历容器,虽然程序不会出错,但由于插入位置的不同,可能会遗漏新插入的元素。
版权说明:Copyright © 广州松河信息科技有限公司 2005-2025 版权所有 粤ICP备16019765号
广州松河信息科技有限公司 版权所有