目录
1. STL组件
由容器、迭代器、算法三部分组成。
2. 容器
2.1 容器分类
分为三类,且每一种包含的类型皆在下图中显示:
2.2 三种容器实现原理
2.3 关联式和无序容器的小知识点
- 可以认为是“索引是任意类型”的数组。
- 关联式和无序容器会自动排序元素,因此,它们键值(key)必须是常量。
2.4 容器适配器
3. 迭代器
3.1 迭代器概念与基本操作
3.2 迭代器的半开区间性质
3.3 迭代器的小知识点
- ++it vs. it++ 自增的效率对此:
- Range-Based for 循环 vs. 迭代器 实现关系
3.4 迭代器种类
关于随机访问迭代器,功能高级,但有些容器不支持,所以使用时得注意,特别进行泛型编程时要考虑好这一点的差异。比如:
// 示例1
coll.begin() - coll.end()
// 示例2
coll.begin() + 1
coll.begin() + 3
// 示例3
for (auto it = coll.begin(); pos < coll.end(); ++it) {
...
}
// 示例4
++coll.begin()
// 示例5
for (auto it = coll.begin(); pos != coll.end(); ++it) {
...
}
示例1、示例2和示例3是第三种迭代器特有的:
示例1,返回的是两个迭代器之间的距离。
示例2,可以直接使用算术运算。
示例3,操作 ’ < ’ 比较迭代器。
为了通用,应当尽可能使用示例4和示例5。
4. 算法
用法示例:
#include <algorithm>
#include <vector>
#include <iostream>
using namespace std;
int main()
{
// create vector with elements from 1 to 6 in arbitrary order
vector<int> coll = { 2, 5, 4, 1, 6, 3 };
// find and print minimum and maximum elements
auto minpos = min_element(coll.cbegin(),coll.cend());
cout << "min: " << *minpos << endl;
auto maxpos = max_element(coll.cbegin(),coll.cend());
cout << "max: " << *maxpos << endl;
// sort all elements
sort (coll.begin(), coll.end());
// find the first element with value 3
// - no cbegin()/cend() because later we modify the elements pos3 refers to
auto pos3 = find (coll.begin(), coll.end(), // range
3); // value
// reverse the order of the found element with value 3 and all following elements
reverse (pos3, coll.end());
// print all elements
for (auto elem : coll) {
cout << elem << ' ';
}
cout << endl;
}
4.1 算法的处理区间
比如下面的例子:
#include <algorithm>
#include <list>
#include <iostream>
using namespace std;
int main()
{
list<int> coll;
// insert elements from 20 to 40
for (int i=20; i<=40; ++i) {
coll.push_back(i);
}
// find position of element with value 3
// - there is none, so pos3 gets coll.end()
auto pos3 = find (coll.begin(), coll.end(), // range
3); // value
// reverse the order of elements between found element and the end
// - because pos3 is coll.end() it reverses an empty range
reverse (pos3, coll.end());
// find positions of values 25 and 35
list<int>::iterator pos25, pos35;
pos25 = find (coll.begin(), coll.end(), // range
25); // value
pos35 = find (coll.begin(), coll.end(), // range
35); // value
// print the maximum of the corresponding range
// - note: including pos25 but excluding pos35
cout << "max: " << *max_element (pos25, pos35) << endl;
// process the elements including the last position
cout << "max: " << *max_element (pos25, ++pos35) << endl;
}