0

I tried to allocate memory to the priority_queue using the constructor, but getting the below error:

No matching constructor for initialization of 'priority_queue pq(3)'

why this is not working in priority_queue but working correctly in vectors?

#include <iostream> 
#include <queue> 
using namespace std; 

int main() 
{ 

priority_queue<int> pqueue(4); 
pqueue.push(3); 
pqueue.push(5); 
pqueue.push(1); 
pqueue.push(2); 

}
mrazimi
  • 337
  • 1
  • 3
  • 12
R_M_R
  • 31
  • 6
  • 1
    Even for `std::vector` this would not just allocate memory, but initialize it as well. Your example would yield a vector containing (0,0,0,0,3,5,1,2). Be aware of that. – eike Sep 17 '19 at 09:21

2 Answers2

2

related question

std::priority_queue doesn't have such constructor, but the below code implements what you want:

std::vector<int> temporary_container(4);

std::priority_queue<int, std::vector<int>> pqueue (comparator, std::move(container));

Also if you want not to change the size of queue and only reserve memory, you can do it like below:

std::vector<int> temporary_container;
temporary_container.reserve(4);

std::priority_queue<int, std::vector<int>> pqueue (comparator, std::move(container));

Using this ways, you should define your comparator and pass it to the constructor.

mrazimi
  • 337
  • 1
  • 3
  • 12
  • You didn't mention any difference between priority_queue and vector which answer the question: "why this is not working in priority_queue but working correctly in vectors?". – Hoseyn Heydari Sep 17 '19 at 12:00
  • 1
    @HoseynHeydari `queue` has its own concept. It's not `vector` and we won't access randomly to each element or change their value, so maybe it's not useful generally to en-queue several elements with a value of `0` (which are all equivalent), at starting. Anyway, this constructor is not implemented for `std::queue` and that is the reason we can not use it. – mrazimi Sep 17 '19 at 13:24
0

A std::priority_queue has a restrictive interface, isn't the same thing as a std::vector and doesn't have that constructor.

See https://en.cppreference.com/w/cpp/container/priority_queue/priority_queue for constructor summary.

To fix the compile error, you may just do instead:

priority_queue<int> pqueue{}; 
darune
  • 10,480
  • 2
  • 24
  • 62
  • Actually, you can use constructor (3) and pass in a preinitialized `std::vector`. Doesn't help for memory allocation though, as it just copy constructs the internal container. – eike Sep 17 '19 at 09:23