c++ 模板学习笔记:函数模板实现数组通用排序和遍历打印(权哥)
2013-11-24 22:19
976 查看
#include <algorithm> #include <cstring> #include <iostream> using namespace std; template <typename T> void sort(T a[], int n) { for(int i=0; i<n-1; i++){ int min = i; for(int j=i+1; j<n; j++) if(a[j]<a[min]) min = j; swap(a[min],a[i]); } } template <typename T> void sort(T* a[], int n) { for(int i=0; i<n-1; i++){ int min = i; for(int j=i+1; j<n; j++) if(*a[j]<*a[min]) min = j; swap(a[min],a[i]); } } template <> void sort(const char* a[], int n) { for(int i=0; i<n-1; i++){ int min = i; for(int j=i+1; j<n; j++) if(strcmp(a[j],a[min])<0) min = j; swap(a[min],a[i]); } } /*定义一个日期结构体*/ struct Date{ int y, m, d; //Date(int y, int m, int d):y(y),m(m),d(d){} }; /*小于号重载*/ bool operator<(const Date& a, const Date& b){ return (a.y<b.y||a.y==b.y&&(a.m<b.m||a.m==b.m&&a.d<b.d)); } /*输出流重载*/ ostream& operator<<(ostream& o, const Date& d) { return o << d.y << '-' << d.m << '-' << d.d; } /*数组遍历打印,提供数组长度*/ template <class T> void show(T a[], int n) { for(int i=0; i<n; i++) cout << a[i] << ' '; cout << endl; } /*template <typename T, int N> //void show(T& t) //{ // int n = sizeof(t)/sizeof(t[0]); // for(int i=0; i<n; i++) // cout << t[i] << ' '; // cout << endl; //}*/ /*数组遍历打印,只提供数组名*/ template <typename T, int N> void show(T(&t) ) { for(int i=0; i<N; i++) cout << t[i] << ' '; cout << endl; } /*数组遍历打印,只提供数组名,而且数组是指针数组*/ template <typename T, int N> void show(T*(&t) ) { for(int i=0; i<N; i++) cout << *t[i] << ' '; cout << endl; } /*打印单个指定类型的值*/ template <typename T> void show(T data) { cout << data << endl; } int main() { double m=123.4; show(m); int a[5]={6,1,9,2,8}; double d[4]={3.3,5.5,2.2,1.6}; Date x[3]={{2010,9,30},{2010,9,9},{2010,8,8}}; sort(a,5);//a==>int* // sort(reinterpret_cast<int*>(d),4); sort(d,4); sort(x,3); show(a,5);show(d,4);show(x,3); show(a);show(d);show(x); const char* s[3]={"furong","quange","chunge"}; sort(s,3); show(s); int* ap[4]={new int(5),new int(2),new int(9),new int(8)}; double* bp[3]={new double(3.3),new double(5.5),new double(2.2)}; sort(ap,4);sort(bp,3); show(ap);show(bp); } /*输出: 123.4 1 2 6 8 9 1.6 2.2 3.3 5.5 2010-8-8 2010-9-9 2010-9-30 1 2 6 8 9 1.6 2.2 3.3 5.5 2010-8-8 2010-9-9 2010-9-30 c f q 2 5 8 9 2.2 3.3 5.5 */
相关文章推荐
- C++ 函数模板和排序的函数模板——学习笔记
- c++ 模板学习笔记:用数组和类模板模拟通用栈(权哥)
- c++ 模板学习笔记:类模板和函数模板实现pair(权哥)
- c++学习笔记-----qsort通用排序函数
- c++ 模板学习笔记:函数模板的类型识别(权哥)
- C/C++学习笔记12:数组作为函数参数
- 学习笔记:快速排序的C++、JavaScript(2种方法)、Java实现
- C++学习笔记(三)--函数参数,数组函数,指针和const,二维数组函数,递归,函数指针
- (c++)类模板与函数模板实例:通用数组
- c++学习笔记(七):函数返回数组
- 【C++数据结构学习笔记---线性表】用数组实现线性表
- c++ 模板学习笔记:理解类模板的特化与偏特化(权哥)
- c++学习笔记(14.函数模板)
- 前端攻城狮学习笔记一:实现一个遍历数组或对象里所有成员的迭代器
- Linux-C基础知识学习:C语言作业-将5个学生成绩保存在一个数组中,单独实现一个计算平均成绩的average函数, 在main函数中获取该函数返回的平均值,并打印。
- C++面向对象—成员函数与成员变量的实现机制学习笔记(1)
- 【C++】【学习笔记】【未成功实现】关于指针的函数【very difficult】
- php学习笔记 数组遍历实现代码
- C++学习笔记五——函数重载(多态)、函数模板及函数模板重载和完全匹配与最佳匹配
- 一个无聊男人的疯狂《数据结构与算法分析-C++描述》学习笔记 用C++/lua/python/bash的四重实现(7)习题2.8 随机数组的三种生成算法