亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用自定義std :: set比較器

使用自定義std :: set比較器

C++
蝴蝶刀刀 2019-11-23 15:15:38
使用自定義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 回答

?
白衣非少年

TA貢獻1155條經驗 獲得超0個贊

您正在使用一個函數,因為您應該使用仿函數(一個重載()運算符的類,因此可以像函數一樣調用它。

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-11-24
?
拉風的咖菲貓

TA貢獻1995條經驗 獲得超2個贊

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-11-24
?
江戶川亂折騰

TA貢獻1851條經驗 獲得超5個贊

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-11-24
  • 3 回答
  • 0 關注
  • 513 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號