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