c++那些事儿5 0 模板

模板

 是泛型编程的重点,在后面的STL中,模板的功能得到广泛运用。
 在java中泛型,集合都有模板的身影,弄清模板可以让我们更加深入学习。
复制代码

####可讲的东西不多,直接看code ``` #include #include using namespace std; //选择排序的模板函数 template void sort(T *arr,int n) { T min; for (int i = 0; i < n-1; i++) { min = arr[i]; for (int j = i + 1; j < n; j++) { if (min > arr[j]) { min = arr[j]; arr[j] = arr[i]; arr[i] = min; } } } } //打印数组的模板函数。 template void print(N *arry, int n) { for (int i = 0; i < n; i++) cout << arry[i] << " "; } int main() {
int arr[6] = { 2,89,55,33,22,88 };
cout << "原数组:";
print(arr, 6);
cout << endl;
sort(arr, 6);
cout << "选择排序后的数组:";
print(arr, 6);
cout << endl;

system("pause");
return 0;
复制代码

}

<hr>
####结果如下:
![001.PNG](http://upload-images.jianshu.io/upload_images/4976516-574233d8288ddbef.PNG?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

#### 模板类
复制代码
模板声明前要加上  template<typename 类型参数> 
          //typename也可以用class替换,但是我不建议,任意混淆
复制代码
<hr>
####代码如下
复制代码

// 定义模板堆栈 #include #include using namespace std;

/* 定义堆栈类模板 */ template<typename T, int num> class Stack { private: T arr[num]; int point; public: Stack();//构造函数 bool isEmpty(); //判断栈是否为空 bool isFull(); //判断栈是否为满 bool add(const T &t); //一个元素压栈 bool get(T &t); //取堆栈元素 };

template<class T, int num> Stack<T, num>::Stack() { point = 0; //初始化为空。 }

template<typename T, int num> bool Stack<T, num>::isEmpty() { return point == 0; }

template<class T, int num> bool Stack<T, num>::isFull() { return point == num; }

template<class T, int num> bool Stack<T, num>::add(const T &obj) { if (isFull()) return false; else { arr[point] = obj; point++; return true; } } template<class T, int num> bool Stack<T, num>::get(T &obj) { if (isEmpty()) return false; else { point--; obj = arr[point]; return true; } }

int main() { Stack<double, 5> stack; cout << "堆栈是否为空:" << stack.isEmpty() << endl; stack.add(3.1); //压栈 cout << "堆栈是否为空:" << stack.isEmpty() << endl; stack.add(3.14); stack.add(3.141); stack.add(3.1415); stack.add(3.14159); cout << "堆栈是否已满:" << stack.isEmpty() << endl; double d = 0.0; while (stack.get(d)) { cout << d <<" "; } system("pause"); return 0; }

####结果:
![
](http://upload-images.jianshu.io/upload_images/4976516-6d14389fa6b1afb9.PNG?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
<hr>
>**代码排版还行吧?** 
复制代码

争取把c++语法写完,然后写javase,在数据结构与算法。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值