簡體   English   中英

C++ class 成員的用戶定義比較器

[英]User defined comparator for member of C++ class

我有一個關於以下代碼的快速問題:

#include <iostream>
#include <string>
#include <map>

using namespace std;

struct mySet{
    
    mySet(){
    }

    auto compare = [](int a, int b){ return a > b; };
    
    map<int, int, bool(*)(int, int)> myMap(compare);
    
    void insert(int x){
        if(myMap.find(x) == myMap.end()) myMap[x] = 1;
        else myMap[x]++;
    }
    
    void output(){
        for(auto p : myMap) cout << p.first << " " << p.second << endl;   
    }
};

int main()
{
  mySet thing;
  thing.insert(1);
  thing.insert(2);
  thing.insert(1);
  thing.output();
}

這段代碼引發了一個錯誤,我懷疑它圍繞

    auto compare = [](int a, int b){ return a > b; };
    
    map<int, int, bool(*)(int, int)> myMap(compare);

我的理解是這不會編譯,因為 compare 是 class 的成員,它需要一個實例才能被調用。

如果我將此代碼替換為

    static auto compare = [](int a, int b){ return a > b; };

它仍然無法編譯,因為它至少需要一個 mySet 實例才能調用 compare 。

我的問題是:

  1. 我的理解是否正確,或者 std::map 中的函數類型和比較器類型是否存在更險惡的情況?

  2. 是否有一個簡單的解決方案來使用用戶定義的比較器聲明 class 的成員? 我最簡單的想法就是將成員聲明為

std::map<int, int, bool(*)(int, int)> myMap;

然后將 function 傳遞給構造函數,例如

mySet( bool(*f)(int, int) ){
     map<int, int, bool(*)(int, int)> newMap (f);
     myMap = newMap;
}

只是好奇是否有更簡單的解決方案,並試圖更好地理解正在發生的事情。

感謝和感謝任何幫助。

您不能使用auto聲明非靜態成員。

並且 static 非整數類型的非 constexpr 數據成員的類內初始化也不可能。

類內初始化不使用(){} (或= )(以避免令人煩惱的解析問題)

所以你可以使用:

static constexpr auto compare = [](int a, int b){ return a > b; };
    
std::map<int, int, bool(*)(int, int)> myMap{compare};

演示

或者在你的情況下,簡單地說:

std::map<int, int, std::greater<int>> myMap;

演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM