Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
386 views
in Technique[技术] by (71.8m points)

c++ - Passing a parameter to a comparison function?

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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().


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...