I have a std::vector
, that I use std::heap
on it.
I want in a while loop, to pop the minimum value, every time the loop starts. In the body of the loop, another element will be inserted in the heap. The loop stops after a number of runs.
What came to my mind is to use std::sort_heap
and then erase the first element. However, this doesn't seem to be a good idea. You see, speed is of real essence at this part of my code.
I don't think that this is a good idea, because I have to call std::sort_heap
at every run, because an element is going to be inserting, thus making the std::vector
a heap again, which means that I have to sort it again, in order the minimum element to be placed at the front.
Moreover, erasing from start, with vector.erase()
is slower than erasing the last element, right? If I delete the first element, then all the others have to be moved one position to the left. If I delete the last, element, I just pay the cost of deletion.
That lead me to this idea, sort the vector my way, so that the minimum element will come to the end, thus paying the deletion of the last element only. However, this still requires sorting at every run of the loop, right?
Which is the optimal approach to tackle this problem?