C++ 将参数传递给比较函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4066576/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 14:28:12  来源:igfitidea点击:

Passing a parameter to a comparison function?

c++sortingstl

提问by George41

When using the STL sort algorithm on a vector, I want to pass in my own comparison function which also takes a parameter.

在向量上使用 STL 排序算法时,我想传入我自己的比较函数,该函数也接受一个参数。

For example, ideally I want to do a local function declaration like:

例如,理想情况下我想做一个局部函数声明,如:

int main() {
    vector<int> v(100);
    // initialize v with some random values

    int paramA = 4;

    bool comp(int i, int j) {
        // logic uses paramA in some way...
    }

    sort(v.begin(), v.end(), comp);
}

However, the compiler complains about that. When I try something like:

但是,编译器对此有所抱怨。当我尝试类似的事情时:

int main() {
    vector<int> v(100);
    // initialize v with some random values

    int paramA = 4;

    struct Local {
        static bool Compare(int i, int j) {
            // logic uses paramA in some way...
        }
    };

    sort(v.begin(), v.end(), Local::Compare);
}

The compiler still complains: "error: use of parameter from containing function"

编译器仍然抱怨:“错误:使用包含函数的参数”

What should I do? Should I make some global variables with a global comparison function..?

我该怎么办?我应该使用全局比较函数创建一些全局变量吗?

Thanks.

谢谢。

回答by Adam Rosenfield

You cannot access the local variables of a function from within a locally defined function -- C++ in its current form does not allow closures. The next version of the language, C++0x, will support this, but the language standard has not been finalized and there is little support for the current draft standard at the moment.

您不能从局部定义的函数内部访问函数的局部变量——当前形式的 C++ 不允许闭包。该语言的下一版本 C++0x 将支持这一点,但语言标准尚未最终确定,目前对当前草案标准的支持很少。

To make this work, you should change the third parameter of std::sortto be an object instanceinstead of a function. The third parameter of std::sortcan be anything that is callable (i.e. any xwhere adding parentheses like x(y, z)makes syntactic sense). The best way to do this is to define a struct that implements the operator()function, and then pass an instance of that object:

为了使这项工作,你应该改变的第三个参数std::sort是一个对象实例,而不是一个功能。的第三个参数std::sort可以是任何可调用的参数(即x,在x(y, z)句法上添加括号的任何地方)。最好的方法是定义一个实现该operator()函数的结构体,然后传递该对象的一个​​实例:

struct Local {
    Local(int paramA) { this->paramA = paramA; }
    bool operator () (int i, int j) { ... }

    int paramA;
};

sort(v.begin(), v.end(), Local(paramA));

Note that we have to store paramAin the structure, since we can't access it otherwise from within operator().

请注意,我们必须存储paramA在结构中,因为否则我们无法从 内部访问它operator()

回答by Prasoon Saurav

In C++ you cannot define a free function inside another function. So your first code snippet is ill formed.

在 C++ 中,您不能在另一个函数中定义自由函数。所以你的第一个代码片段格式不正确。

sort(v.begin(), v.end(), Local::Compare);

sort(v.begin(), v.end(), Local::Compare);

The 3rd argument must be a function object. Overload ()operator inside the class and then create the function object.

第三个参数必须是一个函数对象。()在类内部重载运算符,然后创建函数对象。



In C++0x you can use lambda expressions.

在 C++0x 中,您可以使用lambda 表达式

auto comp = [&](int m,int n)-> bool {

        return m<n; //or use paramA in some way
    };

sort(v.begin(), v.end(), comp);

回答by Jerry Coffin

One possibility is to pass the parameter when you construct your comparator object:

一种可能性是在构造比较器对象时传递参数:

class cmp {
    int param;
public:
    cmp(int p) : param(p) {}

    bool operator()(int i, int j) {
        // logic uses param
    }
};

int main() {
    vector<int> v(100);
    // initialize v with some random values

    int paramA = 4;

    sort(v.begin(), v.end(), cmp(paramA));
}

回答by dang son

//Using std::bind

//使用 std::bind

//Example

//例子

{
vector<int> vecInt{2, 4, 10, 20, 30};
    int i = 4;
    sort(vecInt.begin(), vecInt.end(), std::bind( [](int a, int b, int c)
    {
        return abs(a - c) < abs(b - c);
    }, std::placeholders::_1, std::placeholders::_2, i)
    );
}