编程语言
首页 > 编程语言> > [Cheat Sheet] C/C++ STL

[Cheat Sheet] C/C++ STL

作者:互联网

Resources

Algorithm

https://hackingcpp.com/cpp/std/algorithms.png

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

size & capacity

size, 当前容器实际包含的元素个数

capacity, 当前容器总容量, 预留空间大小

iteration

// 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<int> items;
for (int i = 0; i < items.size(); i++) cout << items[i] << endl;
map<int, int> mappers;
for (auto m : mappers) cout << m.first << ' ' << m.second << endl;

assignment

vector<int> v;
v.assign(size);
v.assign(size, value);
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