c++
排序比较
Node定义
struct Node {
int time;
int st; // 1 is up, 0 is down
Node(int _time, int _st) : time(_time), st(_st) {}
};
class 比较
struct cmp {
bool operator()(const Node* a, const Node* b) const {
if (a->time == b->time) return a->st < b->st;
return a->time < b->time;
}
};
static 函数比较
static bool cmp(const Node* a, const Node* b) {
if (a->time == b->time) return a->st < b->st;
return a->time < b->time;
}
匿名函数
sort(planes.begin(), planes.end(), [](const Node* a, const Node* b) {
if (a->time == b->time) return a->st < b->st;
return a->time < b->time;
});
堆
默认大根堆
priority_queue<int, vector<int>> maxHeap;
c++自带比较器
priority_queue<int, vector<int>, greater<int>> minHeap;
priority_queue<int, vector<int>, less<int>> maxHeap;
自定义
小根堆
struct cmp {
bool operator() (const int &a, const int &b) {
return a > b;
}
};
priority_queue<int, vector<int>, cmp> minHeap;
小根堆
struct cmp {
bool operator() (const int &a, const int &b) {
return a < b;
}
};
priority_queue<int, vector<int>, cmp> maxHeap;
代码内部lambda函数自定义比较
unordered_map<char, int> hash;
auto cmp = [&](const char &a, const char &b) {
return hash[a] < hash[b];
};
priority_queue<char, vector<char>, decltype(cmp)> maxHeap{cmp};