What is the C++ equivalent using std::priority_queue (C++ STL) of this Java code

The elements of the queue are vectors, and thus that is the type of object that are being compared to each other. vector<int> a[1] is not a vector, but an array of vectors of length 1 (although as a function argument, it will be adjusted in this case to be a pointer to the element of that array i.e. pointer to vector). As such, the argument type of the comparison object doesn’t match the element type of the container and is thus wrong.

One way to fix it is to change the argument to be a reference to const qualified element of the queue – you will want to use a reference in order to avoid unnecessarily copying the vectors on each comparison. But perhaps even simpler is to use auto so that the type is deduced like it is in the Java example:

auto cmp = [](const auto& a, const auto& b) {
    return a[1] < b[1];

Furthermore, the comparison object is not a template argument. The template argument is the type of the comparison object. Lastly, your example lacks a name for the variable. A fixed example:

priority_queue<vector<int>, vector<vector<int>>, decltype(cmp)> pq(cmp);

For maximal type deduction, you could use the constructor that accepts the underlying container as argument:

vector<vector<int>> v; // you may optionally populate the queue here
priority_queue pq {cmp, std::move(v)};

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top