简体   繁体   中英

Type error in C++ when instantiating a priority_queue of int pairs with a custom comparator (to implement a min heap)

Currently working through a leetcode problem for which I need a min Heap of pairs.
I am trying to use a priority_queue with int pair s and a custom compare type.
Attempts of implementation of the same have failed with the following error:

In file included from prog_joined.cpp:1: In file included from./precompiled/headers.h:55: In file included from /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/queue:64: /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_queue.h:467:7: error: static_assert failed due to requirement 'is_same<int, std::pair<int, int>>::value' "value_type must be the same as the underlying container" static_assert(is_same<_Tp, typename _Sequence::value_type>::value, ^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Line 9: Char 67: note: in instantiation of template class 'std::priority_queue<int, std::vector<std::pair<int, int>, std::allocator<std::pair<int, int>>>, std::greater>' requested here priority_queue<int, vector<pair<int, int>>, greater> pq;

Here's the code with which I'm trying to implement the heap:

#include <queue>
#include <utility>
using namespace std;
//...
priority_queue<int, pair<int, int>, greater<int>> pq;

As you can see in the std::priority_queue documentation :

  • The 1st template argument is the data type (should be pair<int,int> in your case).
  • The 2nd template argument should be the underlying container type used for the queue.
  • The 3rd should be the compare type.

For example if you want a priority_queue of int pair s that use std::vector as a container, you need:

std::priority_queue<std::pair<int, int>,                  // data type
                    std::vector<std::pair<int,int>>,      // container type
                    std::greater<std::pair<int,int>>> pq; // compare type

Note: as you can see here the std::pair implementation for comparison operators which are used by std::greater is:

Compares lhs and rhs lexicographically by operator<, that is, compares the first elements and only if they are equivalent, compares the second elements.

If this is not what you need you can implement your own compare type for std::pair<int,int> .

A side note: it is better to avoid using namespace std . See here: Why is "using namespace std;" considered bad practice? .

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