1.vector

1.0 数组定义

  1. vector<int> arr;
  2. vector<vector<int>> res(N,vector<int>(M));

1.1 基本数据类型自定义排序

1.1.1 自定义cmp方法

  1. bool cmp(const int &a, const int &b) { return a < b; };
  2. vector<int> arr = {2, 1, 6, 5, 4, 9, 0};
  3. sort(arr.begin(), arr.end(), cmp);

1.1.2 lamda 方式实现

  1. sort(arr.begin(), arr.end(), [](int a, int b) { return a < b; });

1.2 实体类自定义排序

  1. //二维 点
  2. struct Point {
  3. int x, y;
  4. Point() {}
  5. Point(int _x, int _y) : x(_x), y(_y) {}
  6. };
  7. vector<Point> arr = {{1, 2}, {2, 3}, {-1, 3}};
  8. sort(arr.begin(), arr.end(), [](Point &a, Point &b) {
  9. if (a.x == b.x) {
  10. return a.y < b.y;
  11. } else {
  12. return a.x < b.x;
  13. }
  14. });

2.priority_queue

2.1 使用pair

2.1.1 默认排序

  1. priority_queue<pair<int, int>> queue;

默认先排 first ,然后 再排 second

2.1.2 自定义排序

  1. struct cmp {
  2. bool operator()(const pair<int, int> &a, const pair<int, int> &b) {
  3. if (a.first == b.first) {
  4. return a.second < b.second;
  5. } else {
  6. return a.first < b.first;
  7. }
  8. }
  9. };
  10. priority_queue<pair<int, int>, vector<pair<int, int>>, cmp> queue;
  11. queue.emplace(2, 1);
  12. queue.emplace(3, 2);
  13. queue.emplace(1, 5);
  14. queue.emplace(3, 3);
  15. queue.emplace(4, -1);
  16. 4== -1
  17. 3== 3
  18. 3== 2
  19. 2== 1
  20. 1== 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";
    }