C++编程(B)

Educn 135 templateclass t class vector t v int

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: 版本 Beijing University of Posts & Telecommunications Beijing young@buptnet.edu.cn 函数模板示例 template<class T> void sort(vector<T>&); void f(vector<int>& vi, vector<string>& vs) { sort(vi); // sort(vector<int>&); sort(vs); // sort(vector<string>&); } template<class T> void sort(vector<T>& v) { // Shell sort(Knuth, Vol. 3, pg.84) const size_t n = v.size(); for(int gap=n/2; 0<gap; gap/=2) for(int i=gap; i<n; i++) for(int j=i-gap; 0<=j; j-=gap) if(v[j+gap]<v[j]) swap(v[j], v[j+gap]); // 注意,用<做比较运算,并非所有类型都支持该运算符 } Beijing University of Posts & Telecommunications Beijing young@buptnet.edu.cn 13.3.1 函数模板的参数 模板函数对于写出通用型算法是至关重要 的,这种算法可以应用于广泛且多样化的容 器类型 对于一个调用,能从函数的参数推断出模板 参数的能力是其中最关键的 Beijing University of Posts & Telecommunications Beijing young@buptnet.edu.cn 函数模板的参数示例 编译器能够从一个调用推断出类型参数和非类 型参数,条件是由这个调用的函数参数表能够唯 一地标识出模板参数的一个集合 template<class T, int i> T& lookup(Buffer<T,i>& b, const char* p); class Record{ const char v[12]; // ... }; Record& f(Buffer<Record,128>& buf, const char* p) { return lookup(buf,p); // 使用lookup(),其中T是Record, i是128 } Beijin...
View Full Document

This note was uploaded on 02/10/2014 for the course ECE C++ taught by Professor Xiaoshengtang during the Fall '13 term at BUPT.

Ask a homework question - tutors are online