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

本文通过实例展示了C++中使用模板参数处理迭代器和指针的方法,具体包括如何定义迭代器特性结构、实现插入排序算法,并应用于不同数据类型如整型数组、字符串列表和双精度数列表。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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);
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值