Home > OS >  priority_queue of vectors in increasing order
priority_queue of vectors in increasing order

Time:08-03

I'm trying to build a priority_queue of vectors in increasing order of the first element in each vector, in C . Could someone help me with this? I can use a normal priority_queue with all vector elements in negative sign but is there some other way to do that? Thanks already :)

CodePudding user response:

You can pass it a different comparator. The default is std::less, but here you'll want std::greater, for example:

#include <functional>

typedef std::vector<int> ItemType;

std::priority_queue<
  ItemType,                                      // Type of items
  std::priority_queue<ItemType>::container_type, // Type of container
  std::greater<ItemType>                         // Comparison functor
  >
  my_queue;

Notice the trick in the second template argument to avoid copying the default value.

CodePudding user response:

Yes you can use std::greater or lambda function.

std::priority_queue<int, std::vector<int>, std::greater<int>>
        pq(data.begin(), data.end());

Or

auto cmp = [](int left, int right) { return left < right; };
std::priority_queue<int, std::vector<int>, decltype(cmp)> pq(cmp);
  • Related