Remove an element from the middle of an std::heap

后端 未结 6 2135
离开以前
离开以前 2021-02-07 05:17

I\'m using a priority queue as a scheduler with one extra requirement. I need to be able to cancel scheduled items. This equates to removing an item from the middle of the pri

6条回答
  •  南旧
    南旧 (楼主)
    2021-02-07 05:56

    Here's a bit of delphi code i used to remove items from a heap. I don't know this C++ of which you speak and don't have a repair function, but hey..

    first the pop, so you get an idea of how the thing works:

    function THeap.Pop: HeapItem;
    begin
      if fNextIndex > 1 then begin
        Dec(fNextIndex);
        Result:= fBuckets[1];   //no zero element
        fBuckets[1] := fBuckets[fNextIndex];
        fBuckets[fNextIndex] := nil;
        FixHeapDown;            //this has a param defaulting to 
        end
      else
        Result:= nil;
    end;
    

    now to contrast, the deletion:

    procedure THeap.Delete(Item: HeapItem);
    var
      i:integer;
    begin
      for i:=1 to pred(fNextIndex) do
        if Item=fBuckets[i] then begin
          dec(fNextIndex);
          fBuckets[i] := fBuckets[fNextIndex];
          fBuckets[fNextIndex] := nil;
          FixHeapDown(i);
          break;
          end;
    end;
    

    its of course a no-no to even think about doing what we're doing here, but hey, costs do change sometimes and jobs do get canceled.

    enjoy. i hope this helps.

提交回复
热议问题