自定义比较器
控制排序顺序
自定义比较器 是 CoddyKit 上的免费 C++ Academy 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 C++ Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 C++ Academy 课程共包含 4 节课。
为什么需要自定义比较器
默认情况下,有序容器使用 std::less 按升序排序。自定义比较器可以改变排序顺序,例如改为降序,或根据特定字段排序。
#include <iostream>
#include <set>
int main() {
std::set<int> ascending{3, 1, 2};
for (int x : ascending) std::cout << x << ' ';
std::cout << '\n';
return 0;
}使用 std::greater 按降序排序
最简单的自定义比较器是标准函子 std::greater,它会按降序排序。
#include <iostream>
#include <set>
#include <functional>
int main() {
std::set<int, std::greater<int>> s{3, 1, 2};
for (int x : s) std::cout << x << ' ';
std::cout << '\n';
return 0;
}映射中的比较器
比较器是 std::map 的第三个模板参数。在这里,键会从大到小排序。
#include <iostream>
#include <map>
#include <functional>
int main() {
std::map<int, std::string, std::greater<int>> m{
{1, "one"}, {3, "three"}, {2, "two"}
};
for (const auto& [k, v] : m) std::cout << k << ':' << v << ' ';
std::cout << '\n';
return 0;
}比较器的工作方式
比较器是一个接受两个参数的可调用对象;如果第一个参数应排在第二个参数之前,则返回 true。它必须定义严格弱序。
#include <iostream>
struct Less {
bool operator()(int a, int b) const { return a < b; }
};
int main() {
Less cmp;
std::cout << std::boolalpha << cmp(2, 5) << '\n';
std::cout << cmp(5, 2) << '\n';
return 0;
}自定义结构体比较器
请定义一个带有 operator() 的函子结构体,并将其类型作为比较器传入。
#include <iostream>
#include <set>
struct ByAbs {
bool operator()(int a, int b) const {
return (a < 0 ? -a : a) < (b < 0 ? -b : b);
}
};
int main() {
std::set<int, ByAbs> s{-5, 3, -1, 4};
for (int x : s) std::cout << x << ' ';
std::cout << '\n';
return 0;
}按长度排序字符串
比较器可以比较任意属性。在这里,字符串先按长度排序,再按字母顺序排序,以解决长度相同的情况。
#include <iostream>
#include <set>
#include <string>
struct ByLen {
bool operator()(const std::string& a, const std::string& b) const {
if (a.size() != b.size()) return a.size() < b.size();
return a < b;
}
};
int main() {
std::set<std::string, ByLen> s{"bbb", "a", "cc", "dd"};
for (const auto& x : s) std::cout << x << ' ';
std::cout << '\n';
return 0;
}为什么次级比较条件很重要
如果比较器认为两个元素都不应排在另一个元素之前,容器就会将它们视为相等。在 set 中,这意味着其中一个元素会被当作重复项丢弃。
#include <iostream>
#include <set>
#include <string>
struct LenOnly {
bool operator()(const std::string& a, const std::string& b) const {
return a.size() < b.size();
}
};
int main() {
std::set<std::string, LenOnly> s{"ab", "cd", "x"};
std::cout << s.size() << " elements\n";
return 0;
}将 Lambda 用作比较器
您可以通过 decltype 传入 Lambda 的类型,并将 Lambda 本身传给构造函数。
#include <iostream>
#include <set>
int main() {
auto cmp = [](int a, int b) { return a > b; };
std::set<int, decltype(cmp)> s(cmp);
s.insert(1);
s.insert(3);
s.insert(2);
for (int x : s) std::cout << x << ' ';
std::cout << '\n';
return 0;
}priority_queue 中的比较器
比较器也可以配置 std::priority_queue。配合 std::greater 后,它会变成最小堆。
#include <iostream>
#include <queue>
#include <vector>
#include <functional>
int main() {
std::priority_queue<int, std::vector<int>, std::greater<int>> pq;
pq.push(5); pq.push(1); pq.push(3);
while (!pq.empty()) { std::cout << pq.top() << ' '; pq.pop(); }
std::cout << '\n';
return 0;
}比较键值对
如果要按照键值对的第二个元素为一组键值对排序,请编写一个检查 .second 的比较器。
#include <iostream>
#include <set>
#include <utility>
struct BySecond {
bool operator()(const std::pair<int,int>& a, const std::pair<int,int>& b) const {
return a.second < b.second;
}
};
int main() {
std::set<std::pair<int,int>, BySecond> s{{1, 9}, {2, 3}, {3, 6}};
for (const auto& p : s) std::cout << p.first << ':' << p.second << ' ';
std::cout << '\n';
return 0;
}透明比较器
使用 std::less<>(空尖括号)可以在 C++14 中启用异构查找,从而避免临时的键类型转换。
#include <iostream>
#include <set>
#include <functional>
int main() {
std::set<int, std::less<>> s{1, 2, 3};
std::cout << (s.find(2) != s.end() ? "found" : "no") << '\n';
return 0;
}快速检查
请测试您对比较器如何定义相等关系的理解。
总结
您已经学会,自定义比较器:
- 通过容器的比较器模板参数改变排序顺序
- 可以是
std::greater、函子结构体,或通过decltype使用的 Lambda - 通过等价关系定义相等,因此始终应加入次级比较条件,以避免丢失不同的元素
下一课程:使用 std::unordered_map 进行快速的基于哈希的查找。
用 AI 导师学习 C++ — 免费
在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。
- 课程
- 51
- 课程
- 203
常见问题解答
「自定义比较器」课时是免费的吗?
是的 — 「自定义比较器」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 C++ Academy 课程的其余内容,请升级到 CoddyKit PRO。 C++ Academy 课程共包含 4 节课。
「自定义比较器」这节课中我会学到什么?
控制排序顺序 你通过在浏览器中直接运行的动手代码来练习 C++ Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 C++ Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 C++ Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。
「自定义比较器」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 C++ Academy 课中编写并运行代码吗?
能。每节 C++ Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。