简体   繁体   中英

How to write lambda with captures for the comparator of std::priority_queue

I have following code snippet where I would like to create a lambda expression but with a capture for the std::priority_queue:

    vector<vector<int>> arrays;
    ......

    // I'd like to create a lambda comparator which will access the element of arrays
    auto cmp = [&arrays](const pair<size_t, size_t> &a, const pair<size_t, size_t> &b) -> bool
    {
       return arrays[a.first][a.second] >= arrays[b.first][b.second];
    };

    // Then, I'd like to put this lambda to be used in the priority queue.
    std::priority_queue<pair<size_t, size_t>, vector<pair<size_t, size_t>>, decltype(cmp)> queue;

However, I will get following compilation errors because Clang would like to insert a parameter when constructing the cmp:

No matching constructor for initialization of 'value_compare' Candidate constructor (the implicit copy constructor) not viable: requires 1 argument, but 0 were provided

Any suggestions on this? Thanks.

You have to pass an instance of decltype(cmp) (say, cmp ) to the queue when constructing it.

The type of the lambda does not store which array was caputured. That state is in the value of the lambda, thus must be passed by value.

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