在 C++ 中,cmp 函数通常用作比较器,用于定义排序规则或自定义数据结构的相等性判断。它可以在多种数据结构中使用,例如:
std::sort)中,cmp 函数可以用来定义元素之间的排序规则。例如:#include<algorithm>#include<vector>#include<iostream>bool cmp(int a, int b) { return a > b; // 降序排列}int main() { std::vector<int> v = {3, 1, 4, 1, 5, 9}; std::sort(v.begin(), v.end(), cmp); for (int i : v) { std::cout << i << " "; } return 0;}优先队列(堆):在优先队列(如 std::priority_queue)中,cmp 函数可以用来定义元素的优先级。例如:#include<queue>#include<iostream>bool cmp(int a, int b) { return a > b; // 最小堆}int main() { std::priority_queue<int, std::vector<int>, decltype(&cmp)> pq(cmp); pq.push(3); pq.push(1); pq.push(4); while (!pq.empty()) { std::cout << pq.top() << " "; pq.pop(); } return 0;}关联容器:在关联容器(如 std::map、std::set)中,cmp 函数可以用来定义元素的排序规则。例如:#include <map>#include<iostream>bool cmp(const std::string &a, const std::string &b) { return a.size() < b.size(); // 按字符串长度排序}int main() { std::map<std::string, int, decltype(&cmp)> m(cmp); m["apple"] = 1; m["banana"] = 2; m["cherry"] = 3; for (const auto &p : m) { std::cout << p.first << ": " << p.second<< std::endl; } return 0;}请注意,在这些示例中,我们使用了 C++11 的 lambda 表达式来定义 cmp 函数。你也可以使用普通的函数指针或者自定义的比较类。


