如何将参数传递到自定义比较C 中分类的函数

How to pass parameters to custom compare function for sorting in C++

本文关键字:分类 函数 比较 自定义 参数传递      更新时间:2023-10-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

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

在另一个注意事项上,您实际上不需要两个返回语句

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