c++ - 如果成员函数需要多个参数,则使用 mem_fun_ref

标签 c++

不幸的是,我不能使用 C++11 或 Boost。

我有一些类似下面的代码

struct Cell
{
    Cell(int value) : value(value) {}

    int value;

    bool CompareValue(const Cell& other) const
    {
        return this->value < other.value;
    }
};

int main()
{
    const int size = 10;
    vector<Cell> cells;
    for (int i = 0; i < size; i++)
    {
        cells.push_back(Cell(rand()));
        cout << "[ " << cells.back().value << " ] ";
    }
    cout << "\n\n";

    int maxvalue = max_element(cells.begin(), cells.end(), mem_fun_ref(&Cell::CompareValue))->value;
    int minvalue = min_element(cells.begin(), cells.end(), mem_fun_ref(&Cell::CompareValue))->value;

    cout << "Max = " << maxvalue << "\n" << "Min = " << minvalue << "\n";
}

但是现在我需要扩展compare函数来取一个compare MODE

bool CompareValue(const Cell& other, MODE_T mode) const
{
    switch (mode)
    {
        ...
    }
}

但是,我不知道如何更新 max_element 的使用以使用这个新函数。模式参数对于每次比较运行都是相同的。我尝试使用各种绑定(bind)和东西但无济于事。任何帮助表示赞赏。

最佳答案

你可以写functor,它会做这样的事情。

struct CompareCellWithMode : public std::binary_function<Cell, Cell, bool>
{
public:
   result_type CompareCellWithMode
   (const first_argument_type& f, const second_argument_type& s)
   {
      return f.CompareValue(s, mode);
   }
private:
   MODE_T mode;
};

MODE_T mode;
int maxvalue = max_element(cells.begin(), 
cells.end(), CompareCellWithMode(mode))->value;

或使用 std::tr1::bind

MODE_T mode;
int maxvalue = max_element(cells.begin(), cells.end(), 
std::tr1::bind(&Cell::CompareValue, _1, mode))->value;

关于c++ - 如果成员函数需要多个参数,则使用 mem_fun_ref,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17236878/

相关文章:

c++ - WarpAffine 函数在与 openCL 和 opencv 一起使用时抛出错误

c++ - 什么时候使用openGL将数据发送到GPU

c++ - 使用随机值初始化二维 vector

C++11:v = { } 和 v { } 之间的区别

c++ - 不能重载仅由返回类型区分的函数

c++ - 这是什么返回 2 而不是 0?

c++ - 为什么指向 vector 中变量的指针保持有效?

c++ - 如何以编程方式查找加载的共享库的版本?

c++ - 当 C++ 尝试访问 vector 的元素(在范围内)时,Qt Quick Windows 应用程序崩溃

c++ - 多个包含在多个文件中