STL体系结构与内核分析(侯捷)
2.STL体系结构基础介绍
STL设计方式与OO(面向对象)不同的地方,OO鼓励数据和处理数据的方法都放在类里,而STL的数据在容器里,操作数据的方法在其他部件里(模板编程)。
迭代器:泛化指针
STL六大部件:
示例代码:
#include <vector>
#include <algorithm>
#include <functional>
#include <iostream>
using namespace std;
int main() {
int ia[6] = {27, 210, 12, 40, 109, 93};
//vector 容器
//allocator 分配器
vector<int, allocator<int>> vi(ia, ia + 6);
//输出不小于40的数字的个数
//count_if 算法
//begin(),end()迭代器
//less 仿函数
//bind2nd 适配器(这里是仿函数适配器)
cout << count_if(vi.begin(), vi.end(), not1(bind2nd(less<int>(), 40)));
return 0;
}
f = std::bind1st( functor, v); 'f( x)'等价于'functor( v, x)'
f = std::bind2nd( functor, v); 'f( x)'等价于'functor( x, v)'
复杂度取决于数据分布等,具体情况具体分析(所以集成了多种不同算法,而不是唯一的最优算法)
容器特性:前闭后开,空间不一定是连续的
伪代码:
Container<T> C;
...
Container<T>::iterator ite = c.begin();
for (; ite != c.end(); ++ite)
...
range-based for statement(since C++11)–for不同用法
#include <vector>
#include <algorithm>
#include <functional>
#include <iostream>
using namespace std;
int main() {
vector<int, allocator<int>> v{1, 2, 3};
cout << "t1:";
for (int i : {1, 2, 3})
cout << i << " ";
cout << endl;
cout << "t2:";
for (auto i : v)
cout << i << " ";
cout << endl;
cout << "t3:";
for (auto &i : v) {//传引用
i *= 2;
cout << i << " ";
}
cout << endl;
cout << "t4:";
for (auto i : v)
cout << i << " ";
cout << endl;
return 0;
}
输出:
t1:1 2 3
t2:1 2 3
t3:2 4 6
t4:2 4 6