SortedBag
public struct SortedBag<Element: Comparable>: SetAlgebra
A sorted collection of comparable elements; also known as a multiset.
SortedBag is like a SortedSet except it can contain multiple members that are equal to each other.
Lookup, insertion and removal of any element has logarithmic complexity.
SortedBag stores duplicate elements in their entirety; it doesn’t just count multiplicities.
This is an important feature when equal elements can be distinguished by identity comparison or some other means.
(If you’re OK with just counting duplicates, use a Map or a Dictionary with the multiplicity as the value.)
SortedBag is a struct with copy-on-write value semantics, like Swift’s standard collection types.
It uses an in-memory b-tree for element storage, whose individual nodes may be shared with other sorted sets or bags.
Mutating a bag whose storage is (partially or completely) shared requires copying of only O(log(count)) elements.
(Thus, mutation of shared SortedBags may be cheaper than ordinary Sets, which need to copy all elements.)
Set operations on sorted bags (such as taking the union, intersection or difference) can take as little as O(log(n)) time if the elements in the input bags aren’t too interleaved.
See also
SortedSet
-
Create an empty bag.
Declaration
Swift
public init() -
Create a bag that holds the same members as the specified sorted set.
Complexity: O(1); the new bag simply refers to the same storage as the set.
Declaration
Swift
public init(_ set: SortedSet<Element>) -
Create a bag from a finite sequence of items. The sequence need not be sorted. If the sequence contains duplicate items, all of them are kept, in the same order.
Complexity
O(n * log(n)), where n is the number of items in the sequence.Declaration
Swift
public init<S: Sequence>(_ elements: S) where S.Iterator.Element == Element -
Create a bag from a sorted finite sequence of items. If the sequence contains duplicate items, all of them are kept.
Complexity
O(n), where n is the number of items in the sequence.Declaration
Swift
public init<S: Sequence>(sortedElements elements: S) where S.Iterator.Element == Element -
Create a bag with the specified list of items. If the array literal contains duplicate items, all of them are kept.
Declaration
Swift
public init(arrayLiteral elements: Element...)
-
Returns the element at the given index.
Requires
indexoriginated from an unmutated copy of this set.Complexity
O(1)Declaration
Swift
public subscript(index: Index) -> Element -
Return the subbag consisting of elements in the given range of indexes.
Requires
The indices inrangeoriginated from an unmutated copy of this bag.Complexity
O(log(count))Declaration
Swift
public subscript(range: Range<Index>) -> SortedBag<Element> -
The
past-the-end
element index; the successor of the last valid subscript argument.Complexity
O(1)Declaration
Swift
public var endIndex: Index -
The number of elements in this bag.
Declaration
Swift
public var count: Int -
True iff this collection has no elements.
Declaration
Swift
public var isEmpty: Bool -
Return an iterator over all elements in this map, in ascending key order.
Declaration
Swift
public func makeIterator() -> Iterator -
Returns the successor of the given index.
Complexity
Amortized O(1).Declaration
Swift
public func index(after index: Index) -> Index -
Replaces the given index with its successor.
Complexity
Amortized O(1).Declaration
Swift
public func formIndex(after index: inout Index) -
Returns the predecessor of the given index.
Complexity
Amortized O(1).Declaration
Swift
public func index(before index: Index) -> Index -
Replaces the given index with its predecessor.
Complexity
Amortized O(1).Declaration
Swift
public func formIndex(before index: inout Index) -
Returns an index that is at the specified distance from the given index.
Requires
indexmust be a valid index of this set. Ifnis positive, it must not exceed the distance fromindextoendIndex. Ifnis negative, it must not be less than the distance fromindextostartIndex.Complexity
O(log(count)) where count is the number of elements in the set.Declaration
Swift
public func index(_ i: Index, offsetBy n: Int) -> Index -
Offsets the given index by the specified distance.
Requires
indexmust be a valid index of this set. Ifnis positive, it must not exceed the distance fromindextoendIndex. Ifnis negative, it must not be less than the distance fromindextostartIndex.Complexity
O(log(count)) where count is the number of elements in the bag.Declaration
Swift
public func formIndex(_ i: inout Index, offsetBy n: Int) -
Returns an index that is at the specified distance from the given index, unless that distance is beyond a given limiting index.
Requires
indexandlimitmust be valid indices in this bag. The operation must not advance the index beyondendIndexor beforestartIndex.Complexity
O(log(count)) where count is the number of elements in the bag.Declaration
Swift
public func index(_ i: Index, offsetBy n: Int, limitedBy limit: Index) -> Index? -
Offsets the given index by the specified distance, or so that it equals the given limiting index.
Requires
indexandlimitmust be valid indices in this bag. The operation must not advance the index beyondendIndexor beforestartIndex.Complexity
O(log(count)) where count is the number of elements in the bag.Declaration
Swift
public func formIndex(_ i: inout Index, offsetBy n: Int, limitedBy limit: Index) -> Bool -
Returns the distance between two indices.
Requires
startandendmust be valid indices in this bag.Complexity
O(1)Declaration
Swift
public func distance(from start: Index, to end: Index) -> Int
-
Returns the subbag containing elements in the specified range of offsets from the start of the bag.
Complexity
O(log(count))Declaration
Swift
public subscript(offsetRange: Range<Int>) -> SortedBag<Element> -
Returns the element at
offsetfrom the start of the bag.Complexity
O(log(count))Declaration
Swift
public subscript(offset: Int) -> Element -
If
memberis in this bag, return the offset of its first instance. Otherwise, returnnil.Complexity
O(log(count))Declaration
Swift
public func offset(of member: Element) -> Int? -
Returns the offset of the element at
index.Complexity
O(log(count))Declaration
Swift
public func index(ofOffset offset: Int) -> Index -
Returns the index of the element at
offset.Requires
offset >= 0 && offset < countComplexity
O(log(count))Declaration
Swift
public func offset(of index: Index) -> Int
-
Call
bodyon each element inselfin ascending order.Declaration
Swift
public func forEach(_ body: (Element) throws -> Void) rethrows -
Return an
Arraycontaining the results of mapping transform overself.Declaration
Swift
public func map<T>(_ transform: (Element) throws -> T) rethrows -> [T] -
Return an
Arraycontaining the concatenated results of mappingtransformoverself.Declaration
Swift
public func flatMap<S : Sequence>(_ transform: (Element) throws -> S) rethrows -> [S.Iterator.Element] -
Return an
Arraycontaining the non-nilresults of mappingtransformoverself.Declaration
Swift
public func flatMap<T>(_ transform: (Element) throws -> T?) rethrows -> [T] -
Return an
Arraycontaining the elements ofself, in ascending order, that satisfy the predicateincludeElement.Declaration
Swift
public func filter(_ includeElement: (Element) throws -> Bool) rethrows -> [Element] -
Return the result of repeatedly calling
combinewith an accumulated value initialized toinitialand each element ofself, in turn. I.e., returncombine(combine(...combine(combine(initial, self[0]), self[1]),...self[count-2]), self[count-1]).Declaration
Swift
public func reduce<T>(_ initialResult: T, _ nextPartialResult: (T, Element) throws -> T) rethrows -> T
-
Return (the first instance of) the smallest element in the bag, or
nilif the bag is empty.Complexity
O(log(count))Declaration
Swift
public var first: Element? -
Return (the last instance of) the largest element in the bag, or
nilif the bag is empty.Complexity
O(log(count))Declaration
Swift
public var last: Element? -
If this bag is empty, the result is an empty bag.
Complexity
O(log(count))Declaration
Swift
public func dropFirst() -> SortedBag -
Return a copy of this bag with the
nsmallest elements removed. Ifnexceeds the number of elements in the bag, the result is an empty bag.Complexity
O(log(count))Declaration
Swift
public func dropFirst(_ n: Int) -> SortedBag -
Return a copy of this bag with the largest element removed. If this bag is empty, the result is an empty bag.
Complexity
O(log(count))Declaration
Swift
public func dropLast() -> SortedBag -
Return a copy of this bag with the
nlargest elements removed. Ifnexceeds the number of elements in the bag, the result is an empty bag.Complexity
O(log(count))Declaration
Swift
public func dropLast(_ n: Int) -> SortedBag -
Returns a subbag, up to
maxLengthin size, containing the smallest elements in this bag.If
maxLengthexceeds the number of elements, the result contains all the elements ofself.Complexity
O(log(count))Declaration
Swift
public func prefix(_ maxLength: Int) -> SortedBag -
Returns a subbag containing all members of this bag at or before the specified index.
Complexity
O(log(count))Declaration
Swift
public func prefix(through index: Index) -> SortedBag -
Returns a subset containing all members of this bag less than or equal to the specified element (which may or may not be a member of this bag).
Complexity
O(log(count))Declaration
Swift
public func prefix(through element: Element) -> SortedBag -
Returns a subbag containing all members of this bag before the specified index.
Complexity
O(log(count))Declaration
Swift
public func prefix(upTo end: Index) -> SortedBag -
Returns a subbag containing all members of this bag less than the specified element (which may or may not be a member of this bag).
Complexity
O(log(count))Declaration
Swift
public func prefix(upTo end: Element) -> SortedBag -
Returns a subbag, up to
maxLengthin size, containing the largest elements in this bag.If
maxLengthexceeds the number of members, the result contains all the elements ofself.Complexity
O(log(count))Declaration
Swift
public func suffix(_ maxLength: Int) -> SortedBag -
Returns a subbag containing all members of this bag at or after the specified index.
Complexity
O(log(count))Declaration
Swift
public func suffix(from index: Index) -> SortedBag -
Returns a subset containing all members of this bag greater than or equal to the specified element (which may or may not be a member of this bag).
Complexity
O(log(count))Declaration
Swift
public func suffix(from element: Element) -> SortedBag
-
A textual representation of this bag.
Declaration
Swift
public var description: String -
A textual representation of this bag, suitable for debugging.
Declaration
Swift
public var debugDescription: String
-
Return true if the bag contains
element.Complexity
O(log(count))Declaration
Swift
public func contains(_ element: Element) -> Bool -
Returns the multiplicity of
memberin this bag, i.e. the number of instances ofmembercontained in the bag. Returns 0 ifmemberis not an element.Complexity
O(log(count))Declaration
Swift
public func count(of member: Element) -> Int -
Returns the index of the first instance of a given member, or
nilif the member is not present in the bag.Complexity
O(log(count))Declaration
Swift
public func index(of member: Element) -> BTreeIndex<Element, Void>? -
Returns the index of the lowest member of this bag that is strictly greater than
element, ornilif there is no such element.This function never returns
endIndex. (If it returns non-nil, the returned index can be used to subscript the bag.)Complexity
O(log(count))Declaration
Swift
public func indexOfFirstElement(after element: Element) -> BTreeIndex<Element, Void>? -
Returns the index of the lowest member of this bag that is greater than or equal to
element, ornilif there is no such element.This function never returns
endIndex. (If it returns non-nil, the returned index can be used to subscript the bag.)Complexity
O(log(count))Declaration
Swift
public func indexOfFirstElement(notBefore element: Element) -> BTreeIndex<Element, Void>? -
Returns the index of the highest member of this bag that is strictly less than
element, ornilif there is no such element.This function never returns
endIndex. (If it returns non-nil, the returned index can be used to subscript the bag.)Complexity
O(log(count))Declaration
Swift
public func indexOfLastElement(before element: Element) -> BTreeIndex<Element, Void>? -
Returns the index of the highest member of this bag that is less than or equal to
element, ornilif there is no such element.This function never returns
endIndex. (If it returns non-nil, the returned index can be used to subscript the bag.)Complexity
O(log(count))Declaration
Swift
public func indexOfLastElement(notAfter element: Element) -> BTreeIndex<Element, Void>?
-
Return
trueiffselfandothercontain the same number of instances of all the same elements.This method skips over shared subtrees when possible; this can drastically improve performance when the two bags are divergent mutations originating from the same value.
Complexity
O(count)Declaration
Swift
public func elementsEqual(_ other: SortedBag<Element>) -> Bool -
Returns
trueiffacontains the exact same elements asb, including multiplicities.This function skips over shared subtrees when possible; this can drastically improve performance when the two bags are divergent mutations originating from the same value.
Complexity
O(count)Declaration
Swift
public static func ==(a: SortedBag<Element>, b: SortedBag<Element>) -> Bool -
Returns
trueiff no members in this bag are also included inother.The elements of the two input bags may be freely interleaved. However, if there are long runs of non-interleaved elements, parts of the input bags may be skipped instead of elementwise processing, which can drastically improve performance.
Complexity
- O(min(
self.count,other.count)) in general. - O(log(
self.count+other.count)) if there are only a constant amount of interleaving element runs.
Declaration
Swift
public func isDisjoint(with other: SortedBag<Element>) -> Bool - O(min(
-
Returns
trueiff all members in this bag are also included inother.The elements of the two input bags may be freely interleaved. However, if there are long runs of non-interleaved elements, parts of the input bags may be skipped instead of elementwise processing, which can drastically improve performance.
Complexity
- O(min(
self.count,other.count)) in general. - O(log(
self.count+other.count)) if there are only a constant amount of interleaving element runs.
Declaration
Swift
public func isSubset(of other: SortedBag<Element>) -> Bool - O(min(
-
Returns
trueiff all members in this bag are also included inother, but the two bags aren’t equal.The elements of the two input bags may be freely interleaved. However, if there are long runs of non-interleaved elements, parts of the input bags may be skipped instead of elementwise processing, which can drastically improve performance.
Complexity
- O(min(
self.count,other.count)) in general. - O(log(
self.count+other.count)) if there are only a constant amount of interleaving element runs.
Declaration
Swift
public func isStrictSubset(of other: SortedBag<Element>) -> Bool - O(min(
-
Returns
trueiff all members inotherare also included in this bag.The elements of the two input bags may be freely interleaved. However, if there are long runs of non-interleaved elements, parts of the input bags may be skipped instead of elementwise processing, which can drastically improve performance.
Complexity
- O(min(
self.count,other.count)) in general. - O(log(
self.count+other.count)) if there are only a constant amount of interleaving element runs.
Declaration
Swift
public func isSuperset(of other: SortedBag<Element>) -> Bool - O(min(
-
Returns
trueiff all members inotherare also included in this bag, but the two bags aren’t equal.The elements of the two input bags may be freely interleaved. However, if there are long runs of non-interleaved elements, parts of the input bags may be skipped instead of elementwise processing, which can drastically improve performance.
Complexity
- O(min(
self.count,other.count)) in general. - O(log(
self.count+other.count)) if there are only a constant amount of interleaving element runs.
Declaration
Swift
public func isStrictSuperset(of other: SortedBag<Element>) -> Bool - O(min(
-
Unconditionally insert a new member into the bag, adding another instance if the member was already present.
The new member is inserted after its existing instances, if any. (This is important when equal members can be distinguished by identity comparison or some other means.)
Note
SetAlgebrarequiresinsertto do nothing and return(false, member)if the set already contains a matching element.SortedBagignores this requirement and always inserts a new copy of the specified element.Parameter
Parameter newMember: An element to insert into the set.
Returns
(true, newMember)to satisfy the syntactic requirements of theSetAlgebraprotocol.Complexity
O(log(
count))Declaration
Swift
public mutating func insert(_ newMember: Element) -> (inserted: Bool, memberAfterInsert: Element)Parameters
newMemberAn element to insert into the set.
Return Value
(true, newMember)to satisfy the syntactic requirements of theSetAlgebraprotocol. -
Unconditionally insert a new member into the bag, adding another instance if the member was already present.
The new member is inserted before its existing instances, if any. (This is important when equal members can be distinguished by identity comparison or some other means.)
Note
SetAlgebrarequiresupdateto replace and return an existing member if the set already contains a matching element.SortedBagignores this requirement and always inserts a new copy of the specified element.Parameter
Parameter newMember: An element to insert into the set.
Returns
Always returns
nil, to satisfy the syntactic requirements of theSetAlgebraprotocol.Declaration
Swift
public mutating func update(with newMember: Element) -> Element?Parameters
newMemberAn element to insert into the set.
Return Value
Always returns
nil, to satisfy the syntactic requirements of theSetAlgebraprotocol.
-
Remove and return the first instance of
memberfrom the bag, or returnnilif the bag contains no instances ofmember.Complexity
O(log(count))Declaration
Swift
public mutating func remove(_ member: Element) -> Element? -
Remove all instances of
memberfrom the bag.Complexity
O(log(count))Declaration
Swift
public mutating func removeAll(_ member: Element) -
Remove the member referenced by the given index.
Complexity
O(log(count))Declaration
Swift
public mutating func remove(at index: Index) -> Element -
Remove the member at the given offset.
Complexity
O(log(count))Declaration
Swift
public mutating func remove(atOffset offset: Int) -> Element -
Remove and return the smallest member in this bag, or return
nilif the bag is empty.Complexity
O(log(count))Declaration
Swift
public mutating func popFirst() -> Element? -
Remove and return the largest member in this bag, or return
nilif the bag is empty.Complexity
O(log(count))Declaration
Swift
public mutating func popLast() -> Element? -
Remove all members from this bag.
Declaration
Swift
public mutating func removeAll()
-
Return a bag containing all members from both this bag and
other. The result contains all elements of duplicate members from both bags.Elements from
otherfollow matching elements fromthisin the result.The elements of the two input bags may be freely interleaved. However, if there are long runs of non-interleaved elements, parts of the input bags will be simply linked into the result instead of copying, which can drastically improve performance.
Complexity
- O(
self.count+other.count) in general. - O(log(
self.count+other.count)) if there are only a constant amount of interleaving element runs.
Declaration
Swift
public func union(_ other: SortedBag<Element>) -> SortedBag<Element> - O(
-
Add all members in
otherto this bag, also keeping all existing instances already inself.The elements of the two input bags may be freely interleaved. However, if there are long runs of non-interleaved elements, parts of the input sets will be simply linked into the result instead of copying, which can drastically improve performance.
Complexity
- O(
self.count+other.count) in general. - O(log(
self.count+other.count)) if there are only a constant amount of interleaving element runs.
Declaration
Swift
public mutating func formUnion(_ other: SortedBag<Element>) - O(
-
Return a set consisting of all members in
otherthat are also in this bag. For duplicate members, only as many instances fromotherare kept in the result that appear inself.The elements of the two input sets may be freely interleaved. However, if there are long runs of non-interleaved elements, parts of the input sets will be simply linked into the result instead of copying, which can drastically improve performance.
Complexity
- O(min(
self.count,other.count)) in general. - O(log(
self.count+other.count)) if there are only a constant amount of interleaving element runs.
Declaration
Swift
public func intersection(_ other: SortedBag<Element>) -> SortedBag<Element> - O(min(
-
Remove all members from this bag that are not also included in
other. For duplicate members, only as many instances fromselfare kept that appear inother.The elements of the two input sets may be freely interleaved. However, if there are long runs of non-interleaved elements, parts of the input sets will be simply linked into the result instead of copying, which can drastically improve performance.
Complexity
- O(min(
self.count,other.count)) in general. - O(log(
self.count+other.count)) if there are only a constant amount of interleaving element runs.
Declaration
Swift
public mutating func formIntersection(_ other: SortedBag<Element>) - O(min(
-
Return a bag containing those members of this bag that aren’t also included in
other. For duplicate members whose multiplicity exceeds that of matching members inother, the extra members are kept in the result.The elements of the two input bags may be freely interleaved. However, if there are long runs of non-interleaved elements, parts of the input bags will be simply linked into the result instead of copying, which can drastically improve performance.
Complexity
- O(min(
self.count,other.count)) in general. - O(log(
self.count+other.count)) if there are only a constant amount of interleaving element runs.
Declaration
Swift
public func subtracting(_ other: SortedBag) -> SortedBag - O(min(
-
Remove all members from this bag that are also included in
other. For duplicate members whose multiplicity exceeds that of matching members inother, the extra members aren’t removed.The elements of the two input bags may be freely interleaved. However, if there are long runs of non-interleaved elements, parts of the input bags will be simply linked into the result instead of copying, which can drastically improve performance.
Complexity
- O(min(
self.count,other.count)) in general. - O(log(
self.count+other.count)) if there are only a constant amount of interleaving element runs.
Declaration
Swift
public mutating func subtract(_ other: SortedBag) - O(min(
-
Return a bag consisting of members from
selfandotherthat aren’t in both bags at once. For members whose multiplicity is different in the two bags, the last d members from the bag with the greater multiplicity is kept in the result (where d is the absolute difference of multiplicities).The elements of the two input bags may be freely interleaved. However, if there are long runs of non-interleaved elements, parts of the input bags will be simply linked into the result instead of copying, which can drastically improve performance.
Complexity
- O(min(
self.count,other.count)) in general. - O(log(
self.count+other.count)) if there are only a constant amount of interleaving element runs.
Declaration
Swift
public func symmetricDifference(_ other: SortedBag<Element>) -> SortedBag<Element> - O(min(
-
Replace
selfwith a set consisting of members fromselfandotherthat aren’t in both sets at once.The elements of the two input sets may be freely interleaved. However, if there are long runs of non-interleaved elements, parts of the input sets will be simply linked into the result instead of copying, which can drastically improve performance.
Complexity
- O(min(
self.count,other.count)) in general. - O(log(
self.count+other.count)) if there are only a constant amount of interleaving element runs.
Declaration
Swift
public mutating func formSymmetricDifference(_ other: SortedBag<Element>) - O(min(
-
Return the count of elements in this bag that are in
range.Complexity
O(log(self.count))Declaration
Swift
public func count(elementsIn range: Range<Element>) -> Int -
Return the count of elements in this bag that are in
range.Complexity
O(log(self.count))Declaration
Swift
public func count(elementsIn range: ClosedRange<Element>) -> Int -
Return a bag consisting of all members in
selfthat are also inrange.Complexity
O(log(self.count))Declaration
Swift
public func intersection(elementsIn range: Range<Element>) -> SortedBag<Element> -
Return a bag consisting of all members in
selfthat are also inrange.Complexity
O(log(self.count))Declaration
Swift
public func intersection(elementsIn range: ClosedRange<Element>) -> SortedBag<Element> -
Remove all members from this bag that are not included in
range.Complexity
O(log(self.count))Declaration
Swift
public mutating func formIntersection(elementsIn range: Range<Element>) -
Remove all members from this bag that are not included in
range.Complexity
O(log(self.count))Declaration
Swift
public mutating func formIntersection(elementsIn range: ClosedRange<Element>) -
Remove all elements in
rangefrom this bag.Complexity
O(log(self.count))Declaration
Swift
public mutating func subtract(elementsIn range: Range<Element>) -
Remove all elements in
rangefrom this bag.Complexity
O(log(self.count))Declaration
Swift
public mutating func subtract(elementsIn range: ClosedRange<Element>) -
Return a bag containing those members of this bag that aren’t also included in
range.Complexity
O(log(self.count))Declaration
Swift
public mutating func subtracting(elementsIn range: Range<Element>) -> SortedBag<Element> -
Return a bag containing those members of this bag that aren’t also included in
range.Complexity
O(log(self.count))Declaration
Swift
public mutating func subtracting(elementsIn range: ClosedRange<Element>) -> SortedBag<Element>
-
Shift the value of all elements starting at
startbydelta. For a positivedelta, this shifts elements to the right, creating an empty gap instart ..< start + delta. For a negativedelta, this shifts elements to the left, removing any elements in the rangestart + delta ..< startthat were previously in the bag.Complexity
O(self.count). The elements are modified in place.Declaration
Swift
public mutating func shift(startingAt start: Element, by delta: Element.Stride) -
Shift the value of all elements starting at index
startbydelta.This variant does not ever remove elements from the bag; if
deltais negative, its absolute value must not be greater than the difference between the element atstartand the element previous to it (if any).Requires
`start == self.startIndex || self[self.index(before: startIndex)] <= self[index] + deltaComplexity
O(self.count). The elements are modified in place.Declaration
Swift
public mutating func shift(startingAt start: Index, by delta: Element.Stride)
View on GitHub
Install in Dash
SortedBag Struct Reference