c++priority-queue

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.


Solution

  • 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.