您的位置:首页 > 大数据 > 人工智能

【点滴记录】iterator_traits<Iterator>用法

2011-12-01 19:56 369 查看
MSDN上看到的原型:
template<class Iterator>
struct iterator_traits {
typedef typename Iterator::iterator_category iterator_category;
typedef typename Iterator::value_type value_type;
typedef typename Iterator::difference_type difference_type;
typedef typename Iterator::pointer pointer;
typedef typename Iterator::reference reference;
};
template<class Type>
struct iterator_traits<Type*> {
typedef random_access_iterator_tag iterator_category;
typedef Type value_type;
typedef ptrdiff_t difference_type;
typedef Type *pointer;
typedef Type& reference;
};
template<class Type>
struct iterator_traits<const Type*> {
typedef random_access_iterator_tag iterator_category;
typedef Type value_type;
typedef ptrdiff_t difference_type;
typedef const Type *pointer;
typedef const Type& reference;
};


就是说模板参数可以是一个迭代器,也可以是一个具体数据类型的指针。

如下例子:

首先是执行插入排序的一个函数:

template<typename Iterator>
void insertionSort(const Iterator &a,const Iterator &b){
typedef typename iterator_traits<Iterator>::value_type T;
int i,j,n=distance(a,b);
T key;
Iterator p,q,t;
for(j=1,q=p=a,p++,t=p;j<n;j++,q=p,p++,t=p){
key=*p;
i=j-1;
while(i>=0 && *q>key){
*t=*q;
i--,t--,q--;
}
*t=key;
}
}


main函数:

#include <iostream>
#include <string>
#include <vector>
#include <list>
#include <iterator>
#include "insertionsort_cpp.h"
using namespace std;
int main(int argc,char** argv)
{
int a[]={5,1,9,4,6,2,0,3,8,7},i;
string b[]={"ChonqQing","ShangHai","AoMen","TianJin","BeiJing","XiangGang"};
double c[]={8.5,6.3,1.7,9.2,0.5,2.3,4.1,7.4,5.9,3.7};
vector<string> vb=vector<string>(b,b+6);
list<double> lc=list<double>(c,c+10);
insertionSort<int*>(a,a+10);    //模板参数为具体类型的指针
copy(a,a+10,ostream_iterator<int>(cout," "));
cout<<endl;
insertionSort<vector<string>::iterator>(vb.begin(),vb.end()); //模板参数为一个迭代器
copy(vb.begin(),vb.end(),ostream_iterator<string>(cout," "));
cout<<endl;
insertionSort<list<double>::iterator>(lc.begin(),lc.end());
copy(lc.begin(),lc.end(),ostream_iterator<double>(cout," "));
cout<<endl;
return(0);
}


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