STL迭代器之辅助迭代器函数

本文详细介绍了C++ STL中的三个辅助迭代器函数:advance()、distance()和iter_swap()。通过具体示例展示了如何使用这些函数来增强迭代器的功能,如在不同类型的迭代器上实现向前移动和交换值等。

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

辅助迭代器函数:
STL提供三个辅助函数:advance(),distance(), and iter_swap().那前两个函数给了所有迭代器一些能力,平常这些能力只有random access iterators拥有:向前移动多个位置和处理两个迭代器的差值。第三个函数允许你交换两个迭代器的值。

函数advance()
#include <iterator>
void advance (InputIterator& pos, Dist n)
1.input iterator pos 向前前进N个元素。
2.对于For bidirectional  random access iterators N也许是负数。
3.Dist 是个模板参数,一般它是整型,因为像这样的操作<, ++, --, and0比较被调用。
4.该函数不检查传递的迭代器是不是容器的end().所以在用时一定要注意。
由于用到了 iterator traits, 该函数总是用最好的执行方式,因为它依赖于iterator category。对于random access iterators, 它只是简单的调用pos+=n,对于其它的迭代器它调用 ++pos n 次。
例子:
list<int> coll;
for (int i=1; i<=9; ++i) {coll.push_back(i);}
list<int>::iterator pos = coll.begin();
cout << *pos << endl;
advance (pos, 3);
cout << *pos << endl;
advance (pos, -1);
cout << *pos << endl;
output:
1
4
3

函数distance()
#include <iterator>
Dist distance (InputIterator pos1, InputIterator pos2)
1.        返回两个迭代器之间的距离。
2.        两个迭代器一定要指向同一个容器
3.        如果迭代器不是random access iterators,,那个pos2一定不能在pos1的后面,可以在同一个位置。
4.        返回值的类型依赖于迭代器的类型;iterator_traits<InputIterator>::difference_type。

该函数也用到了iterator traits, 所以总是用最好的执行方式。

例子:
list<int> coll;
for (int i=-3; i<=9; ++i) {coll.push_back(i);}
list<int>::iterator pos;
pos = find (coll.begin(), coll.end(),5); 
if (pos != coll.end()) {
cout << "difference between beginning and 5: "
<< distance(coll.begin(),pos) << endl;
}
else {
cout << "5 not found" << endl;
}
}
Output: difference between beginning and 5: 8.




iter_swap()函数:
#include <algorithm>
void iter_swap (ForwardIterator1 pos1, ForwardIterator2 pos2)
1.        交换两个迭代器的值
2.        迭代器不要求是同一种类型,但是值要是可赋值的。

例子:
list<int> coll;
for (int i=1; i<=9; ++i) {coll.push_back(i);}
PRINT_ELEMENTS(coll);
iter_swap (coll.begin(), ++coll.begin());
PRINT_ELEMENTS(coll);
Output:
1 2 3 4 5 6 7 8 9
2 1 3 4 5 6 7 8 9
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值