mirror of
https://github.com/nim-lang/Nim.git
synced 2026-07-21 00:11:26 +00:00
Add items and contains to heapqueue (#23296)
The implementation of these functions are trivial yet they were missing from the module.
This commit is contained in:
@@ -47,6 +47,9 @@ runnableExamples:
|
||||
|
||||
import std/private/since
|
||||
|
||||
when defined(nimPreviewSlimSystem):
|
||||
import std/assertions
|
||||
|
||||
type HeapQueue*[T] = object
|
||||
## A heap queue, commonly known as a priority queue.
|
||||
data: seq[T]
|
||||
@@ -73,6 +76,13 @@ proc `[]`*[T](heap: HeapQueue[T], i: Natural): lent T {.inline.} =
|
||||
## Accesses the i-th element of `heap`.
|
||||
heap.data[i]
|
||||
|
||||
iterator items*[T](heap: HeapQueue[T]): lent T {.inline, since: (2, 1, 1).} =
|
||||
## Iterates over each item of `heap`.
|
||||
let L = len(heap)
|
||||
for i in 0 .. high(heap.data):
|
||||
yield heap.data[i]
|
||||
assert(len(heap) == L, "the length of the HeapQueue changed while iterating over it")
|
||||
|
||||
proc heapCmp[T](x, y: T): bool {.inline.} = x < y
|
||||
|
||||
proc siftup[T](heap: var HeapQueue[T], startpos, p: int) =
|
||||
@@ -178,6 +188,11 @@ proc find*[T](heap: HeapQueue[T], x: T): int {.since: (1, 3).} =
|
||||
for i in 0 ..< heap.len:
|
||||
if heap[i] == x: return i
|
||||
|
||||
proc contains*[T](heap: HeapQueue[T], x: T): bool {.since: (2, 1, 1).} =
|
||||
## Returns true if `x` is in `heap` or false if not found. This is a shortcut
|
||||
## for `find(heap, x) >= 0`.
|
||||
result = find(heap, x) >= 0
|
||||
|
||||
proc del*[T](heap: var HeapQueue[T], index: Natural) =
|
||||
## Removes the element at `index` from `heap`, maintaining the heap invariant.
|
||||
runnableExamples:
|
||||
|
||||
Reference in New Issue
Block a user