Skip to content

Commit

Permalink
delete! for PriorityQueue (#428)
Browse files Browse the repository at this point in the history
* delete! for PriorityQueue
Closes #343

* Update test_priority_queue.jl

* Update priority-queue.md

* correct test for #343
  • Loading branch information
scls19fr authored and oxinabox committed Aug 12, 2018
1 parent 6941c29 commit 55a2fce
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 0 deletions.
1 change: 1 addition & 0 deletions docs/src/priority-queue.md
Expand Up @@ -14,6 +14,7 @@ enqueue!(pq, k, v) # insert the key k into pq with priority v
enqueue!(pq, k=>v) # (same, using Pairs)
dequeue!(pq) # remove and return the lowest priority key
peek(pq) # return the lowest priority key without removing it
delete!(pq, k) # delete the mapping for the given key in a priority queue, and return the priority queue.
```

`PriorityQueue` also behaves similarly to a `Dict` in that keys can be
Expand Down
20 changes: 20 additions & 0 deletions src/priorityqueue.jl
Expand Up @@ -313,6 +313,26 @@ function dequeue_pair!(pq::PriorityQueue, key)
dequeue_pair!(pq)
end

"""
delete!(pq, key)
Delete the mapping for the given key in a priority queue, and return the priority queue.
# Examples
```jldoctest
julia> q = PriorityQueue(Base.Order.Forward, "a"=>2, "b"=>3, "c"=>1)
PriorityQueue{String,Int64,Base.Order.ForwardOrdering} with 3 entries:
"c" => 1
"b" => 3
"a" => 2
julia> delete!(q, "b")
DataStructures.PriorityQueue{String,Int64,Base.Order.ForwardOrdering} with 2 entries:
"c" => 1
"a" => 2
```
"""
function delete!(pq::PriorityQueue, key)
dequeue_pair!(pq, key)
pq
end

# Unordered iteration through key value pairs in a PriorityQueue
iterate(pq::PriorityQueue) = iterate(pq.index)
Expand Down
7 changes: 7 additions & 0 deletions test/test_priority_queue.jl
Expand Up @@ -202,6 +202,13 @@ import Base.Order.Reverse
@test dequeue_pair!(pq, 'b') == ('b'=>4)
@test length(pq) == 3
end

@testset "delete!" begin
pq = PriorityQueue(Base.Order.Forward, "a"=>2, "b"=>3, "c"=>1)
pq_out = delete!(pq, "b")
@test pq === pq_out
@test Set(collect(pq)) == Set(["a"=>2, "c"=>1])
end
end

@testset "LowLevelHeapOperations" begin
Expand Down

0 comments on commit 55a2fce

Please sign in to comment.