diff options
author | Antonis Geralis <43617260+planetis-m@users.noreply.github.com> | 2024-02-09 14:19:36 +0200 |
---|---|---|
committer | GitHub <noreply@github.com> | 2024-02-09 13:19:36 +0100 |
commit | c234a2a661eb098fc5c6e0ccc4bda1da162373b0 (patch) | |
tree | 0ee3aa6809dab1d03c45bdd555055eb51ac03283 /lib/pure | |
parent | befb383ac8f033be94ca83845b1a26e9feeb3306 (diff) | |
download | Nim-c234a2a661eb098fc5c6e0ccc4bda1da162373b0.tar.gz |
Add items and contains to heapqueue (#23296)
The implementation of these functions are trivial yet they were missing from the module.
Diffstat (limited to 'lib/pure')
-rw-r--r-- | lib/pure/collections/heapqueue.nim | 15 |
1 files changed, 15 insertions, 0 deletions
diff --git a/lib/pure/collections/heapqueue.nim b/lib/pure/collections/heapqueue.nim index bcfdf37c2..96f9b4430 100644 --- a/lib/pure/collections/heapqueue.nim +++ b/lib/pure/collections/heapqueue.nim @@ -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: |