简体   繁体   中英

c++: priority_queue: lambda-expression in template-argument

I am trying to create a priority_queue with each element as a 3D vector. The element whose third dimension has the largest value would become the priority element.

Here is my code:

   priority_queue< vector<int>, vector<vector<int>>, [](vector<int> &v1, vector<int> &v2){
        return v1[2] > v2[2];
    }> pq{};

but I got the following error:

error: lambda-expression in template-argument

Any idea what I did wrong? Thanks!

You cant have a lambda (which is an object) in a type template declaration (where a type is needed. Do instead:

auto lambda =  [](vector<int> &v1, vector<int> &v2){
    return v1[2] > v2[2];
};
priority_queue< vector<int>, vector<vector<int>>,decltype(lambda)> pq{lambda};

We also need to pass the lambda since it is not default constructible.

Form C++20 on, we can do the following:

priority_queue< vector<int>, vector<vector<int>>,decltype([](vector<int> &v1, vector<int> &v2){
    return v1[2] > v2[2];
};
)> pq{};

Here there come two new featurs of lambdas into play. First that you can take the type of it directly (formally: In C++17 you cannot have a lambda-expression in unevaluated context) and second that lambdas are default constructible. But right now, that is not yet possible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM