[英]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 。
我的問題是:
我的理解是否正確,或者 std::map 中的函數類型和比較器類型是否存在更險惡的情況?
是否有一個簡單的解決方案來使用用戶定義的比較器聲明 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;
}
只是好奇是否有更簡單的解決方案,並試圖更好地理解正在發生的事情。
感謝和感謝任何幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.