mirror of
https://github.com/nim-lang/Nim.git
synced 2026-02-12 22:33:49 +00:00
add sets.pop procedure (analogue to python) (#8383)
This commit is contained in:
@@ -347,6 +347,18 @@ proc excl*[A](s: var HashSet[A], other: HashSet[A]) =
|
||||
assert other.isValid, "The set `other` needs to be initialized."
|
||||
for item in other: discard exclImpl(s, item)
|
||||
|
||||
proc pop*[A](s: var HashSet[A]): A =
|
||||
## Remove and return an arbitrary element from the set `s`.
|
||||
##
|
||||
## Raises KeyError if the set `s` is empty.
|
||||
##
|
||||
for h in 0..high(s.data):
|
||||
if isFilled(s.data[h].hcode):
|
||||
result = s.data[h].key
|
||||
excl(s, result)
|
||||
return result
|
||||
raise newException(KeyError, "set is empty")
|
||||
|
||||
proc containsOrIncl*[A](s: var HashSet[A], key: A): bool =
|
||||
## Includes `key` in the set `s` and tells if `key` was added to `s`.
|
||||
##
|
||||
|
||||
22
tests/sets/tsetpop.nim
Normal file
22
tests/sets/tsetpop.nim
Normal file
@@ -0,0 +1,22 @@
|
||||
discard """
|
||||
targets: "c c++ js"
|
||||
output: '''1000
|
||||
0
|
||||
set is empty
|
||||
'''
|
||||
"""
|
||||
|
||||
import sets
|
||||
|
||||
var a = initSet[int]()
|
||||
for i in 1..1000:
|
||||
a.incl(i)
|
||||
echo len(a)
|
||||
for i in 1..1000:
|
||||
discard a.pop()
|
||||
echo len(a)
|
||||
|
||||
try:
|
||||
echo a.pop()
|
||||
except KeyError as e:
|
||||
echo e.msg
|
||||
Reference in New Issue
Block a user