30分钟掌握STL系列(三)
使用迭代器编程
下面就讲一讲几种类型迭代器的编程。
输入迭代器
输入迭代器是最普通的类型。输入迭代器至少能够使用==和!=等。使用*来访问数据;使用++操作来递进迭代器到下一个元素或到达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;
}
输出迭代器
输出迭代器缺省只写,通常用于将数据从一个位置拷贝到另一个位置。由于输出迭代器无法读取对象,因此你不会再任何搜索和其他算法中使用它。要想读取一个拷贝的值,必须使用另一个输入迭代器(或它的继承迭代器)。看一段程序:
#include<iostream.h>
#include<algorithm>
#include<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()算法的时候,你必须确保目标容器有足够大的空间,或者容器本身是自
动扩展的。
前推迭代器
前推迭代器能够读写数据值,并能够先前推进到下一个值。但是没法递减。
下面的算法显示了前推迭代器的使用方法:
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的值。
双向迭代器
双向迭代器要求能够增减。如reverse()算法要求两个双向迭代器作为参数:
template <class BidirectionalIterator>
void reverse (BidirectionalIterator first,
BidirectionalIterator last);
使用reverse()函数来对容器进行逆向排序:
reverse(vdouble.begin(), vdouble.end());
随机访问迭代器
随机访问迭代器能够以任意顺序访问数据,并能用于读写数据(不是const的C++指针
也是随机访问迭代器)。STL的排序和搜索函数使用随机访问迭代器。随机访问迭代
器可以使用关系操作符作比较。
random_shuffle() 函数随机打乱原先的顺序。申明为:
template <class RandomAccessIterator>
void random_shuffle (RandomAccessIterator first,
RandomAccessIterator last);
使用方法:
random_shuffle(vdouble.begin(), vdouble.end());