C/C++ STL

Resources

Algorithm

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);
});

next_permutation

string s = "2231";
  • return {bool}, 表示是否还有下一个增序 (或者自定义 cmp) 排列结果.
while (next_permutation(s.begin(), s.end())) {
    cout << "-" << s;
}
  • output
-2312-2321-3122-3212-3221

Container

STL 容器常用操作: 创建, 遍历, 增删查改, ...

basic

  • assignment: 创建, 赋值

  • iteration: 迭代

  • insert / erase: 值, 添加 / 删除

  • interact with C: 与 C 风格指针函数交互

size & capacity

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

  • size() → number of elements in vector
  • resize(new_number_of_elements)
  • assign(size, value)→ 直接分配元素个数

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

  • capacity() → number of available memory slots
  • reserve(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]));

String

string.png

Number <=> String

Number to String

int number = 123456;
string x = to_string(number);
cout << to_string(123.456) << endl; // 123.456
cout << to_string(1234567) << endl; // 1234567
cout << to_string(1e5+2) << endl;   // 100002.000000

String to Number (C++11)

stoi(); stol(); stoll();
stoul(); stoull();
stof(); stod(); stold();
  • stoi(str) example
std::string str1 = "45";                // 45
std::string str2 = "3.14159";           // 3
std::string str3 = "31337 with words";  // 31337

References

原文地址:https://www.cnblogs.com/crayonsea/p/14616251.html