2015-09-28 93 views
0

我可以用函數指針作爲其比較器來聲明一個集合作爲數據成員嗎?自定義std ::設置比較使用函數指針

bool lex_compare (const int& lhs, const int & rhs){ 
     return true; 
    }; 

// So I can define a std::set testSet using function pointer: 
set<int, bool(*)(const int & lhs, const int & rhs)> testSet (&lex_compare); 

我的問題是我應該如何聲明和定義測試集作爲使用函數指針作爲比較數據成員?

注:我知道,仿函數可以在我的情況的解決方案:

struct lex_compare { 
    bool operator() (const int& lhs, const int& rhs) const{ 
     return ture; 
    } 
}; 

set<int, lex_compare> testSet; 

我是個有興趣,如果有一種方法是函數指針可以做。

回答

4

我的問題是我應該如何聲明和定義測試集作爲使用函數指針作爲比較數據成員?

你可以聲明它就像你有,

set<int, bool(*)(const int &, const int &)> testSet; 

您可以在構造函數的成員初始化列表初始化。

MyClass::MyClass() : testSet (&lex_compare) { ... } 

推薦

可以簡化lex_compare到:

bool lex_compare (int lhs, int rhs){ ... } 
1

它基本上是相同的,如果你在一個類中這樣做:

struct MyClass { 
    static bool lex_compare (const int& lhs, const int & rhs){ 
      return ...; 
     }; 

    set<int, bool(*)(const int & lhs, const int & rhs)> testSet; 

    MyClass() 
    : testSet(&lex_compare) 
    { 
    } 
}; 

讓您lex_compare功能是靜態使它成爲一個常規函數,以便您可以獲得常規函數指針。

用C++ 11或更高,這可以簡化爲:

struct MyClass { 
    static bool lex_compare(const int& lhs, const int & rhs){ 
      return ...; 
     }; 

    set<int, decltype(&lex_compare)> testSet {lex_compare}; 
}; 

作爲R薩胡所指出的,使用普通的整數作爲參數比較好,所以這成爲:

struct MyClass { 
    static bool lex_compare(int lhs, int rhs) { return ...; } 
    set<int, decltype(&lex_compare)> testSet {lex_compare}; 
};