Iterator Adapters(迭代器配接器)

本文详细介绍了逆向迭代器的工作原理及其在C++标准容器中的应用,通过实例展示了如何使用逆向迭代器进行逆序遍历,并解释了逆向迭代器与常规迭代器之间的转换方式。此外,还简要提到了安插型迭代器和流迭代器的相关概念。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


Reverse Iterators(逆向迭代器)

逆向迭代器是一种配接器,重新定义递增运算和递减运算,使其行为正好倒置,这么一来,如果你使用这类迭代器,算法将以逆序次序来处理元素。所有标准容器都允许使用Reverse迭代器来遍历元素。

例子

#include <iostream>
#include <list>
#include <algorithm>
using namespace std;

void print(int elem)
{
	cout << elem << ' ';

}
int main()
{
	list<int> coll;
	for (int i = 1; i <= 9; ++i)
	{
		coll.push_back(i);
	}

	for_each(coll.begin(), coll.end(), print);
	cout << endl;

	for_each(coll.rbegin(), coll.rend(), print);
	cout << endl;

	return 0;
}


  • rbegin()传回一个Reverse迭代器指向逆向遍历的第一个位置,也就是实际上最后一个元素位置。
  • rend()传回一个Reverse迭代器指向逆向遍历时最后一个位置的下一个位置,也就是实际上第一个元素的前一位置。

Iterator 和 Reverse Iterator的转化

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

void print(int elem)
{
	cout << elem << ' ';

}
int main()
{
	vector<int> coll;
	for (int i = 1; i <= 9; ++i)
	{
		coll.push_back(i);
	}
	vector<int>::iterator pos;
	pos = find(coll.begin(), coll.end(), 5);
	cout << "pos " << *pos<<endl;

	//pos to rpos
	vector<int>::reverse_iterator rpos(pos);
	cout << "rpos " << *rpos << endl;


	return 0;
}
//output:
//pos: 5
//rpos: 4

这里并不是bug,而是特性。逆向迭代器的设计者使用了一个小技巧:他们实际上倒置了“半开原则”。逆向迭代器所定义的区间,实际上不包括起点,反倒是包括了终点。

Insert Iterators(安插型迭代器)

Stream Iterators(流迭代器)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值