STL 是什么
- STL = Standard Template Library,首先他是一个 Library,也就是一个函数库,就像大家以前用的函数sin/random等来自数学库,printf/fopen/fread/fwrite等来自 io 库, strcpy/strcmp/strcat 等来自己字符串库。库避免了重复造轮子,提高了开发效率。
- 其次,就是 Template,中文是模板的意思, 模板解决了什么问题呢, 泛型编程,泛型编程最早也是一种理念, 简单的来讲就是用一种模子,解决一类问题。 C++引入Template 后,泛型编程才算是落到了实处,其实也是解决避免重复造轮子,提高开发效率的问题。
- 再者就是, Standard 标准。为什么说是标准呢,己经被 C++委员会纳入 C++标准的一部分。以前说 C++有三大特征,封装,继承,多态。现在至少要说, C++四大特征 封装,继承,多态和 STL。
STL组成图示
STL 主要由空间适配器 allocator,容器 container,算法 algorithm,迭代器iterator 和仿函数 functor
对应示例代码:
#include <iostream> #include <vector> #include <algorithm> using namespace std; class Compare { public: bool operator()(int x, int y) { return x<y; } }; int main() { int arr[10] = {1,3,5,6,7,2,4,6,8,10}; vector<int,allocator<int>> vi(arr,arr+10);//vector容器,allocator空间适配器 vector<int>::iterator itr;//迭代器 for(itr = vi.begin(); itr != vi.end(); itr++) { cout<<*itr<<endl; } sort(vi.begin(),vi.end(),Compare());//sort算法,Compare仿函数 for(auto &i:vi) cout<<i<<endl; return 0; }