2665
备注:
|
3047
|
删除的内容标记成这样。 | 加入的内容标记成这样。 |
行号 52: | 行号 52: |
练习:写一个abs类,可以计算任意类型的数的绝对值 |
|
行号 127: | 行号 129: |
练习:写一个Array类,可以存放任何类型元素的数组 == 系统内置的模板库 == === 基本容器 === 线性容器:vector、deque、list,关联容器:set、multiset、map、multimap === 适配器 === stack、queue、priority_queue === 迭代子 === === 算法 === |
C++模板
模板是C++最有特色的语法,也是最复杂的语法。它将类型看作一种参数来进行编程。
1. 模板函数
写一个max,求两个东西中较大的一个。
它们的算法都是类似的,只是参与运算的对象的类型不同。我们可以把类型定义成一个参数:
调用方法
调用时会自动对模板函数的类型进行推导。前面这个模板还不能对两个C字符串进行比较,比如
可以对函数进行重载
练习:写一个abs类,可以计算任意类型的数的绝对值
2. 模板类
1 class Stack {
2 int *data_;
3 int size_;
4 int capacity_;
5 public:
6 Stack(int capacity) {
7 capacity_ = capacity;
8 size_ = 0;
9 data_ = new int[capacity_];
10 }
11 ~Stack() {
12 delete[] data_;
13 }
14 void push(int t) {
15 data_[size_++] = t;
16 }
17 void pop() {
18 size_--;
19 }
20 int top() const{
21 return data_[size_-1];
22 }
23 bool empty() const{
24 return size_ == 0;
25 }
26 int size() const {
27 return size_;
28 }
29 };
这个栈只能用来存放int不能存放其他东西,为了让他能够存放其他东西,我们把int参数化
1 template<class T>
2 class Stack {
3 T *data_;
4 int size_;
5 int capacity_;
6 public:
7 Stack(int capacity) {
8 capacity_ = capacity;
9 size_ = 0;
10 data_ = new T[capacity_];
11 }
12 ~Stack() {
13 delete[] data_;
14 }
15 void push(const T &t) {
16 data_[size_++] = t;
17 }
18 void pop() {
19 size_--;
20 }
21 T top() const{
22 return data_[size_-1];
23 }
24 bool empty() const{
25 return size_ == 0;
26 }
27 int size() const {
28 return size_;
29 }
30 };
有了这个模板类以后,我们可以定义存放各种类型元素的栈:
练习:写一个Array类,可以存放任何类型元素的数组
3. 系统内置的模板库
3.1. 基本容器
线性容器:vector、deque、list,关联容器:set、multiset、map、multimap
3.2. 适配器
stack、queue、priority_queue
3.3. 迭代子
3.4. 算法