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

辅助迭代器函数:
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  是个模板参数,一般它是整型,因为像这样的操作 <, ++, --, and 0 比较被调用。
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、付费专栏及课程。

余额充值