不幸的是,我不能使用 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/