第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

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

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

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

C++
牛魔王的故事 2019-07-24 14:47:23
使用自定義std :: set比較器我試圖將一組整數(shù)中的項的默認順序更改為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條經(jīng)驗 獲得超6個贊

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

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();
    }};

然后使用類名作為類型參數(shù)

set<int64_t, lex_compare> s;

如果你想避免仿函數(shù)樣板代碼,你也可以使用函數(shù)指針(假設(shè)lex_compare是一個函數(shù))。

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


查看完整回答
反對 回復(fù) 2019-07-24
?
楊魅力

TA貢獻1811條經(jīng)驗 獲得超6個贊

1.現(xiàn)代C ++ 11解決方案

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

我們使用lambda函數(shù)作為比較器。像往常一樣,比較器應(yīng)該返回布爾值,指示作為第一個參數(shù)傳遞的元素是否被認為是在它定義的特定嚴(yán)格弱順序中的第二個之前。

在線演示

2.與第一種解決方案類似,但功能代替lambda

使比較器成為通常的布爾函數(shù)

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.替代解決方案:從布爾函數(shù)創(chuàng)建struct

采取布爾函數(shù)

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

并使用它來構(gòu)建struct std::integral_constant

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

最后,使用struct作為比較器

std::set<X, Cmp> set;

在線演示


查看完整回答
反對 回復(fù) 2019-07-24
?
泛舟湖上清波郎朗

TA貢獻1818條經(jīng)驗 獲得超3個贊

Yacoby的回答激勵我編寫一個用于封裝仿函數(shù)樣板的適配器。

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!

哇,我覺得那值得一試!


查看完整回答
反對 回復(fù) 2019-07-24
  • 3 回答
  • 0 關(guān)注
  • 912 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號