【点滴记录】iterator_traits用法

MSDN上看到的原型:

template
   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
   struct iterator_traits {
   typedef random_access_iterator_tag iterator_category;
   typedef Type value_type;
   typedef ptrdiff_t difference_type;
   typedef Type *pointer;
   typedef Type& reference;
   };
template
   struct iterator_traits {
   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
void insertionSort(const Iterator &a,const Iterator &b){
	typedef typename iterator_traits::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=0 && *q>key){
			*t=*q;
			i--,t--,q--;
		}
		*t=key;
	}
}

main函数:

#include 
#include 
#include 
#include 
#include 
#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 vb=vector(b,b+6);
	list lc=list(c,c+10);
	insertionSort(a,a+10);    //模板参数为具体类型的指针
	copy(a,a+10,ostream_iterator(cout," "));
	cout<::iterator>(vb.begin(),vb.end()); //模板参数为一个迭代器
	copy(vb.begin(),vb.end(),ostream_iterator(cout," "));
	cout<::iterator>(lc.begin(),lc.end());
	copy(lc.begin(),lc.end(),ostream_iterator(cout," "));
	cout<


你可能感兴趣的:(C/C++)