STL是Standard Template Library的简称,标准模板库。从根本上说,STL是一些“容器”的集合,这些“容器”有list, vector, set, map等,STL也是算法和其他一些组件的集合。STL的目的是标准化组件,这样就不用重新开发,可以使用现成的组件。
STL已成为C++标准程序库的大脉系,因此,目前所有的 C++ 编译器一定支持有一份STL在相应的各个C++头文件(headers)中。STL并非以二进制代码面貌出现,而是以源代码面貌供应。
STL六大组件相互交互如图1:
图1
STL六大组件的交互关系:Container通过Allocator取得数据储存空间,Algorithm 通过 lterator存取 Container 内容,Functor 可以协助 Algorithm完成不同的策略变化,Adapter可以修饰或套接Functor。
- 容器(containers):各种数据结构,如vector,1ist,deque,set,map,用来存放数据。
- 算法(algorithms):各种常用算法如sort,search,copy,erase…。从实现的角度来看,STL算法是一种function template.
- 迭代器(iterators):扮演容器与算法之间的胶合剂,是所谓的“泛型指针”。共有五种类型,以及其它衍生变化。从实现的角度来看,迭代operator--等指针器是一种将 operator*,operator->,operator++,相关操作予以重载的class template。所有STL容器都附带有自己专属的迭代器——是的,只有容器设计者才知道如何遍历自己的元素。原生指针(native pointer)也是一种迭代器。
- 仿函数(functors):行为类似函数,可作为算法的某种策略(policy)。从实现的角度来看,仿函数是一种重载了operator()的class或class template。一般函数指针可视为狭义的仿函数。
- 配接器(adapters):一种用来修饰容器(containers)或仿函数(functors)或迭代器(iterators)接口的东西。例如,STL提供的queue和stack,虽然看似容器,其实只能算是一种容器配接器,因为它们的底部完全借助deque,所有操作都由底层的deque供应。改变functor接口者,称为function adapter;改变 container 接口者,称为 container adapter; 改变iterator接口者,称为iterator adapter。
- 配置器(allocators):负责空间配置与管理。从实现的角度来看,配置器是一个实现了动态空间配置、空间管理、空间释放的 class template。
六大组件code实例展示:
#include <vector>
#include <algorithm>
#include <functional>
#include <iostream>
using namespace std;
int main()
{
int ia[6] = { 27, 210, 12, 47, 109, 83 };
//使用vector container
//<int, allocator<int>>模板初始化,allocator分配空间。
vector<int, allocator<int>> vi(ia, ia + 6);
//使用vector的iterator { vi.begin(), vi.end()}
//使用算法algorithm {count_if()}
//使用function adapter {not1(bind2nd())}
//使用functiono object {less<int>()}
cout << count_if(vi.begin(), vi.end(),
not1(bind2nd(less<int>(), 40)));
return 0;
}
参考文献:
STL源码剖析