将参数传递给比较函数? [英] Passing a parameter to a comparison function?

查看:84
本文介绍了将参数传递给比较函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在向量上使用STL排序算法时,我想传递自己的比较函数,该函数也带有一个参数.

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

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);
}

但是,编译器对此有所抱怨.当我尝试类似的东西时:

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);
}

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

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

谢谢.

解决方案

您不能从本地定义的函数中访问函数的局部变量-当前形式的C ++不允许

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

Thanks.

解决方案

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.

To make this work, you should change the third parameter of std::sort to be an object instance instead of a function. The third parameter of std::sort can be anything that is callable (i.e. any x where 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:

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 paramA in the structure, since we can't access it otherwise from within operator().

这篇关于将参数传递给比较函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆