为了账号安全,请及时绑定邮箱和手机立即绑定

使用自定义std :: set比较器

使用自定义std :: set比较器

C++
牛魔王的故事 2019-07-24 14:47:23
使用自定义std :: set比较器我试图将一组整数中的项的默认顺序更改为lexicographic而不是numeric,并且我无法使用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’我究竟做错了什么?
查看完整描述

3 回答

?
哈士奇WWW

TA贡献1799条经验 获得超6个赞

您正在使用一个函数,因为您应该使用仿函数(一个重载()运算符的类,因此可以像函数一样调用它。

struct lex_compare {
    bool operator() (const int64_t& lhs, const int64_t& rhs) const {
        stringstream s1, s2;
        s1 << lhs;
        s2 << rhs;
        return s1.str() < s2.str();
    }};

然后使用类名作为类型参数

set<int64_t, lex_compare> s;

如果你想避免仿函数样板代码,你也可以使用函数指针(假设lex_compare是一个函数)。

set<int64_t, bool(*)(const int64_t& lhs, const int64_t& rhs)> s(&lex_compare);


查看完整回答
反对 回复 2019-07-24
?
杨魅力

TA贡献1811条经验 获得超5个赞

1.现代C ++ 11解决方案

auto cmp = [](int a, int b) { return ... };std::set<int, decltype(cmp)> s(cmp);

我们使用lambda函数作为比较器。像往常一样,比较器应该返回布尔值,指示作为第一个参数传递的元素是否被认为是在它定义的特定严格弱顺序中的第二个之前。

在线演示

2.与第一种解决方案类似,但功能代替lambda

使比较器成为通常的布尔函数

bool cmp(int a, int b) {
    return ...;}

然后使用它

std::set<int, decltype(&cmp)> s(&cmp);

在线演示

3.使用struct with ()operator的旧解决方案

struct cmp {
    bool operator() (int a, int b) const {
        return ...
    }};// ...// laterstd::set<int, cmp> s;

在线演示

4.替代解决方案:从布尔函数创建struct

采取布尔函数

bool cmp(int a, int b) {
    return ...;}

并使用它来构建struct std::integral_constant

#include <type_traits>using Cmp = std::integral_constant<decltype(&cmp), &cmp>;

最后,使用struct作为比较器

std::set<X, Cmp> set;

在线演示


查看完整回答
反对 回复 2019-07-24
?
泛舟湖上清波郎朗

TA贡献1818条经验 获得超3个赞

Yacoby的回答激励我编写一个用于封装仿函数样板的适配器。

template< class T, bool (*comp)( T const &, T const & ) >class set_funcomp {
    struct ftor {
        bool operator()( T const &l, T const &r )
            { return comp( l, r ); }
    };public:
    typedef std::set< T, ftor > t;};// usagebool my_comparison( foo const &l, foo const &r );set_funcomp< foo, my_comparison >::t boo; // just the way you want it!

哇,我觉得那值得一试!


查看完整回答
反对 回复 2019-07-24
  • 3 回答
  • 0 关注
  • 792 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信