#@author: gr#@date: 2014-07-18#@email: forgerui@gmail.com
下面进行STL的学习。希望能了解标准模板库中的常用容器,迭代器,可以自由运用STL以提高编写代码的效率。下面的内容我想以知识点为总结,不再像
《Effective C++》
那样以章节进行总结,这样写可能毫无组织,但可以看到整个学习的历程。。
一、Contents
- C++模板
- 类模板
template
class Test{ //下面的函数使用了T1,T2模板 int count(T1 x, T2 y){ return x.num + y.num; } };
+ 函数模板 ```cpp //使用传进来的str构造一个容器类Container templateT make(string str){ return Container(str.begin(), str.end()); } //----------------------------------------------- //make函数的使用vector, list, deque... vector vStr = make >("hello"); list lStr = make
>("hello"); deque dStr = make >("hello"); // ...
+ 成员函数模板(在类模板中,还可以使用成员函数模板,两者不受影响)```cpp templateclass Test{ //下面的函数使用了T1,T2模板 int count(T1 x, T2 y){ return x.num + y.num; } template void show(T x){ std::cout< <
2. 默认模板参数```cpp template> class vector{ // ... }
通过allocator<T>
为第2个模板参数Allocator
赋一个初值,allocator
类型(用户自己定义的一个类)则在未提供第二个模板时使用。这样,vector<int>
和vector<int, allocator<int>
都是可以的。
- 容器
- 序列容器
vector<T>
:提供对变长序列的随机访问deque<T>
:提供对变长序列的随机访问list<T>
:提供对变长序列的线性时间访问O(N),其中N是序列的当前长度。
- 顺序关联容器
set<Key>
惟一的键multi<Key>
可重复的键map<Key, T>
惟一的键索引类型Tmultimap<Key, T>
可重复的键索引类型T
- 序列容器
#include
- 类属算法
//1. reverse: 逆序 reverse(vector.begin(), vector.end()); //2. find: 在序列中查找特定值'e' string::iterator it = find(str.begin(), str.end(), 'e'); //map中的find map::iterator it = _map.find(key); //3. merge: 将两个容器中的东西拷贝到一个容器中 /** * @func: merge * @params: first1, last1分别表示输入序列的起始和终止位置 * @params: first2, last2分别表示另一个输入序列的起始和终止位置 * @params: result表示合并后序列存放的位置 * @example: 合并string与list到deque * merge(str, str+strlen(str), list1.begin(), list1.end(), deque1.begin()); * merge(str.begin(), str.end(), list1.begin(), list1.end(), deque1.begin()); * * @comments: !!!注意,这里的两个输入都必须是升序排列的,否则报错 */ merge(first1, last1, first2, last2, result); //4. replace: 替换其中的值 replace(a.begin(), a.end(), 'a', 'b'); //5. copy: 拷贝一段东西到另一个容器中 copy(a.begin(), a.end(), b.begin());
-
迭代器
- 输入迭代器
- 输出迭代器
- 前向迭代器
- 双向迭代器
- 随机访问迭代器
- 插入迭代器
- back_insert_iterator
- front_insert_iterator
- insert_iterator
- 流迭代器
- istream_iterator
- ostream_iterator
-
函数对象
-
适配器
-
分配器