您的位置:首页 > 其它

STL学习笔记---- iterator

2010-05-07 14:34 344 查看
作者:winterTTr(转载请注明)  资料来源:《C++ Standard Libarry》

 

 

有关iterator的分类和简单操作,就不介绍了,一般的资料都会有的。

这里总写一些我们用的不多的,或者不太熟悉的方面。

 

 

一些有用的函数

#include <iterator>
void advance (InputIterator& pos, Dist n)
//将pos增加n
#include <iterator>
Dist distance (InputIterator pos1, InputIterator pos2)
//计算pos1和pos2之间的距离
#include <algorithm>
void iter_swap (ForwardIterator1 pos1, ForwardIterator2 pos2)
//交换pos1和pos2所指向的内容


 

 

iterator的适配器

我们可以通过reverse_iterator来讲一个正向的iter转换为逆向的。不过,这里要注意一点,那就是转换后的iter保持的是”物理位置“,而不是”逻辑位置“。

例如:

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
vector<int> coll;
//insert elements from 1 to 9
for (int i=1; i<=9; ++i) {
coll.push_back(i);
}
//find position of element with value 5
vector<int>::iterator pos;
pos = find (coll.begin(), coll.end(), 5);
//print value to which iterator pos refers
cout << "pos: " << *pos << endl;
//convert iterator to reverse iterator rpos
vector<int>::reverse_iterator rpos(pos);
//print value to which reverse iterator rpos refers
cout << "rpos: " << *rpos <<endl;
}

 

的结果是:

pos: 5

rpos: 4

这是一种特性,而不是bug,这点要很注意!

 

当然,我们可以通过reverse_iterator本身的base()函数,讲一个反向iterator转换为正向的,不过,注意点相同,保持”物理位置“而非”逻辑位置“

 

插入适配器:



需要注意一点的时候,我们如果使用copy等标准算法进行插入的时候,在特殊情况下不要忘记预留足够的空间,否则,会造成interator的无效问题。

 

stream iterator:



 

 



 

 

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息