2015-09-28 125 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}; 
};