0

I used heap-related operations to maintain a heap structure.

For example:

std::vector<int> a = {1,2,56, 2};
std::make_heap(a.begin(), a.end());
// add
a.push_back(3);
std::push_heap(a.begin(), a.end());
// erase
std::pop_heap(a.begin(), a.end());
int v = a.back();
a.pop_back();

Recently, I find there is a structure named priority_queue seems also implement a heap.

which has simpler function with push pop.

Is there any difference between these two? (performance, memory, and other things)

And which one you think is better?

can i use reserve to reduce memory allocate time since the container is vector (for heap operation)?

nick
  • 832
  • 3
  • 12
  • *"And which one you think is better?"* -- you should remove this part of the question as without objective criteria for "better", it is opinion-based. Plus, one question per question. – JaMiT Nov 20 '21 at 09:00
  • *"can i use reserve to [...]"* -- given Stack Overflow's prohibition against multiple questions in a question, I suggest removing this from your question. But before you post a new question for this, take a look at [priority_queue underlying vector container capacity resize](https://stackoverflow.com/questions/3666387/c-priority-queue-underlying-vector-container-capacity-resize). – JaMiT Nov 20 '21 at 09:08

1 Answers1

1

See cppreference.com:

Working with a priority_queue is similar to managing a heap in some random access container, with the benefit of not being able to accidentally invalidate the heap.

And in case it isn't clear: your code manages a heap in a random access container.

JaMiT
  • 14,422
  • 4
  • 15
  • 31