1.5 KiB
1.5 KiB
2.11 容器和模板
2.11.1 标准容器
Vector
List
Map
Set
2.11.2 迭代器
2.11.3 模板类
使用模板的目的就是能够让程序员编写与类型无关的代码。比如编写了一个交换两个整型 int 类型的 swap 函数,这个函数就只能实现 int 型,对 double,字符这些类型无法实现,要实现这些类型的交换就要重新编写另一个 swap 函数。使用模板的目的就是要让这程序的实现与类型无关,比如一个 swap 模板函数,即可以实现 int 型,又可以实现 double 型的交换。
模板的声明或定义只能在全局,命名空间或类范围内进行。
函数模板的格式为:
template<class 形参名, class 形参名, ...> 返回类型 函数名(参数列表)
{
...
}
类模板的格式为:
template<class 形参名, class 形参名, ...> class 类名
{
...
};
一个简单的示例如下:
/**
* @file ATemplate.h
*/
#pragma once // 只被编译一次.
template<class T> class A{
public:
A();
T Add(T a,T b);
};
#endif
/**
* @file ATemplate.cpp
*/
#include "ATemplate.h"
#include <iostream.h>
template<class T> A<T>::A()
{
}
template<class T> T A<T>::Add(T a,T b)
{
return a+b;
}
/**
* @file main.cpp
*/
#include "ATemplate.h"
void main(){
A<int> a;
cout<<a.Add(2, 3)<<endl;
}
练习
基于模板实现堆栈操作。