[Cheat Sheet] C/C++ STL
作者:互联网
Resources
- Hacking CPP https://hackingcpp.com/
- 在线编译器 https://www.programiz.com/cpp-programming/online-compiler/
Algorithm
sort
bool cmp(const vector<int>& a, const vector<int>& b) {
return a[0] == b[0]? a[1] < b[1]: a[0] < b[0];
}
vector<vector<int>> arrs;
sort(arrs.begin(), arrs.end(), cmp);
sort(arrs.begin(), arrs.end(), [](const vector<int>& a, const vector<int>& b) {
return COST(a) < COST(b);
});
Container
STL 容器常用操作: 创建, 遍历, 增删查改, ...
basic
-
assignment
: 创建, 赋值 -
iteration
: 迭代 -
insert / erase
: 值, 添加 / 删除 -
interact with C
: 与 C 风格指针函数交互
size & capacity
size
, 当前容器实际包含的元素个数
size()
→ number of elements in vectorresize(new_number_of_elements)
assign(size, value)
→ 直接分配元素个数
capacity
, 当前容器总容量, 预留空间大小
capacity()
→ number of available memory slotsreserve(new_capacity)
iteration
common
// range based loop
for (auto i : items); // 'i' is a reference to an item of items
for (auto &i : items); // 'i' is copied from an item of items
for (auto const &i : items); // const & avoid making copies
// iterators
for (auto i = begin(items); i != end(items); ++i) { cout << *i << endl; };
for (auto i = rbegin(items); i != rend(items); ++i) { cout << *i << endl; }; // reverse
for (auto i = cbegin(items); i != cend(items); ++i) { cout << *i << endl; }; // const
vector
vector<int> items;
for (int i = 0; i < items.size(); i++) cout << items[i] << endl;
map
map<int, int> mappers;
for (auto m : mappers) cout << m.first << ' ' << m.second << endl;
assignment
assign
vector<int> v;
v.assign(size);
v.assign(size, value);
constructor
vector<int> v2(v.begin(), v.end());
vector<int> vec1 {10, 20, 30};
vector<int> vec2 = {10, 20, 30}; // c++[11, 14, 17, ...]
static const int arr[] = {16,2,77,29};
vector<int> vec3(arr, arr + sizeof(arr)/sizeof(arr[0]));
References
标签:Sheet,Cheat,items,STL,vector,arrs,auto,const,size 来源: https://www.cnblogs.com/crayonsea/p/14616251.html