使用迭代器编程

来源:互联网 发布:淘宝网店从哪开 编辑:程序博客网 时间:2024/06/05 04:12
 

输入迭代器

输入迭代器是最普通的类型。输入迭代器至少能够使用==和!=测试是否相等;使用*来访问数据;

使用++操作来递推迭代器到下一个元素或到达past-the-end值

为了理解迭代器和STL函数是如何使用它们的,现在来看一下find()模版函数的定义:

template<class InputIterator,class T>

InputIterator find(InputIterator first,InputIterator last,const T& value)

{

while (first!=last&&*first!=value)

 ++first;

return first;

}

注意 在find算法中,注意如果 first和last指向不同的容器,该算法可能陷入死循环。

输出迭代器

输出迭代器缺省只写,通常用于将数据从一个位置拷贝到另一个位置。由于输出迭代器无法读取对象,因此你不会在任何搜索和其他算法中使用它。要想读取一个拷贝值,必须使用另一个输入迭代器(或其它的继承迭代器)。

#include <iostream.h>

#include<algorithm> //Need copy()

#include<vector>      //Need vector

using namespace std;

double darray[10]={1.0,1.1,1.2,1.3,1.4,1.5,1.6,1.7,1.8,1.9};

vector<double> vdouble(10);

int main()

{

vector<double>::iterator outputIterator=vdouble.begin();

copy(darray,darray+10,outputIterator);

while(outputIterator!=vdouble.end())

{

cout<<*outputIterator<<endl;

outputIterator++;

}

return 0;

}

注意

当使用copy() 算法的时候,你必须确保目标容器足够大的空间,或者容器本身是自动扩展的

前推迭代器

前推迭代器能够读写数据值,并能够向前推进到下一个值。但没法递减。replace()

算法显示了前推迭代器的使用方法

template<class ForwardIterator,class T>

void replace(ForwardIterator first,

                       ForwardIterator last,

                       const  T&old_value,

                       const  T&new_value);

使用replace()将【first,last】范围内的所有值为old_value的对象替换为new_value.

replace(vdouble.begin(),vdouble.end(),1.5,3.14159);

双向迭代器

双向迭代器要求能够增减。如reverse()算法要求两个双向迭代器作为参数;

template<class BidirectionalIterator>

void reverse (BidirectionalIterator first,BidirectionalIterator last);

使用reverse(vdouble.begin(),vdouble.end());

随机访问迭代器

随机访问迭代器能够以任意顺序访问数据,并能用于读写数据(不是CONST的c++指针也是随机访问迭代器)。

STL的排序和搜索函数使用随机访问迭代器。随机访问迭代器可以使用关系操作符作比较

random_shuffle()函数随机打乱原先顺序

template <class RandomAccessIterator>

void random_shuffle (RandomAccrssIterator  first,RandomAccessIterator last);

使用方法:

random_shuffle(vdouble.begin(),vdouble.end());