是自己做题中整理的常用C++操作,此为存档。
STL容器
容器适配器,STL里面的vector/array/deque/set/map/unordered_set可以直接使用==比较是否相等:
vector<int> a; deque<int> a; map<int, string> a;
unordered_map<int, string> a;
set<int> a;
unordered_set<int> a;
forward_list<int> a; // 单向链表 list<int> a; // 双向链表 priority_queue<int> a; // 最大堆 stack<int> a; // 栈模拟 queue<int> a; // 队列模拟
unordererd_set的查找(C++20):
unordered_set<int> hash; bool result = hash.contains(a);
priority_queue自定义比较函数:
std::less<int>() std::greater<int>() [](int a, int b)(return a<b;);
unordered_set自定义hash函数:
#include <iostream> #include <unordered_set> #include <string> #include <utility> // for std::pair// 自定义哈希函数 struct pair_hash {template <class T1, class T2>std::size_t operator() (const std::pair<T1, T2>& p) const {auto hash1 = std::hash<T1>{}(p.first);auto hash2 = std::hash<T2>{}(p.second);return hash1 ^ hash2; // 组合两个哈希值,使用XOR }};int main() {// 使用自定义哈希函数std::unordered_set<std::pair<std::string, std::string>, pair_hash> dp;// 插入一些元素dp.insert({"hello", "world"});dp.insert({"foo", "bar"});return 0;}
泛型算法
求最大最小:
std::min_element(a.begin(), a.end());
std::max_element(a.begin(), a.end());
二分搜索(要求有序):
it = std::upper_bound(a.begin(), a.end(), val); // *it > val it = std::lower_bound(a.begin(), a.end(), val); //*it >= Val
* 如果找不到的话,会返回a.end()
* 如果使用的是std::binary_search的话,只能返回一个bool值,并且还要提前保证数组有序
* 如果是想求等于某元素的情况,可以用:
// 从开始位置到i位置=k的结果 upper_bound(nums.begin(), nums.begin()+i+1, k) - lower_bound(nums.begin(), nums.begin()+i+1, k);
使用<numeric>的accumulate迭代器求和:
int sum = stdaccumulate(vec.begin(), vec.end(), 0);
使用fill函数填充:
std::fill(a.begin(), a.end(), 1);
在STL的泛型函数中使用谓词:
int evenCount = std::count_if(vec.begin(), vec.end(), [](int n) {return n % 2 == 0;}); std::sort(vec.begin(), vec.end(), compare);
使用STL里面的copy操作(from origin to destination),注意copy的第二个参数是尾后迭代器
字符串
字符串切片
sub = str.substr(7, 5); // start at 7 length 5 sub = str.substr(5); // start at 5 length to the end
与c风格字符串的转化
string str = std::to_string(pi); // int, float to string const char* cstr = str.c_str();
读取字符流并提取单个单词
std::vector<std::string> splitString(const std::string& str){std::vector<std::string> result;std::stringstream ss(str);std::string word;// 使用流提取运算符 (>>) 从字符串流中逐个提取单词while (ss >> word) {result.push_back(word);}return result;}