1.vector
1.0 数组定义
vector<int> arr;vector<vector<int>> res(N,vector<int>(M));
1.1 基本数据类型自定义排序
1.1.1 自定义cmp方法
bool cmp(const int &a, const int &b) { return a < b; };vector<int> arr = {2, 1, 6, 5, 4, 9, 0};sort(arr.begin(), arr.end(), cmp);
1.1.2 lamda 方式实现
sort(arr.begin(), arr.end(), [](int a, int b) { return a < b; });
1.2 实体类自定义排序
//二维 点struct Point {int x, y;Point() {}Point(int _x, int _y) : x(_x), y(_y) {}};vector<Point> arr = {{1, 2}, {2, 3}, {-1, 3}};sort(arr.begin(), arr.end(), [](Point &a, Point &b) {if (a.x == b.x) {return a.y < b.y;} else {return a.x < b.x;}});
2.priority_queue
2.1 使用pair
2.1.1 默认排序
priority_queue<pair<int, int>> queue;
默认先排 first ,然后 再排 second
2.1.2 自定义排序
struct cmp {bool operator()(const pair<int, int> &a, const pair<int, int> &b) {if (a.first == b.first) {return a.second < b.second;} else {return a.first < b.first;}}};priority_queue<pair<int, int>, vector<pair<int, int>>, cmp> queue;queue.emplace(2, 1);queue.emplace(3, 2);queue.emplace(1, 5);queue.emplace(3, 3);queue.emplace(4, -1);4== -13== 33== 22== 11== 5
2.2 使用 int 数组
2.2.1 升降序
priority_queue < int, vector<int>, greater<int> > que;默认升序
priority_queue < int > que;默认降序
3.unordered_map
3.1 使用pair做key
需要重载hash方法
// 重载 hashmap使用pair 时 hash算法;
struct pair_hash {
template <class T1, class T2> size_t operator()(const pair<T1, T2> &p) const {
auto h1 = hash<T1>{}(p.first);
auto h2 = hash<T2>{}(p.second);
return h1 ^ h2;
}
};
unordered_map<pair<int, int>, int, pair_hash> pair_hashMap;
pair_hashMap.insert({{1, 2}, 1});
pair_hashMap.insert({{2, 2}, 1});
for (auto &a : pair_hashMap) {
cout << a.first.first << " " << a.first.second << " " << a.second << "\n";
}
