【问题标题】:How to pass parameters to custom compare function for sorting in C++如何将参数传递给自定义比较函数以在 C++ 中进行排序
【发布时间】:2018-07-27 07:22:16
【问题描述】:

我有一个自定义比较功能:

bool compare(int a, int b){
    if(a>2*b) return true;
    return false;
}

现在我想像这样使用这个函数:

vector<int> numbers;//say it contains random numbers
sort(numbers.begin(), numbers.end(), compare(a, b));//a and b are the numbers that sort function currently compares to each other

很明显,这段代码是行不通的,因为程序不知道 a 和 b 是什么。我的问题是,如何传递所需的数字来比较函数?

【问题讨论】:

  • 你没有。 std::sort 这样做。
  • 只需sort(numbers.begin(), numbers.end(), compare) 工作。
  • 顺便说一句,如果这是你真正的函数,你就有麻烦了——compare() 函数需要实现一个总排序,而这个不需要。

标签: c++ function sorting parameters parameter-passing


【解决方案1】:

这里有一个关于如何使用 std::sort 的好答案

https://stackoverflow.com/a/1380496/6115571

另一方面,你的函数中并不需要两个 return 语句

bool compare(int a, int b) {
  return (a>2*b);
}

【讨论】:

  • 您也不需要在返回的表达式周围加上括号。 return a&gt;2*b; 做同样的事情。有些人喜欢括号,但这完全是风格问题。
猜你喜欢
  • 1970-01-01
  • 2020-07-10
  • 1970-01-01
  • 2011-06-05
  • 2013-11-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多