Using custom std::set comparator(使用自定义 std::set 比较器)
问题描述
我正在尝试将一组整数中项目的默认顺序更改为字典顺序而不是数字,但我无法使用 g++ 编译以下内容:
I am trying to change the default order of the items in a set of integers to be lexicographic instead of numeric, and I can't get the following to compile with g++:
file.cpp:
bool lex_compare(const int64_t &a, const int64_t &b)
{
stringstream s1,s2;
s1 << a;
s2 << b;
return s1.str() < s2.str();
}
void foo()
{
set<int64_t, lex_compare> s;
s.insert(1);
...
}
我收到以下错误:
error: type/value mismatch at argument 2 in template parameter list for ‘template<class _Key, class _Compare, class _Alloc> class std::set’
error: expected a type, got ‘lex_compare’
我做错了什么?
推荐答案
1.现代 C++20 解决方案
auto cmp = [](int a, int b) { return ... };
std::set<int, decltype(cmp)> s;
我们使用 lambda 函数作为比较器.像往常一样,比较器应该返回布尔值,指示作为第一个参数传递的元素是否被认为在特定 严格弱排序 它定义了.
We use lambda function as comparator. As usual, comparator should return boolean value, indicating whether the element passed as first argument is considered to go before the second in the specific strict weak ordering it defines.
在线演示
auto cmp = [](int a, int b) { return ... };
std::set<int, decltype(cmp)> s(cmp);
在 C++20 之前,我们需要将 lambda 作为参数传递给 set 构造函数
Before C++20 we need to pass lambda as argument to set constructor
在线演示
像往常一样制作比较器
bool cmp(int a, int b) {
return ...;
}
然后以这种方式使用它:
Then use it, either this way:
std::set<int, decltype(cmp)*> s(cmp);
在线演示
或者这样:
std::set<int, decltype(&cmp)> s(&cmp);
在线演示
struct cmp {
bool operator() (int a, int b) const {
return ...
}
};
// ...
// later
std::set<int, cmp> s;
在线演示
取布尔函数
bool cmp(int a, int b) {
return ...;
}
并使用 std::integral_constant
#include <type_traits>
using Cmp = std::integral_constant<decltype(&cmp), &cmp>;
最后,使用结构体作为比较器
Finally, use the struct as comparator
std::set<X, Cmp> set;
在线演示
这篇关于使用自定义 std::set 比较器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用自定义 std::set 比较器
基础教程推荐
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 我有静态或动态 boost 库吗? 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
