常见快速类型转换
1.int
->string
#include <string>
#include <iostream>int num = 123;
std::string str = std::to_string(num);
std::cout << str << std::endl; // 输出 "123"
2.string
-> int
#include <sstream>
int str_to_int(string str_) {int num;std::stringstream ss(str_);ss >> num; // 从字符串流读取到 intreturn num;//0123 -> 123
}
STL常见用法
String
快速清空数组为0/-1,但是不建议为其他除了0/-1之外的数字
#include <cstring> // for memsetint arr[1000];
memset(arr, 0, sizeof(arr)); // 全部置 0
其他算法
查找类
高效查找两个固定数组的共同元素
哈希
//哈希
#include <unordered_set>
#include <vector>long long count_ele(const std::vector<long long> &a,const std::vector<long long> &b) {std::unordered_set<long long> set_a(a.begin(),a.end()); // 将数组 a 存入哈希表long long count = 0;for (int num : b) {if (set_a.count(num)) { // 检查 b 的元素是否在 a 中存在count++;}}return count;
}
双指针
long long count_elements(std::vector<long long> &a, std::vector<long long> &b) {std::sort(a.begin(), a.end()); std::sort(b.begin(), b.end()); long long i = 0, j = 0, count = 0;while (i < a.size() && j < b.size()) {if (a[i] == b[j]) {count++;i++;j++;} else if (a[i] < b[j]) {i++;} else {j++;}}return count;
}
gcd lcm
lld gcd(lld x, lld y) {if (y == 0) {return x;} else {return gcd(y, x % y);}
}lld lcm(lld x, lld y) { return x * y / gcd(x, y);
}
附录
ASCII对照表
//number
0: 48
b: 49
...
9: 57
//快速把char输出为int
cout << x - 48 << endl;//word
a: 97
b: 98
...
z: 122
头文件
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <functional>
#include <iostream>
#include <ostream>
#include <sstream>
#include <string>#define lld long long // long long 的printf 占位符是lld
#define ENDL '\n' // 将 endl 替换为 \n 取消缓冲区const long long MAX_ = 1e9;using std::cin;
using std::cout;
using std::endl;
using std::string;
已知两个固定数组的大小和内容,查找两个数组a b有多少共同元素
高效的算法