I have code that continuously extracts the object with the maximum value from the heap and processes it. However, during processing, max affects other objects in the heap and may need to be deleted. Roughly speaking:
vector<HeapEntry*> myHeap = vector<HeapEntry*>();
fillHeap(myHeap, someData);
make_heap(myHeap.begin(), myHeap.end());
while (!myHeap.empty())
{
HeapEntry* hp = myHeap.front();
HeapEntry* neighbor = hp->getNeighbor();
if (someCondition)
{
remove(myHeap, neighbor);
}
}
And the remove function:
void remove(vector<HeapEntry*> myHeap, HeapEntry* toRemove)
{
for (it = myHeap.begin(); it != myHeap.end(); it++)
{
if (*it == hp)
{
myHeap.erase(it);
break;
}
}
make_heap(myHeap.begin(), myHeap.end());
}
This is done and gives the correct result. But it is slow, like all hell: 2 minutes to process a file of 40 kilobytes in size (the heap size is linear in file size). In any case, it should be more effective.
The delete function ends up being called about n times, where n is the size of the heap. So this linear search makes the whole algorithm O (n ^ 2). I think the problem is, and I believe that this can work in O (n * log (n)).
My goal is to execute the delete function in O (log (n)) time. Sort of:
- pop_heap (myHeap.begin(), myHeap.end()); myHeap.pop_back();
- make_heap (myHeap.begin(), myHeap.end());
, ( stl).
- , , ?