c++ - C++ STL 集 : Can comparison function be a member function of a class? 的比较函数

标签 c++ stl set

我必须使用 STL 集并且我想定义我自己的比较函数。但根据我的要求,这个比较函数不应该是全局的,而应该是类的公共(public)成员。

//CLASS DEFINITION
class IDENTIFERS
{
public:
         IDENTIFIERS();
         ~IDENTIFIERS();
bool     compare_identifier(int Identifier, int Identifier);

public:
std::set <Identifier, bool(*)(Identifier, Identifier)>      set_instance;

};

//CLASS Constructor
IDENTIFIERS::IDENTIFIERS()
{
std::set <Identifier, bool(*)(Identifier, Identifier)>   set_instance(compare_identifier);
}

如果我像上面提到的那样写一段代码。它无法编译,因为比较函数的原型(prototype)与 compare_identifier() 函数不匹配。

有办法吗?

最佳答案

非静态成员函数为 this 采用隐式第一个参数,因此您的 compare_identifier 实际上有三个参数。如果你需要它是一个非静态成员函数,你需要将成员函数的隐式第一个参数绑定(bind)到一个IDENTIFIERS的实例上,例如,

#include <set>
#include <functional>

struct Identifier { int id; };

class IDENTIFERS
{
public:
  IDENTIFERS() : set_instance(std::bind(&IDENTIFERS::compare_identifier,
                                        this,                                               
                                        std::placeholders::_1,
                                        std::placeholders::_2))
  {}
  bool  compare_identifier(const Identifier& lhs, const Identifier& rhs)
  {
    return lhs.id < rhs.id;
  }

public:
  std::set <Identifier, std::function<bool(const Identifier&, const Identifier&)>> set_instance;

};

关于c++ - C++ STL 集 : Can comparison function be a member function of a class? 的比较函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17250622/

相关文章:

c++ - 如何取消引用 DWARF 中的引用

c++ - C++标准是否保证cin、cout等先创建后销毁?

python - 忽略元组比较中的值但仍检索它

python - 如何在 Python 中克隆或复制集合?

php - 如何在 (php/python) 和 C++ (Win32/Native Windows) 中的服务器端之间实现加密?

c++ - 使用 GDI+ 和 C++ 将 JPEG 编码的屏幕截图保存到缓冲区

c++ - 使用数组而不是 std::vector 的优点?

c++ - "error: no matching function for call to ' std::priority_queue<int>::priority_queue(int) ' priority_queue<int> pqueue(4); "

c++ - 将集合插入/读取到 map 中

c++ - g++ #include 文件未找到编译器错误