使用自定义 std::set 比较器 [英] Using custom std::set comparator

查看:64
本文介绍了使用自定义 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 比较器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆