【点滴记录】iterator_traits<Iterator>用法
2011-12-01 19:56
369 查看
MSDN上看到的原型:
就是说模板参数可以是一个迭代器,也可以是一个具体数据类型的指针。
如下例子:
首先是执行插入排序的一个函数:
main函数:
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); }
相关文章推荐
- &lt;s:iterator&gt;各种遍历用法
- Struts2中<s:iterator>基本用法及示例
- <s:iterator>及<s:property>的用法
- <s:iterator>各种遍历用法
- <s:iterator>的用法
- <s:iterator>各种遍历用法
- <s:iterator>的一些用法
- <s:iterator>标签的用法
- error C2665: 'ostream_iterator<int,char,struct std::char_traits<char> >::ostream_iterator<int,char,s
- <c:forEach></c:forEach>嵌套的用法与for的区别
- <applet>和<object>标签的用法区别研究二
- iOS出现 Undefined symbols for architecture armv7 std::basic_string<char, std::char_traits<char>
- struts2<s:iterator>遍历map小结
- C++ 在dynamic_cast<>用法
- C# List<>简单用法
- 【MySql】使用记录<四>
- Seam <s:fileUpload>标签的用法
- C# List<T>基本用法
- 字符特性char_traits定义,及其特化版本char_traits<char>,char_traits<wchar_t>
- Map.Entry<K,V> 的简单用法