If you are willing to call std::pop_heap()
on your own container v
, then you can just first v.push_back()
on the container the "modified" element before popping the heap. Then, shrink v
.
// Precondition is that v is already a heap.
void change_max_element (std::vector<int> &v, int modified_value) {
v.push_back(modified_value);
std::pop_heap(v.begin(), v.end());
v.pop_back();
}
This "works" because std::pop_heap()
is defined to swap the first and last elements and bubble down. However, the requirement is also stated that the input sequence should be a valid heap. If we are able to define a specialized comparison operation that would allow the newly pushed back item to report itself to belong in the last position if it was already in the last position, then it could technically satisfy the requirement.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…