0

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 :)

  • `std::vector` have [relational operators](https://en.cppreference.com/w/cpp/container/vector/operator_cmp) so all you have to do is to decide if you want the queue to use the [less than](https://en.cppreference.com/w/cpp/utility/functional/less) (which is the default) or the [greater than](https://en.cppreference.com/w/cpp/utility/functional/greater) relation. [A `std::priority_queue` reference](https://en.cppreference.com/w/cpp/container/priority_queue) might also come in handy. – Some programmer dude Aug 02 '22 at 09:03

2 Answers2

3

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.

Thomas
  • 174,939
  • 50
  • 355
  • 478
0

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);
GAVD
  • 1,977
  • 3
  • 22
  • 40
  • 1
    Worth noting that from C++20 the argument for `pq` is unnecessary, since stateless lambdas became default-constructible. – Fureeish Aug 02 '22 at 09:36