辅助迭代器函数:
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
STL提供三个辅助函数:advance(),distance(),
函数
#include <iterator>
void advance (InputIterator& pos, Dist n)
1.
2.
3.Dist
4.
由于用到了 iterator traits,
例子:
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
函数
#include <iterator>
Dist distance (InputIterator pos1, InputIterator pos2)
1.
2.
3.
4.
该函数也用到了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.
#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