diff --git a/lib/typescript-stl.d.ts b/lib/typescript-stl.d.ts index 06edc79b..35bd3974 100644 --- a/lib/typescript-stl.d.ts +++ b/lib/typescript-stl.d.ts @@ -2751,46 +2751,6 @@ declare namespace std { */ function minmax_element>(first: ForwardIterator, last: ForwardIterator, compare: (x: T, y: T) => boolean): Pair; } -declare namespace std.base { - /** - *

Static class holding enumeration codes of color of Red-black tree.

- * - *

Color codes imposed to nodes of RB-Tree are following those rules:

- * - *
    - *
  1. A node is either red or black.
  2. - *
  3. The root is black. This rule is sometimes omitted. Since the root can - * always be changed from red to black, but not - * necessarily vice versa, this rule has little effect on analysis.
  4. - *
  5. All leaves (NIL; null) are black.
  6. - *
  7. If a node is red, then both its children are - * black.
  8. - *
  9. Every path from a given node to any of its descendant NIL nodes contains the same number of - * black nodes. Some definitions: the number of - * black nodes from the root to a node is the node's - * black depth; the uniform number of black - * nodes in all paths from root to the leaves is called the black-height of - * the red-black tree.
  10. - *
- * - * @author Migrated by Jeongho Nam - */ - enum Color { - /** - *

Code of color black.

- * - *
    - *
  • Those are clearly black: root, leaf nodes or children nodes of red.
  • - *
  • Every path from a given nodes containes the same number of black nodes exclude NIL(s).
  • - *
- */ - BLACK = 0, - /** - *

Code of color red.

- */ - RED = 1, - } -} declare namespace std.base { /** *

An abstract container.

@@ -2903,1094 +2863,608 @@ declare namespace std.base { swap(obj: IContainer): void; } } -declare namespace std.base { +declare namespace std { /** - *

An abstract error instance.

+ *

Bi-directional iterator.

* - *

{@link ErrorInstance} is an abstract class of {@link ErrorCode} and {@link ErrorCondition} - * holding an error instance's identifier {@link value}, associated with a {@link category}.

+ *

{@link Iterator Bidirectional iterators} are iterators that can be used to access the sequence of elements + * in a range in both directions (towards the end and towards the beginning).

* - *

The operating system and other low-level applications and libraries generate numerical error codes to - * represent possible results. These numerical values may carry essential information for a specific platform, - * but be non-portable from one platform to another.

+ *

All {@link IArrayIterator random-access iterators} are also valid {@link Iterrator bidirectional iterators}. + *

* - *

Objects of this class associate such numerical codes to {@link ErrorCategory error categories}, - * so that they can be interpreted when needed as more abstract (and portable) - * {@link ErrorCondition error conditions}.

+ *

There is not a single type of {@link Iterator bidirectional iterator}: {@link IContainer Each container} + * may define its own specific iterator type able to iterate through it and access its elements.

* - *

- *

+ *

+ * + *

* + * @reference http://www.cplusplus.com/reference/iterator/BidirectionalIterator * @author Jeongho Nam */ - abstract class ErrorInstance { - /** - * @hidden - */ - protected category_: ErrorCategory; - /** - * @hidden - */ - protected value_: number; - /** - * Default Constructor. - */ - constructor(); + abstract class Iterator { /** - * Construct from a numeric value and error category. - * - * @param val A numerical value identifying an error instance. - * @param category A reference to an {@link ErrorCategory} object. + * Source container of the iterator is directing for. */ - constructor(val: number, category: ErrorCategory); + protected source_: base.IContainer; /** - *

Assign error instance.

- * - *

Assigns the {@link ErrorCode} object a value of val associated with the {@link ErrorCategory}.

+ * Construct from the source {@link IContainer container}. * - * @param val A numerical value identifying an error instance. - * @param category A reference to an {@link ErrorCategory} object. + * @param source The source */ - assign(val: number, category: ErrorCategory): void; + constructor(source: base.IContainer); /** - *

Clear error instance.

+ *

Get iterator to previous element.

+ *

If current iterator is the first item(equal with {@link IContainer.begin IContainer.begin()}), + * returns {@link IContainer.end IContainer.end()}.

* - *

Clears the value in the {@link ErrorCode} object so that it is set to a value of 0 of the - * {@link ErrorCategory.systemCategory ErrorCategory.systemCategory()} (indicating no error).

+ * @return An iterator of the previous item. */ - clear(): void; + abstract prev(): Iterator; /** - *

Get category.

- * - *

Returns a reference to the {@link ErrorCategory} associated with the {@link ErrorCode} object.

+ *

Get iterator to next element.

+ *

If current iterator is the last item, returns {@link IContainer.end IContainer.end()}.

* - * @return A reference to a non-copyable object of a type derived from {@link ErrorCategory}. + * @return An iterator of the next item. */ - category(): ErrorCategory; + abstract next(): Iterator; /** - *

Error value.

- * - *

Returns the error value associated with the {@link ErrorCode} object.

+ * Advances the {@link Iterator} by n element positions. * - * @return The error value. + * @param n Number of element positions to advance. + * @return An advanced iterator. */ - value(): number; + advance(n: number): Iterator; /** - *

Get message.

- * - *

Returns the message associated with the error instance.

- * - *

Error messages are defined by the {@link category} the error instance belongs to.

- * - *

This function returns the same as if the following member was called:

- * - *

category().message(value())

- * - * @return A string object with the message associated with the {@link ErrorCode}. + * Get source */ - message(): string; + get_source(): base.IContainer; /** - *

Default error condition.

- * - *

Returns the default {@link ErrorCondition}object associated with the {@link ErrorCode} object.

+ *

Whether an iterator is equal with the iterator.

* - *

This function returns the same as if the following member was called:

+ *

Compare two iterators and returns whether they are equal or not.

* - *

category().default_error_condition(value())

+ *

Note

+ *

Iterator's equal_to() only compare souce container and index number.

* - *

{@link ErrorCategory.default_error_condition ErrorCategory.default_error_condition()} - * is a virtual member function, that can operate differently for each category.

+ *

Although elements in a pair, key and value are equal_to, if the source map or + * index number is different, then the {@link equal_to equal_to()} will return false. If you want to + * compare the elements of a pair, compare them directly by yourself.

* - * @return An {@link ErrorCondition}object that corresponds to the {@link ErrorCode} object. + * @param obj An iterator to compare + * @return Indicates whether equal or not. */ - default_error_condition(): ErrorCondition; + equal_to(obj: Iterator): boolean; /** - *

Convert to bool.

- * - *

Returns whether the error instance has a numerical {@link value} other than 0.

- * - *

If it is zero (which is generally used to represent no error), the function returns false, otherwise it returns true.

+ *

Get value of the iterator is pointing.

* - * @return true if the error's numerical value is not zero. - * false otherwise. + * @return A value of the iterator. */ - to_bool(): boolean; + value: T; + abstract swap(obj: Iterator): void; } } -declare namespace std.base { - enum Hash { - MIN_SIZE = 10, - RATIO = 1, - MAX_RATIO = 2, - } +declare namespace std { /** - *

Hask buckets.

+ *

This class reverses the direction in which a bidirectional or random-access iterator iterates through a range. + *

+ * + *

A copy of the original iterator (the {@link Iterator base iterator}) is kept internally and used to reflect + * the operations performed on the {@link ReverseIterator}: whenever the {@link ReverseIterator} is incremented, its + * {@link Iterator base iterator} is decreased, and vice versa. A copy of the {@link Iterator base iterator} with the + * current state can be obtained at any time by calling member {@link base}.

+ * + *

Notice however that when an iterator is reversed, the reversed version does not point to the same element in + * the range, but to the one preceding it. This is so, in order to arrange for the past-the-end element of a + * range: An iterator pointing to a past-the-end element in a range, when reversed, is pointing to the last element + * (not past it) of the range (this would be the first element of the reversed range). And if an iterator to the + * first element in a range is reversed, the reversed iterator points to the element before the first element (this + * would be the past-the-end element of the reversed range).

+ * + *

+ * + *

* + * @reference http://www.cplusplus.com/reference/iterator/reverse_iterator * @author Jeongho Nam */ - class HashBuckets { - /** - * @hidden - */ - private buckets_; + abstract class ReverseIterator, This extends ReverseIterator> extends Iterator { /** * @hidden */ - private item_size_; + protected base_: Base; /** - * Default Constructor. + * Construct from base iterator. + * + * @param base A reference of the base iterator, which iterates in the opposite direction. */ - constructor(); + constructor(base: Base); /** - *

Reconstruction of hash table.

+ *

Return base iterator.

* - *

All the elements in the hash buckets are rearranged according to their hash value into the new set of - * buckets. This may alter the order of iteration of elements within the container.

+ *

Return a reference of the base iteraotr.

* - *

Notice that {@link rehash rehashes} are automatically performed whenever its number of elements is going - * to greater than its own {@link capacity}.

+ *

The base iterator is an iterator of the same type as the one used to construct the {@link ReverseIterator}, + * but pointing to the element next to the one the {@link ReverseIterator} is currently pointing to + * (a {@link ReverseIterator} has always an offset of -1 with respect to its base iterator). * - * @param size Number of bucket size to rehash. + * @return A reference of the base iterator, which iterates in the opposite direction. */ - rehash(size: number): void; - clear(): void; - size(): number; - item_size(): number; - capacity(): number; - at(index: number): Vector; - hash_index(val: T): number; - insert(val: T): void; - erase(val: T): void; - } -} -declare namespace std.base { - /** - *

Common interface for hash map.

- * - *

{@link IHashMap}s are associative containers that store elements formed by the combination of - * a key value and a mapped value.

- * - *

In an {@link IHashMap}, the key value is generally used to uniquely identify the - * element, while the mapped value is an object with the content associated to this key. - * Types of key and mapped value may differ.

- * - *

Internally, the elements in the {@link IHashMap} are not sorted in any particular order with - * respect to either their key or mapped values, but organized into buckets depending on - * their hash values to allow for fast access to individual elements directly by their key values - * (with a constant average time complexity on average).

- * - *

Elements with equivalent keys are grouped together in the same bucket and in such a way that - * an iterator can iterate through all of them. Iterators in the container are doubly linked iterators.

- * - *

- * - *

- * - *

Container properties

- *
- *
Associative
- *
Elements in associative containers are referenced by their key and not by their absolute - * position in the container.
- * - *
Hashed
- *
Hashed containers organize their elements using hash tables that allow for fast access to elements - * by their key.
- * - *
Map
- *
Each element associates a key to a mapped value: - * Keys are meant to identify the elements whose main content is the mapped value.
- *
- * - * @param Type of the key values. - * Each element in an {@link IHashMap} is identified by a key value. - * @param Type of the mapped value. - * Each element in an {@link IHashMap} is used to store some data as its mapped value. - * - * @reference http://www.cplusplus.com/reference/unordered_map - * @author Jeongho Nam - */ - interface IHashMap { - /** - *

Return iterator to beginning.

- * - *

Returns an iterator pointing to the first element in the {@link IHashMap}.

- * - *

Notice that an {@link IHashMap} object makes no guarantees on which specific element is considered its - * first element. But, in any case, the range that goes from its begin to its end covers all the elements in the - * container, until invalidated.

- * - * @return An iterator to the first element in the container. - */ - begin(): MapIterator; - /** - *

Return iterator to beginning.

- * - *

Returns an iterator pointing to the first element in one of buckets in the {@link IHashMap}.

- * - *

Notice that an {@link IHashMap} object makes no guarantees on which specific element is considered its - * first element. But, in any case, the range that goes from its begin to its end covers all the elements in the - * bucket, until invalidated.

- * - * @param index Bucket number. This shall be lower than {@link bucket_count}. - * - * @return An iterator to the first element in the bucket. - */ - begin(index: number): MapIterator; - /** - *

Return iterator to end.

- * - *

Returns an iterator pointing to the past-the-end element in the {@link HaspMap} container.

- * - *

The iterator returned by end does not point to any element, but to the position that follows the last - * element in the {@link HaspMap} container (its past-the-end position). Thus, the value returned shall - * not be dereferenced - it is generally used to describe the open-end of a range, such as - * [begin, end).

- * - *

Notice that an {@link IHashMap} object makes no guarantees on which order its elements follow. But, in any - * case, the range that goes from its begin to its end covers all the elements in the container (or the bucket), - * until invalidated.

- * - * @return An iterator to the element past the end of the container. - */ - end(): MapIterator; - /** - *

Return iterator to end.

- * - *

Returns an iterator pointing to the past-the-end element in the {@link HaspMap} container.

- * - *

The iterator returned by end does not point to any element, but to the position that follows the last - * element in the {@link HaspMap} container (its past-the-end position). Thus, the value returned shall - * not be dereferenced - it is generally used to describe the open-end of a range, such as - * [begin, end).

- * - *

Notice that an {@link IHashMap} object makes no guarantees on which order its elements follow. But, in any - * case, the range that goes from its begin to its end covers all the elements in the container (or the bucket), - * until invalidated.

- * - * @param index Bucket number. This shall be lower than {@link bucket_count}. - * - * @return An iterator to the element past the end of the bucket. - */ - end(index: number): MapIterator; - /** - *

Return {@link MapReverseIterator reverse iterator} to reverse beginning.

- * - *

Returns a {@link MapReverseIterator reverse iterator} pointing to the last element in the {@link IHashMap} - * (i.e., its reverse beginning).

- * - * {@link MapReverseIterator Reverse iterators} iterate backwards: increasing them moves them towards the - * beginning of the container.

- * - *

{@link rbegin} points to the element preceding the one that would be pointed to by member {@link end}.

- * - *

Notice that an {@link IHashMap} object makes no guarantees on which specific element is considered its - * first element. But, in any case, the range that goes from its begin to its end covers all the elements in the - * bucket, until invalidated.

- * - * @return A {@link MapReverseIterator reverse iterator} to the reverse beginning of the sequence - */ - rbegin(): MapReverseIterator; - /** - *

Return {@link MapReverseIterator reverse iterator} to reverse beginning.

- * - *

Returns a {@link MapReverseIterator reverse iterator} pointing to the last element in one of buckets in the - * {@link IHashMap} (i.e., its reverse beginning).

- * - * {@link MapReverseIterator Reverse iterators} iterate backwards: increasing them moves them towards the - * beginning of the container.

- * - *

{@link rbegin} points to the element preceding the one that would be pointed to by member {@link end}.

- * - *

Notice that an {@link IHashMap} object makes no guarantees on which specific element is considered its - * first element. But, in any case, the range that goes from its begin to its end covers all the elements in the - * bucket, until invalidated.

- * - * @param index Bucket number. This shall be lower than {@link bucket_count}. - * - * @return A {@link MapReverseIterator reverse iterator} to the reverse beginning of the sequence - */ - rbegin(index: number): MapReverseIterator; - /** - *

Return {@link MapReverseIterator reverse iterator} to reverse end.

- * - *

Returns a {@link MapReverseIterator reverse iterator} pointing to the theoretical element right before - * the first element in the {@link IHashMap hash map container} (which is considered its reverse end).

- * - *

The range between {@link IHashMap}.{@link rbegin} and {@link IHashMap}.{@link rend} contains all the - * elements of the container (in reverse order).

- * - *

Notice that an {@link IHashMap} object makes no guarantees on which order its elements follow. But, in any - * case, the range that goes from its begin to its end covers all the elements in the container (or the bucket), - * until invalidated.

- * - * @return A {@link MapReverseIterator reverse iterator} to the reverse end of the sequence. - */ - rend(): MapReverseIterator; + base(): Base; /** - *

Return {@link MapReverseIterator reverse iterator} to reverse end.

- * - *

Returns a {@link MapReverseIterator reverse iterator} pointing to the theoretical element right before - * the first element in one of buckets in the {@link IHashMap hash map container} (which is considered its - * reverse end).

- * - *

The range between {@link IHashMap}.{@link rbegin} and {@link IHashMap}.{@link rend} contains all the - * elements of the container (in reverse order).

- * - *

Notice that an {@link IHashMap} object makes no guarantees on which order its elements follow. But, in any - * case, the range that goes from its begin to its end covers all the elements in the container (or the bucket), - * until invalidated.

- * - * @param index Bucket number. This shall be lower than {@link bucket_count}. - * - * @return A {@link MapReverseIterator reverse iterator} to the reverse end of the sequence. + * @hidden */ - rend(index: number): MapReverseIterator; + protected abstract create_neighbor(base: Base): This; /** - *

Return number of buckets.

- * - *

Returns the number of buckets in the {@link IHashMap} container.

- * - *

A bucket is a slot in the container's internal hash table to which elements are assigned based on the - * hash value of their key.

- * - *

The number of buckets influences directly the {@link load_factor load factor} of the container's hash - * table (and thus the probability of collision). The container automatically increases the number of buckets to - * keep the load factor below a specific threshold (its {@link max_load_factor}), causing a {@link rehash} each - * time the number of buckets needs to be increased.

+ *

Get value of the iterator is pointing.

* - * @return The current amount of buckets. + * @return A value of the reverse iterator. */ - bucket_count(): number; + value: T; /** - *

Return bucket size.

- * - *

Returns the number of elements in bucket n.

- * - *

A bucket is a slot in the container's internal hash table to which elements are assigned based on the hash - * value of their key.

- * - *

The number of elements in a bucket influences the time it takes to access a particular element in the - * bucket. The container automatically increases the number of buckets to keep the {@link load_cator load factor} - * (which is the average bucket size) below its {@link max_load_factor}.

- * - * @param n Bucket number. This shall be lower than {@link bucket_count}. - * - * @return The number of elements in bucket n. + * @inheritdoc */ - bucket_size(n: number): number; + prev(): This; /** - *

Get maximum load factor.

- * - *

Returns the current maximum load factor for the {@link HashMultiMap} container.

- * - *

The load factor is the ratio between the number of elements in the container (its {@link size}) and the - * number of buckets ({@link bucket_count}).

- * - *

By default, {@link HashMultiMap} containers have a {@link max_load_factor} of 1.0.

- * - *

The load factor influences the probability of collision in the hash table (i.e., the probability of two - * elements being located in the same bucket). The container uses the value of max_load_factor as the threshold - * that forces an increase in the number of buckets (and thus causing a {@link rehash}).

- * - *

Note though, that implementations may impose an upper limit on the number of buckets (see - * {@link max_bucket_count}), which may force the container to ignore the {@link max_load_factor}.

- * - * @return The current load factor. + * @inheritdoc */ - max_load_factor(): number; + next(): This; /** - *

Set maximum load factor.

- * - *

Sets z as the cnew maximum load factor for the {@link HashMultiMap} container.

- * - *

The load factor is the ratio between the number of elements in the container (its {@link size}) and the - * number of buckets ({@link bucket_count}).

- * - *

By default, {@link HashMultiMap} containers have a {@link max_load_factor} of 1.0.

- * - *

The load factor influences the probability of collision in the hash table (i.e., the probability of two - * elements being located in the same bucket). The container uses the value of max_load_factor as the threshold - * that forces an increase in the number of buckets (and thus causing a {@link rehash}).

- * - *

Note though, that implementations may impose an upper limit on the number of buckets (see - * {@link max_bucket_count}), which may force the container to ignore the {@link max_load_factor}.

- * - * @param z The new maximum load factor. + * @inheritdoc */ - max_load_factor(z: number): void; + advance(n: number): This; /** - *

Locate element's bucket.

- * - *

Returns the bucket number where the element with key is located.

- * - *

A bucket is a slot in the container's internal hash table to which elements are assigned based on the - * hash value of their key. Buckets are numbered from 0 to ({@link bucket_count} - 1).

- * - *

Individual elements in a bucket can be accessed by means of the range iterators returned by - * {@link begin} and {@link end}.

- * - * @param key Key whose bucket is to be located. + * @inheritdoc */ - bucket(key: Key): number; + equal_to(obj: This): boolean; /** - *

Request a capacity change.

- * - *

Sets the number of buckets in the container ({@link bucket_count}) to the most appropriate to contain at - * least n elements.

- * - *

If n is greater than the current {@link bucket_count} multiplied by the {@link max_load_factor}, - * the container's {@link bucket_count} is increased and a {@link rehash} is forced.

- * - *

If n is lower than that, the function may have no effect.

- * - * @param n The number of elements requested as minimum capacity. + * @inheritdoc */ - reserve(n: number): void; - /** - *

Set number of buckets.

- * - *

Sets the number of buckets in the container to n or more.

- * - *

If n is greater than the current number of buckets in the container ({@link bucket_count}), a - * {@link HashBuckets.rehash rehash} is forced. The new {@link bucket_count bucket count} can either be equal or - * greater than n.

- * - *

If n is lower than the current number of buckets in the container ({@link bucket_count}), the - * function may have no effect on the {@link bucket_count bucket count} and may not force a - * {@link HashBuckets.rehash rehash}.

- * - *

A {@link HashBuckets.rehash rehash} is the reconstruction of the hash table: All the elements in the - * container are rearranged according to their hash value into the new set of buckets. This may alter the order - * of iteration of elements within the container.

- * - *

{@link HashBuckets.rehash Rehashes} are automatically performed by the container whenever its - * {@link load_factor load factor} is going to surpass its {@link max_load_factor} in an operation.

- * - *

Notice that this function expects the number of buckets as argument. A similar function exists, - * {@link reserve}, that expects the number of elements in the container as argument.

- * - * @param n The minimum number of buckets for the container hash table. - */ - rehash(n: number): void; + swap(obj: This): void; } -} -declare namespace std.base { /** - *

Hash buckets storing {@link MapIterator MapIterators}.

+ *

Return distance between {@link Iterator iterators}.

* - *

- * - *

+ *

Calculates the number of elements between first and last.

* - * @author Jeongho Nam + *

If it is a {@link IArrayIterator random-access iterator}, the function uses operator- to calculate this. + * Otherwise, the function uses the increase operator {@link Iterator.next next()} repeatedly.

+ * + * @param first Iterator pointing to the initial element. + * @param last Iterator pointing to the final element. This must be reachable from first. + * + * @return The number of elements between first and last. */ - class MapHashBuckets extends HashBuckets> { - private map; - constructor(map: MapContainer); - find(key: K): MapIterator; - } -} -declare namespace std.base { + function distance>(first: InputIterator, last: InputIterator): number; /** - *

A common interface for hash set.

+ *

Advance iterator.

* - *

{@link IHashSet}s are containers that store unique elements in no particular order, and which - * allow for fast retrieval of individual elements based on their value.

+ *

Advances the iterator it by n elements positions.

* - *

In an {@link IHashSet}, the value of an element is at the same time its key, that - * identifies it uniquely. Keys are immutable, therefore, the elements in an {@link IHashSet} cannot be - * modified once in the container - they can be inserted and removed, though.

+ * @param it Iterator to be advanced. + * @param n Number of element positions to advance. * - *

Internally, the elements in the {@link IHashSet} are not sorted in any particular order, but - * organized into buckets depending on their hash values to allow for fast access to individual elements - * directly by their values (with a constant average time complexity on average).

+ * @return An iterator to the element n positions before it. + */ + function advance>(it: InputIterator, n: number): InputIterator; + /** + *

Get iterator to previous element.

* - *

{@link IHashSet} containers are faster than {@link TreeSet} containers to access individual - * elements by their key, although they are generally less efficient for range iteration through a - * subset of their elements.

+ *

Returns an iterator pointing to the element that it would be pointing to if advanced -n positions.

* - *

- * - *

+ * @param it Iterator to base position. + * @param n Number of element positions offset (1 by default). * - *

Container properties

- *
- *
Associative
- *
Elements in associative containers are referenced by their key and not by their absolute - * position in the container.
+ * @return An iterator to the element n positions before it. + */ + function prev>(it: BidirectionalIterator, n?: number): BidirectionalIterator; + /** + *

Get iterator to next element.

* - *
Hashed
- *
Hashed containers organize their elements using hash tables that allow for fast access to elements - * by their key.
+ *

Returns an iterator pointing to the element that it would be pointing to if advanced n positions.

* - *
Set
- *
The value of an element is also the key used to identify it.
- *
+ * @param it Iterator to base position. + * @param n Number of element positions offset (1 by default). * - * @param Type of the elements. - * Each element in an {@link IHashSet} is also uniquely identified by this value. + * @return An iterator to the element n positions away from it. + */ + function next>(it: ForwardIterator, n?: number): ForwardIterator; + /** + *

Iterator to beginning.

* - * @reference http://www.cplusplus.com/reference/unordered_set/unordered_set - * @author Jeongho Nam + *

Returns an iterator pointing to the first element in the sequence.

+ * + *

If the sequence is empty, the returned value shall not be dereferenced.

+ * + * @param container A container object of a class type for which member {@link IContainer.begin begin} is defined. + * + * @return The same as returned by {@link IContainer.begin container.begin()}. */ - interface IHashSet { - /** - *

Return iterator to beginning.

- * - *

Returns an iterator pointing to the first element in the {@link IHashSet}.

- * - *

Notice that an {@link IHashSet} object makes no guarantees on which specific element is considered its - * first element. But, in any case, the range that goes from its begin to its end covers all the elements in the - * container, until invalidated.

- * - * @return An iterator to the first element in the container. - */ - begin(): SetIterator; - /** - *

Return iterator to beginning.

- * - *

Returns an iterator pointing to the first element in one of buckets in the {@link IHashSet}.

- * - *

Notice that an {@link IHashSet} object makes no guarantees on which specific element is considered its - * first element. But, in any case, the range that goes from its begin to its end covers all the elements in the - * bucket, until invalidated.

- * - * @param index Bucket number. This shall be lower than {@link bucket_count}. - * - * @return An iterator to the first element in the bucket. - */ - begin(index: number): SetIterator; - /** - *

Return iterator to end.

- * - *

Returns an iterator pointing to the past-the-end element in the {@link HaspMap} container.

- * - *

The iterator returned by end does not point to any element, but to the position that follows the last - * element in the {@link HaspMap} container (its past-the-end position). Thus, the value returned shall - * not be dereferenced - it is generally used to describe the open-end of a range, such as - * [begin, end).

- * - *

Notice that an {@link IHashSet} object makes no guarantees on which order its elements follow. But, in any - * case, the range that goes from its begin to its end covers all the elements in the container (or the bucket), - * until invalidated.

- * - * @return An iterator to the element past the end of the container. - */ - end(): SetIterator; - /** - *

Return iterator to end.

- * - *

Returns an iterator pointing to the past-the-end element in the {@link HaspMap} container.

- * - *

The iterator returned by end does not point to any element, but to the position that follows the last - * element in the {@link HaspMap} container (its past-the-end position). Thus, the value returned shall - * not be dereferenced - it is generally used to describe the open-end of a range, such as - * [begin, end).

- * - *

Notice that an {@link IHashSet} object makes no guarantees on which order its elements follow. But, in any - * case, the range that goes from its begin to its end covers all the elements in the container (or the bucket), - * until invalidated.

- * - * @param index Bucket number. This shall be lower than {@link bucket_count}. - * - * @return An iterator to the element past the end of the bucket. - */ - end(index: number): SetIterator; - rbegin(): SetReverseIterator; - rbegin(index: number): SetReverseIterator; - rend(): SetReverseIterator; - rend(index: number): SetReverseIterator; - /** - *

Return number of buckets.

- * - *

Returns the number of buckets in the {@link IHashSet} container.

- * - *

A bucket is a slot in the container's internal hash table to which elements are assigned based on the - * hash value of their key.

- * - *

The number of buckets influences directly the {@link load_factor load factor} of the container's hash - * table (and thus the probability of collision). The container automatically increases the number of buckets to - * keep the load factor below a specific threshold (its {@link max_load_factor}), causing a {@link rehash} each - * time the number of buckets needs to be increased.

- * - * @return The current amount of buckets. - */ - bucket_count(): number; - /** - *

Return bucket size.

- * - *

Returns the number of elements in bucket n.

- * - *

A bucket is a slot in the container's internal hash table to which elements are assigned based on the hash - * value of their key.

- * - *

The number of elements in a bucket influences the time it takes to access a particular element in the - * bucket. The container automatically increases the number of buckets to keep the {@link load_cator load factor} - * (which is the average bucket size) below its {@link max_load_factor}.

- * - * @param n Bucket number. This shall be lower than {@link bucket_count}. - * - * @return The number of elements in bucket n. - */ - bucket_size(n: number): number; - /** - *

Get maximum load factor.

- * - *

Returns the current maximum load factor for the {@link HashMultiMap} container.

- * - *

The load factor is the ratio between the number of elements in the container (its {@link size}) and the - * number of buckets ({@link bucket_count}).

- * - *

By default, {@link HashMultiMap} containers have a {@link max_load_factor} of 1.0.

- * - *

The load factor influences the probability of collision in the hash table (i.e., the probability of two - * elements being located in the same bucket). The container uses the value of max_load_factor as the threshold - * that forces an increase in the number of buckets (and thus causing a {@link rehash}).

- * - *

Note though, that implementations may impose an upper limit on the number of buckets (see - * {@link max_bucket_count}), which may force the container to ignore the {@link max_load_factor}.

- * - * @return The current load factor. - */ - max_load_factor(): number; - /** - *

Set maximum load factor.

- * - *

Sets z as the cnew maximum load factor for the {@link HashMultiMap} container.

- * - *

The load factor is the ratio between the number of elements in the container (its {@link size}) and the - * number of buckets ({@link bucket_count}).

- * - *

By default, {@link HashMultiMap} containers have a {@link max_load_factor} of 1.0.

- * - *

The load factor influences the probability of collision in the hash table (i.e., the probability of two - * elements being located in the same bucket). The container uses the value of max_load_factor as the threshold - * that forces an increase in the number of buckets (and thus causing a {@link rehash}).

- * - *

Note though, that implementations may impose an upper limit on the number of buckets (see - * {@link max_bucket_count}), which may force the container to ignore the {@link max_load_factor}.

- * - * @param z The new maximum load factor. - */ - max_load_factor(z: number): void; - /** - *

Locate element's bucket.

- * - *

Returns the bucket number where the element with key is located.

- * - *

A bucket is a slot in the container's internal hash table to which elements are assigned based on the - * hash value of their key. Buckets are numbered from 0 to ({@link bucket_count} - 1).

- * - *

Individual elements in a bucket can be accessed by means of the range iterators returned by - * {@link begin} and {@link end}.

- * - * @param key Key whose bucket is to be located. - */ - bucket(key: T): number; - /** - *

Request a capacity change.

- * - *

Sets the number of buckets in the container ({@link bucket_count}) to the most appropriate to contain at - * least n elements.

- * - *

If n is greater than the current {@link bucket_count} multiplied by the {@link max_load_factor}, - * the container's {@link bucket_count} is increased and a {@link rehash} is forced.

- * - *

If n is lower than that, the function may have no effect.

- * - * @param n The number of elements requested as minimum capacity. - */ - reserve(n: number): void; - /** - *

Set number of buckets.

- * - *

Sets the number of buckets in the container to n or more.

- * - *

If n is greater than the current number of buckets in the container ({@link bucket_count}), a - * {@link HashBuckets.rehash rehash} is forced. The new {@link bucket_count bucket count} can either be equal or - * greater than n.

- * - *

If n is lower than the current number of buckets in the container ({@link bucket_count}), the - * function may have no effect on the {@link bucket_count bucket count} and may not force a - * {@link HashBuckets.rehash rehash}.

- * - *

A {@link HashBuckets.rehash rehash} is the reconstruction of the hash table: All the elements in the - * container are rearranged according to their hash value into the new set of buckets. This may alter the order - * of iteration of elements within the container.

- * - *

{@link HashBuckets.rehash Rehashes} are automatically performed by the container whenever its - * {@link load_factor load factor} is going to surpass its {@link max_load_factor} in an operation.

- * - *

Notice that this function expects the number of buckets as argument. A similar function exists, - * {@link reserve}, that expects the number of elements in the container as argument.

- * - * @param n The minimum number of buckets for the container hash table. - */ - rehash(n: number): void; - } -} -declare namespace std.base { + function begin(container: Vector): VectorIterator; /** - *

Hash buckets storing {@link SetIterator SetIterators}.

+ *

Iterator to beginning.

* - *

- * - *

+ *

Returns an iterator pointing to the first element in the sequence.

* - * @author Jeongho Nam + *

If the sequence is empty, the returned value shall not be dereferenced.

+ * + * @param container A container object of a class type for which member {@link IContainer.begin begin} is defined. + * + * @return The same as returned by {@link IContainer.begin container.begin()}. */ - class SetHashBuckets extends HashBuckets> { - private set; - constructor(set: SetContainer); - find(val: T): SetIterator; - } + function begin(container: List): ListIterator; + /** + *

Iterator to beginning.

+ * + *

Returns an iterator pointing to the first element in the sequence.

+ * + *

If the sequence is empty, the returned value shall not be dereferenced.

+ * + * @param container A container object of a class type for which member {@link IContainer.begin begin} is defined. + * + * @return The same as returned by {@link IContainer.begin container.begin()}. + */ + function begin(container: Deque): DequeIterator; + /** + *

Iterator to beginning.

+ * + *

Returns an iterator pointing to the first element in the sequence.

+ * + *

If the sequence is empty, the returned value shall not be dereferenced.

+ * + * @param container A container object of a class type for which member {@link IContainer.begin begin} is defined. + * + * @return The same as returned by {@link IContainer.begin container.begin()}. + */ + function begin(container: base.SetContainer): SetIterator; + /** + *

Iterator to beginning.

+ * + *

Returns an iterator pointing to the first element in the sequence.

+ * + *

If the sequence is empty, the returned value shall not be dereferenced.

+ * + * @param container A container object of a class type for which member {@link IContainer.begin begin} is defined. + * + * @return The same as returned by {@link IContainer.begin container.begin()}. + */ + function begin(container: base.MapContainer): MapIterator; + /** + *

Iterator to end.

+ * + *

Returns an iterator pointing to the past-the-end element in the sequence.

+ * + *

If the sequence is {@link IContainer.empty empty}, the returned value compares equal to the one returned by {@link begin} with the same argument.

+ * + * @param container A container of a class type for which member {@link IContainer.end end} is defined. + * + * @return The same as returned by {@link IContainer.end container.end()}. + */ + function end(container: Vector): VectorIterator; + /** + *

Iterator to end.

+ * + *

Returns an iterator pointing to the past-the-end element in the sequence.

+ * + *

If the sequence is {@link IContainer.empty empty}, the returned value compares equal to the one returned by {@link begin} with the same argument.

+ * + * @param container A container of a class type for which member {@link IContainer.end end} is defined. + * + * @return The same as returned by {@link IContainer.end container.end()}. + */ + function end(container: List): ListIterator; + /** + *

Iterator to end.

+ * + *

Returns an iterator pointing to the past-the-end element in the sequence.

+ * + *

If the sequence is {@link IContainer.empty empty}, the returned value compares equal to the one returned by {@link begin} with the same argument.

+ * + * @param container A container of a class type for which member {@link IContainer.end end} is defined. + * + * @return The same as returned by {@link IContainer.end container.end()}. + */ + function end(container: Deque): DequeIterator; + /** + *

Iterator to end.

+ * + *

Returns an iterator pointing to the past-the-end element in the sequence.

+ * + *

If the sequence is {@link IContainer.empty empty}, the returned value compares equal to the one returned by {@link begin} with the same argument.

+ * + * @param container A container of a class type for which member {@link IContainer.end end} is defined. + * + * @return The same as returned by {@link IContainer.end container.end()}. + */ + function end(container: base.SetContainer): SetIterator; + /** + *

Iterator to end.

+ * + *

Returns an iterator pointing to the past-the-end element in the sequence.

+ * + *

If the sequence is {@link IContainer.empty empty}, the returned value compares equal to the one returned by {@link begin} with the same argument.

+ * + * @param container A container of a class type for which member {@link IContainer.end end} is defined. + * + * @return The same as returned by {@link IContainer.end container.end()}. + */ + function end(container: base.MapContainer): MapIterator; } -declare namespace std.base { +declare namespace std.Deque { + type iterator = std.DequeIterator; + type reverse_iterator = std.DequeReverseIterator; +} +declare namespace std { /** - *

Array

+ *

Double ended queue.

* - *

{@link IArray} is an interface for sequence containers representing arrays that can change in - * {@link size}. However, compared to arrays, {@link IArray} objectss consume more memory in exchange for - * the ability to manage storage and grow dynamically in an efficient way.

+ *

{@link Deque} (usually pronounced like "deck") is an irregular acronym of + * double-ended queue. Double-ended queues are sequence containers with dynamic sizes that can be + * expanded or contracted on both ends (either its front or its back).

* - *

Both {@link Vector Vectors} and {@link Deque Deques} who implemented {@link IArray} provide a very - * similar interface and can be used for similar purposes, but internally both work in quite different ways: - * While {@link Vector Vectors} use a single array that needs to be occasionally reallocated for growth, the - * elements of a {@link Deque} can be scattered in different chunks of storage, with the container keeping the - * necessary information internally to provide direct access to any of its elements in constant time and with a - * uniform sequential interface (through iterators). Therefore, {@link Deque Deques} are a little more complex - * internally than {@link Vector Vectors}, but this allows them to grow more efficiently under certain - * circumstances, especially with very long sequences, where reallocations become more expensive.

+ *

Specific libraries may implement deques in different ways, generally as some form of dynamic array. But in any + * case, they allow for the individual elements to be accessed directly through random access iterators, with storage + * handled automatically by expanding and contracting the container as needed.

* - *

Both {@link Vector Vectors} and {@link Deque Deques} provide a very similar interface and can be used for - * similar purposes, but internally both work in quite different ways: While {@link Vector Vectors} use a single - * array that needs to be occasionally reallocated for growth, the elements of a {@link Deque} can be scattered - * in different chunks of storage, with the container keeping the necessary information internally to provide - * direct access to any of its elements in constant time and with a uniform sequential interface (through - * iterators). Therefore, {@link Deque Deques} are a little more complex internally than {@link Vector Vectors}, - * but this allows them to grow more efficiently under certain circumstances, especially with very long - * sequences, where reallocations become more expensive.

+ *

Therefore, they provide a functionality similar to vectors, but with efficient insertion and deletion of + * elements also at the beginning of the sequence, and not only at its end. But, unlike {@link Vector Vectors}, + * {@link Deque Deques} are not guaranteed to store all its elements in contiguous storage locations: accessing + * elements in a deque by offsetting a pointer to another element causes undefined behavior.

* - *

For operations that involve frequent insertion or removals of elements at positions other than the - * beginning or the end, {@link IArray} objects perform worse and have less consistent iterators and references - * than {@link List Lists}

. + *

Both {@link Vector}s and {@link Deque}s provide a very similar interface and can be used for similar purposes, + * but internally both work in quite different ways: While {@link Vector}s use a single array that needs to be + * occasionally reallocated for growth, the elements of a {@link Deque} can be scattered in different chunks of + * storage, with the container keeping the necessary information internally to provide direct access to any of its + * elements in constant time and with a uniform sequential interface (through iterators). Therefore, + * {@link Deque Deques} are a little more complex internally than {@link Vector}s, but this allows them to grow more + * efficiently under certain circumstances, especially with very long sequences, where reallocations become more + * expensive.

+ * + *

For operations that involve frequent insertion or removals of elements at positions other than the beginning or + * the end, {@link Deque Deques} perform worse and have less consistent iterators and references than + * {@link List Lists}.

* *

- * - *

+ * + *

* *

Container properties

*
*
Sequence
- *
- * Elements in sequence containers are ordered in a strict linear sequence. Individual elements are - * accessed by their position in this sequence. - *
+ *
Elements in sequence containers are ordered in a strict linear sequence. Individual elements + * are accessed by their position in this sequence.
* *
Dynamic array
- *
- * Allows direct access to any element in the sequence, even through pointer arithmetics, and provides - * relatively fast addition/removal of elements at the end of the sequence. - *
+ *
Generally implemented as a dynamic array, it allows direct access to any element in the + * sequence and provides relatively fast addition/removal of elements at the beginning or the end + * of the sequence.
*
* * @param Type of the elements. * + * @reference http://www.cplusplus.com/reference/deque/deque/ * @author Jeongho Nam */ - interface IArrayContainer extends ILinearContainer { + class Deque extends base.Container implements base.IArrayContainer, base.IDequeContainer { /** - *

Request a change in capacity.

- * - *

Requests that the {@link IArray container} {@link capacity} be at least enough to contain - * n elements.

- * - *

If n is greater than the current {@link IArray container} {@link capacity}, the - * function causes the {@link IArray container} to reallocate its storage increasing its - * {@link capacity} to n (or greater).

- * - *

In all other cases, the function call does not cause a reallocation and the - * {@link IArray container} {@link capacity} is not affected.

- * - *

This function has no effect on the {@link IArray container} {@link size} and cannot alter - * its elements.

- * - * @param n Minimum {@link capacity} for the {@link IArray container}. - * Note that the resulting {@link capacity} may be equal or greater than n. + * @hidden */ - reserve(n: number): void; + private static ROW; /** - *

Return size of allocated storage capacity.

- * - *

Returns the size of the storage space currently allocated for the {@link IArray container}, - * expressed in terms of elements.

- * - *

This {@link capacity} is not necessarily equal to the {@link IArray container} {@link size}. - * It can be equal or greater, with the extra space allowing to accommodate for growth without the - * need to reallocate on each insertion.

+ * @hidden + */ + private static MIN_CAPACITY; + /** + * @hidden + */ + private matrix_; + /** + * @hidden + */ + private size_; + /** + * @hidden + */ + private capacity_; + /** + * @hidden + */ + private get_col_size(); + /** + *

Default Constructor.

* - *

Notice that this {@link capacity} does not suppose a limit on the {@link size} of the - * {@link IArray container}. When this {@link capacity} is exhausted and more is needed, it is - * automatically expanded by the {@link IArray container} (reallocating it storage space). - * The theoretical limit on the {@link size} of a {@link IArray container} is given by member - * {@link max_size}.

+ *

Constructs an empty container, with no elements.

+ */ + constructor(); + /** + *

Initializer list Constructor.

* - *

The {@link capacity} of a {@link IArray container} can be explicitly altered by calling member - * {@link IArray.reserve}.

+ *

Constructs a container with a copy of each of the elements in array, in the same order.

* - * @return The size of the currently allocated storage capacity in the {@link IArray container}, - * measured in terms of the number elements it can hold. + * @param array An array containing elements to be copied and contained. */ - capacity(): number; + constructor(items: Array); /** - *

Access element.

- *

Returns a value to the element at position index in the {@link IArray container}.

- * - *

The function automatically checks whether index is within the bounds of valid elements - * in the {@link IArray container}, throwing an {@link OutOfRange} exception if it is not (i.e., - * if index is greater or equal than its {@link size}).

+ *

Fill Constructor.

* - * @param index Position of an element in the - * If this is greater than or equal to the {@link IArray container} {@link size}, an - * exception of type {@link OutOfRange} is thrown. Notice that the first - * element has a position of 0 (not 1). + *

Constructs a container with n elements. Each element is a copy of val (if provided).

* - * @return The element at the specified position in the + * @param n Initial container size (i.e., the number of elements in the container at construction). + * @param val Value to fill the container with. Each of the n elements in the container is + * initialized to a copy of this value. */ - at(index: number): T; + constructor(size: number, val: T); /** - *

Modify element.

- *

Replaces an element at the specified position (index) in this {@link IArray container} - * with the specified element (val).

- * - *

The function automatically checks whether index is within the bounds of valid elements - * in the {@link IArray container}, throwing an {@link OutOfRange} exception if it is not (i.e., if - * index is greater or equal than its {@link size}).

+ *

Copy Constructor.

* - * @.param index A specified position of the value to replace. - * @param val A value to be stored at the specified position. + *

Constructs a container with a copy of each of the elements in container, in the same order.

* - * @return The previous element had stored at the specified position. + * @param container Another container object of the same type (with the same class template + * arguments T), whose contents are either copied or acquired. */ - set(index: number, val: T): void; - } -} -declare namespace std.base { - /** - *

Random-access iterator.

- * - *

{@link IArrayIterator Random-access iterators} are iterators that can be used to access elements at an - * arbitrary offset position relative to the element they point to, offering the same functionality as pointers. - *

- * - *

{@link IArrayIterator Random-access iterators} are the most complete iterators in terms of functionality. - * All pointer types are also valid {@link IArrayIterator random-access iterators}.

- * - *

There is not a single type of {@link IArrayIterator random-access iterator}: Each container may define its - * own specific iterator type able to iterate through it and access its elements.

- * - *

- * - *

- * - * @reference http://www.cplusplus.com/reference/iterator/RandomAccessIterator - * @author Jeongho Nam - */ - interface IArrayIterator extends Iterator { + constructor(container: Deque); /** - * Get index, sequence number of the iterator in the source {@link IArray array}. + *

Range Constructor.

* - * @return Sequence number of the iterator in the source {@link IArray array}. + *

Constructs a container with as many elements as the range (begin, end), with each + * element emplace-constructed from its corresponding element in that range, in the same order.

+ * + * @param begin Input interator of the initial position in a sequence. + * @param end Input interator of the final position in a sequence. */ - index: number; + constructor(begin: Iterator, end: Iterator); /** * @inheritdoc */ - prev(): IArrayIterator; + assign>(begin: InputIterator, end: InputIterator): void; /** * @inheritdoc */ - next(): IArrayIterator; - } -} -declare namespace std.base { - /** - *

An interface of containers.

- * - *

{@link IContainer} is an interface designed for sequence containers. Sequence containers of STL - * (Standard Template Library) are based on the {@link IContainer}.

- * - *

- * - *

- * - *

Container properties

- *
- *
Sequence
- *
Elements in sequence containers are ordered in a strict linear sequence. Individual elements are - * accessed by their position in this sequence.
- * - *
Doubly-linked list
- *
Each element keeps information on how to locate the next and the previous elements, allowing - * constant time insert and erase operations before or after a specific element (even of entire ranges), - * but no direct random access.
- *
- * - * @param Type of elements. - * - * @author Jeongho Nam - */ - interface IContainer { + assign(n: number, val: T): void; /** - *

Assign new content to content.

- * - *

Assigns new contents to the container, replacing its current contents, and modifying its - * {@link size} accordingly.

- * - * @param begin Input interator of the initial position in a sequence. - * @param end Input interator of the final position in a sequence. + * @inheritdoc */ - assign>(begin: InputIterator, end: InputIterator): void; + reserve(capacity: number): void; /** - *

Clear content.

- * - *

Removes all elements from the Container, leaving the container with a size of 0.

+ * @inheritdoc */ clear(): void; /** - *

Return iterator to beginning.

- * - *

Returns an iterator referring the first element in the

- * - *

Note

- *

If the container is {@link empty}, the returned iterator is same with {@link end end()}.

- * - * @return An iterator to the first element in the The iterator containes the first element's value. + * @inheritdoc */ - begin(): Iterator; + begin(): DequeIterator; /** - *

Return iterator to end.

- *

Returns an iterator referring to the past-the-end element in the

- * - *

The past-the-end element is the theoretical element that would follow the last element in the - * It does not point to any element, and thus shall not be dereferenced.

- * - *

Because the ranges used by functions of the Container do not include the element reference by their - * closing iterator, this function is often used in combination with {@link IContainer}.{@link begin} to - * specify a range including all the elements in the container.

- * - *

Note

- *

Returned iterator from {@link IContainer}.{@link end} does not refer any element. Trying to accessing - * element by the iterator will cause throwing exception ({@link OutOfRange}).

- * - *

If the container is {@link empty}, this function returns the same as {@link Container}.{@link begin}. - *

- * - * @return An iterator to the end element in the + * @inheritdoc */ - end(): Iterator; + end(): DequeIterator; /** - *

Return {@link ReverseIterator reverse iterator} to reverse beginning.

- * - *

Returns a {@link ReverseIterator reverse iterator} pointing to the last element in the container (i.e., - * its reverse beginning).

- * - *

{@link ReverseIterator reverse iterators} iterate backwards: increasing them moves them towards the - * beginning of the

- * - *

{@link rbegin} points to the element right before the one that would be pointed to by member {@link end}. - *

- * - * @return A {@link ReverseIterator reverse iterator} to the reverse beginning of the sequence + * @inheritdoc */ - rbegin(): base.IReverseIterator; + rbegin(): DequeReverseIterator; /** - *

Return {@link ReverseIterator reverse iterator} to reverse end.

- * - *

Returns a {@link ReverseIterator reverse iterator} pointing to the theoretical element preceding the - * first element in the container (which is considered its reverse end).

- * - *

The range between {@link IContainer}.{@link rbegin} and {@link IContainer}.{@link rend} contains all - * the elements of the container (in reverse order). - * - * @return A {@link ReverseIterator reverse iterator} to the reverse end of the sequence + * @inheritdoc */ - rend(): base.IReverseIterator; + rend(): DequeReverseIterator; /** - * Return the number of elements in the Container. - * - * @return The number of elements in the + * @inheritdoc */ size(): number; /** - *

Test whether the container is empty.

- *

Returns whether the container is empty (i.e. whether its size is 0).

- * - *

This function does not modify the container in any way. To clear the content of the container, - * see {@link clear clear()}.

- * - * @return true if the container size is 0, false otherwise. + * @inheritdoc */ empty(): boolean; /** - *

Insert elements.

- * - *

Appends new elements to the container, and returns the new size of the

- * - * @param items New elements to insert. - * - * @return New size of the Container. + * @inheritdoc */ - push(...items: U[]): number; + capacity(): number; /** - *

Insert an element.

- * - *

The container is extended by inserting a new element before the element at the specified - * position. This effectively increases the {@link IContainer.size container size} by the amount of - * elements inserted.

- * - * @param position Position in the {@link IContainer} where the new element is inserted. - * {@link iterator} is a member type, defined as a {@link Iterator random access iterator} - * type that points to elements. - * @param val Value to be copied to the inserted element. - * - * @return An iterator that points to the newly inserted element. + * @inheritdoc */ - insert(position: Iterator, val: T): Iterator; + at(index: number): T; /** - *

Erase an element.

- * - *

Removes from the container a single element.

- * - *

This effectively reduces the container size by the number of element removed.

- * - * @param position Iterator pointing to a single element to be removed from the Container. - * - * @return An iterator pointing to the element that followed the last element erased by the function - * call. This is the {@link end Container.end} if the operation erased the last element in the - * sequence. + * @inheritdoc */ - erase(position: Iterator): Iterator; + set(index: number, val: T): void; /** - *

Erase elements.

- * - *

Removes from the container a range of elements.

- * - *

This effectively reduces the container size by the number of elements removed.

- * - * @param begin An iterator specifying a range of beginning to erase. - * @param end An iterator specifying a range of end to erase. - * - * @return An iterator pointing to the element that followed the last element erased by the function - * call. This is the {@link end Container.end} if the operation erased the last element in - * the sequence. + * @inheritdoc */ - erase(begin: Iterator, end: Iterator): Iterator; + front(): T; + /** + * @inheritdoc + */ + back(): T; + /** + // Fetch row and column's index. + /** + * @hidden + */ + private fetch_index(index); + /** + * @inheritdoc + */ + push(...items: T[]): number; + /** + * @inheritdoc + */ + push_front(val: T): void; + /** + * @inheritdoc + */ + push_back(val: T): void; + /** + * @inheritdoc + */ + pop_front(): void; + /** + * @inheritdoc + */ + pop_back(): void; + /** + * @inheritdoc + */ + insert(position: DequeIterator, val: T): DequeIterator; + /** + * @inheritdoc + */ + insert(position: DequeIterator, n: number, val: T): DequeIterator; + /** + * @inheritdoc + */ + insert>(position: DequeIterator, begin: InputIterator, end: InputIterator): DequeIterator; + /** + * @inheritdoc + */ + insert(position: DequeReverseIterator, val: T): DequeReverseIterator; + /** + * @inheritdoc + */ + insert(position: DequeReverseIterator, n: number, val: T): DequeReverseIterator; + /** + * @inheritdoc + */ + insert>(position: DequeReverseIterator, begin: InputIterator, end: InputIterator): DequeReverseIterator; + /** + * @hidden + */ + private insert_by_val(position, val); + /** + * @hidden + */ + protected _Insert_by_repeating_val(position: DequeIterator, n: number, val: T): DequeIterator; + /** + * @hidden + */ + protected _Insert_by_range>(position: DequeIterator, begin: InputIterator, end: InputIterator): DequeIterator; + /** + * @hidden + */ + private insert_by_items(position, items); + /** + * @inheritdoc + */ + erase(position: DequeIterator): DequeIterator; + /** + * @inheritdoc + */ + erase(first: DequeIterator, last: DequeIterator): DequeIterator; + /** + * @inheritdoc + */ + erase(position: DequeReverseIterator): DequeReverseIterator; + /** + * @inheritdoc + */ + erase(first: DequeReverseIterator, last: DequeReverseIterator): DequeReverseIterator; + /** + * @hidden + */ + protected _Erase_by_range(first: DequeIterator, last: DequeIterator): DequeIterator; /** *

Swap content.

* *

Exchanges the content of the container by the content of obj, which is another - * {@link IContainer container} object with same type of elements. Sizes and container type may differ.

+ * {@link Deque container} object with same type of elements. Sizes and container type may differ.

* *

After the call to this member function, the elements in this container are those which were in obj * before the call, and the elements of obj are those which were in this. All iterators, references and @@ -3999,1225 +3473,1008 @@ declare namespace std.base { *

Notice that a non-member function exists with the same name, {@link std.swap swap}, overloading that * algorithm with an optimization that behaves like this member function.

* - * @param obj Another {@link IContainer container} of the same type of elements (i.e., instantiated + * @param obj Another {@link Deque container} of the same type of elements (i.e., instantiated * with the same template parameter, T) whose content is swapped with that of this - * {@link container IContainer}. + * {@link container Deque}. */ - swap(obj: IContainer): void; - } - interface IReverseIterator extends ReverseIterator, IReverseIterator> { + swap(obj: Deque): void; + /** + * @inheritdoc + */ + swap(obj: base.IContainer): void; } } -declare namespace std.base { +declare namespace std { /** - *

An interface for deque

+ *

An iterator of {@link Deque}.

* - *

- * - *

+ *

+ * + *

* * @author Jeongho Nam */ - interface IDequeContainer extends ILinearContainer { + class DequeIterator extends Iterator implements base.IArrayIterator { /** - *

Insert element at beginning.

+ * Sequence number of iterator in the source {@link Deque}. + */ + private index_; + /** + *

Construct from the source {@link Deque container}.

* - *

Inserts a new element at the beginning of the {@link IDeque container}, right before its - * current first element. This effectively increases the {@link IDeque container} {@link size} by - * one.

+ *

Note

+ *

Do not create the iterator directly, by yourself.

+ *

Use {@link Deque.begin begin()}, {@link Deque.end end()} in {@link Deque container} instead.

* - * @param val Value to be inserted as an element. + * @param source The source {@link Deque container} to reference. + * @param index Sequence number of the element in the source {@link Deque}. */ - push_front(val: T): void; + constructor(source: Deque, index: number); /** - *

Delete first element.

- * - *

Removes the first element in the {@link IDeque container}, effectively reducing its - * {@link size} by one.

+ * @hidden */ - pop_front(): void; - } -} -declare namespace std.base { - /** - *

An interface for linear containers.

- * - *

- * - *

- * - * @author Jeonngho Nam - */ - interface ILinearContainer extends IContainer { + private deque; /** * @inheritdoc */ - assign>(begin: InputIterator, end: InputIterator): void; /** - *

Assign container content.

- * - *

Assigns new contents to the {@link IList container}, replacing its current contents, - * and modifying its {@link size} accordingly.

+ * Set value of the iterator is pointing to. * - * @param n New size for the - * @param val Value to fill the container with. Each of the n elements in the container will - * be initialized to a copy of this value. + * @param val Value to set. */ - assign(n: number, val: T): void; + value: T; /** - *

Access first element.

- *

Returns a value of the first element in the {@link IList container}.

- * - *

Unlike member {@link end end()}, which returns an iterator just past this element, - * this function returns a direct value.

- * - *

Calling this function on an {@link empty} {@link IList container} causes undefined behavior.

- * - * @return A value of the first element of the {@link IList container}. + * @inheritdoc */ - front(): T; + index: number; /** - *

Access last element.

- *

Returns a value of the last element in the {@link IList container}.

- * - *

Unlike member {@link end end()}, which returns an iterator just past this element, - * this function returns a direct value.

- * - *

Calling this function on an {@link empty} {@link IList container} causes undefined behavior.

- * - * @return A value of the last element of the {@link IList container}. + * @inheritdoc */ - back(): T; + prev(): DequeIterator; /** - *

Add element at the end.

- * - *

Adds a new element at the end of the {@link IList container}, after its current last element. - * This effectively increases the {@link IList container} {@link size} by one.

- * - * @param val Value to be copied to the new element. + * @inheritdoc */ - push_back(val: T): void; + next(): DequeIterator; /** - *

Delete last element.

- * - *

Removes the last element in the {@link IList container}, effectively reducing the - * {@link IList container} {@link size} by one.

+ * @inheritdoc */ - pop_back(): void; + advance(n: number): DequeIterator; /** - *

Insert an element.

+ *

Whether an iterator is equal with the iterator.

* - *

The {@link IList conatiner} is extended by inserting new element before the element at the - * specified position, effectively increasing the {@link IList container} {@link size} by - * one.

+ *

Compare two iterators and returns whether they are equal or not.

* - * @param position Position in the {@link IList container} where the new elements are inserted. - * {@link iterator} is a member type, defined as a {@link iterator random access iterator} - * type that points to elements. - * @param val Value to be copied to the inserted element. + *

Note

+ *

Iterator's equal_to() only compare souce container and index number.

* - * @return An iterator that points to the newly inserted element. - */ - insert(position: Iterator, val: T): Iterator; - /** - *

Insert elements by range iterators.

- * - *

The {@link IList container} is extended by inserting new elements before the element at the - * specified position, effectively increasing the {@link IList container} {@link size} by - * the number of repeating elements n.

- * - * @param position Position in the {@link IList container} where the new elements are inserted. - * {@link iterator} is a member type, defined as a {@link iterator random access iterator} - * type that points to elements. - * @param n Number of elements to insert. Each element is initialized to a copy of val. - * @param val Value to be copied (or moved) to the inserted elements. + *

Although elements in a pair, key and value are equal_to, if the source map or + * index number is different, then the {@link equal_to equal_to()} will return false. If you want to + * compare the elements of a pair, compare them directly by yourself.

* - * @return An iterator that points to the first of the newly inserted elements. + * @param obj An iterator to compare + * @return Indicates whether equal or not. */ - insert(position: Iterator, n: number, val: T): Iterator; + equal_to(obj: DequeIterator): boolean; /** - *

Insert elements by range iterators.

- * - *

The {@link IList container} is extended by inserting new elements before the element at the - * specified position, effectively increasing the {@link IList container} {@link size} by - * the number of elements inserted by range iterators.

- * - * @param position Position in the {@link IList container} where the new elements are inserted. - * {@link iterator} is a member type, defined as a {@link iterator random access iterator} - * type that points to elements. - * @param begin Input interator of the initial position in a sequence. - * @param end Input interator of the final position in a sequence. - * - * @return An iterator that points to the first of the newly inserted elements. + * @inheritdoc */ - insert>(position: Iterator, begin: InputIterator, end: InputIterator): Iterator; + swap(obj: DequeIterator): void; } } declare namespace std { /** - *

Bi-directional iterator.

- * - *

{@link Iterator Bidirectional iterators} are iterators that can be used to access the sequence of elements - * in a range in both directions (towards the end and towards the beginning).

+ *

A reverse-iterator of Deque.

* - *

All {@link IArrayIterator random-access iterators} are also valid {@link Iterrator bidirectional iterators}. + *

+ * *

* - *

There is not a single type of {@link Iterator bidirectional iterator}: {@link IContainer Each container} - * may define its own specific iterator type able to iterate through it and access its elements.

- * - *

- * - *

+ * @param Type of the elements. * - * @reference http://www.cplusplus.com/reference/iterator/BidirectionalIterator * @author Jeongho Nam */ - abstract class Iterator { - /** - * Source container of the iterator is directing for. - */ - protected source_: base.IContainer; - /** - * Construct from the source {@link IContainer container}. - * - * @param source The source - */ - constructor(source: base.IContainer); - /** - *

Get iterator to previous element.

- *

If current iterator is the first item(equal with {@link IContainer.begin IContainer.begin()}), - * returns {@link IContainer.end IContainer.end()}.

- * - * @return An iterator of the previous item. - */ - abstract prev(): Iterator; + class DequeReverseIterator extends ReverseIterator, DequeReverseIterator> implements base.IArrayIterator { /** - *

Get iterator to next element.

- *

If current iterator is the last item, returns {@link IContainer.end IContainer.end()}.

+ * Construct from base iterator. * - * @return An iterator of the next item. + * @param base A reference of the base iterator, which iterates in the opposite direction. */ - abstract next(): Iterator; + constructor(base: DequeIterator); /** - * Advances the {@link Iterator} by n element positions. - * - * @param n Number of element positions to advance. - * @return An advanced iterator. + * @hidden */ - advance(n: number): Iterator; + protected create_neighbor(base: DequeIterator): DequeReverseIterator; /** - * Get source + * @inheritdoc */ - get_source(): base.IContainer; /** - *

Whether an iterator is equal with the iterator.

- * - *

Compare two iterators and returns whether they are equal or not.

- * - *

Note

- *

Iterator's equal_to() only compare souce container and index number.

- * - *

Although elements in a pair, key and value are equal_to, if the source map or - * index number is different, then the {@link equal_to equal_to()} will return false. If you want to - * compare the elements of a pair, compare them directly by yourself.

+ * Set value of the iterator is pointing to. * - * @param obj An iterator to compare - * @return Indicates whether equal or not. + * @param val Value to set. */ - equal_to(obj: Iterator): boolean; + value: T; /** - *

Get value of the iterator is pointing.

- * - * @return A value of the iterator. + * Get index. */ - readonly value: T; - abstract swap(obj: Iterator): void; + index: number; } } declare namespace std { /** - *

This class reverses the direction in which a bidirectional or random-access iterator iterates through a range. - *

+ *

Function handling termination on exception

* - *

A copy of the original iterator (the {@link Iterator base iterator}) is kept internally and used to reflect - * the operations performed on the {@link ReverseIterator}: whenever the {@link ReverseIterator} is incremented, its - * {@link Iterator base iterator} is decreased, and vice versa. A copy of the {@link Iterator base iterator} with the - * current state can be obtained at any time by calling member {@link base}.

+ *

Calls the current terminate handler.

* - *

Notice however that when an iterator is reversed, the reversed version does not point to the same element in - * the range, but to the one preceding it. This is so, in order to arrange for the past-the-end element of a - * range: An iterator pointing to a past-the-end element in a range, when reversed, is pointing to the last element - * (not past it) of the range (this would be the first element of the reversed range). And if an iterator to the - * first element in a range is reversed, the reversed iterator points to the element before the first element (this - * would be the past-the-end element of the reversed range).

+ *

By default, the terminate handler calls abort. But this behavior can be redefined by calling + * {@link set_terminate}.

* - *

- * - *

+ *

This function is automatically called when no catch handler can be found for a thrown exception, + * or for some other exceptional circumstance that makes impossible to continue the exception handling process.

* - * @reference http://www.cplusplus.com/reference/iterator/reverse_iterator + *

This function is provided so that the terminate handler can be explicitly called by a program that needs to + * abnormally terminate, and works even if {@link set_terminate} has not been used to set a custom terminate handler + * (calling abort in this case).

+ */ + function terminate(): void; + /** + *

Set terminate handler function.

+ * + *

A terminate handler function is a function automatically called when the exception handling process has + * to be abandoned for some reason. This happens when no catch handler can be found for a thrown exception, or for + * some other exceptional circumstance that makes impossible to continue the exception handling process.

+ * + *

Before this function is called by the program for the first time, the default behavior is to call abort.

+ * + *

A program may explicitly call the current terminate handler function by calling {@link terminate}.

+ * + * @param f Function that takes no parameters and returns no value (void). + */ + function set_terminate(f: () => void): void; + /** + *

Get terminate handler function.

+ * + *

The terminate handler function is automatically called when no catch handler can be found + * for a thrown exception, or for some other exceptional circumstance that makes impossible to continue the exception + * handling process.

+ * + *

If no such function has been set by a previous call to {@link set_terminate}, the function returns a + * null-pointer.

+ * + * @return If {@link set_terminate} has previously been called by the program, the function returns the current + * terminate handler function. Otherwise, it returns a null-pointer. + */ + function get_terminate(): () => void; + /** + *

Standard exception class.

+ * + *

Base class for standard exceptions.

+ * + *

All objects thrown by components of the standard library are derived from this class. + * Therefore, all standard exceptions can be caught by catching this type by reference.

+ * + *

+ *

+ * + * @reference http://www.cplusplus.com/reference/exception/exception * @author Jeongho Nam */ - abstract class ReverseIterator, This extends ReverseIterator> extends Iterator { + class Exception extends Error { /** - * @hidden + * A message representing specification about the Exception. */ - protected base_: Base; + private description; /** - * Construct from base iterator. - * - * @param base A reference of the base iterator, which iterates in the opposite direction. + * Default Constructor. */ - constructor(base: Base); + constructor(); /** - *

Return base iterator.

- * - *

Return a reference of the base iteraotr.

- * - *

The base iterator is an iterator of the same type as the one used to construct the {@link ReverseIterator}, - * but pointing to the element next to the one the {@link ReverseIterator} is currently pointing to - * (a {@link ReverseIterator} has always an offset of -1 with respect to its base iterator). + *

Construct from a message.

* - * @return A reference of the base iterator, which iterates in the opposite direction. - */ - base(): Base; - /** - * @hidden + * @param message A message representing specification about the Exception. */ - protected abstract create_neighbor(base: Base): This; + constructor(message: string); /** - *

Get value of the iterator is pointing.

+ *

Get string identifying exception.

+ *

Returns a string that may be used to identify the exception.

* - * @return A value of the reverse iterator. - */ - readonly value: T; - /** - * @inheritdoc - */ - prev(): This; - /** - * @inheritdoc - */ - next(): This; - /** - * @inheritdoc + *

The particular representation pointed by the returned value is implementation-defined. + * As a virtual function, derived classes may redefine this function so that specify value are + * returned.

*/ - advance(n: number): This; + what(): string; /** * @inheritdoc */ - equal_to(obj: This): boolean; + message: string; /** * @inheritdoc */ - swap(obj: This): void; + name: string; } /** - *

Return distance between {@link Iterator iterators}.

+ *

Logic error exception.

* - *

Calculates the number of elements between first and last.

+ *

This class defines the type of objects thrown as exceptions to report errors in the internal + * logical of the program, such as violation of logical preconditions or class invariants.

* - *

If it is a {@link IArrayIterator random-access iterator}, the function uses operator- to calculate this. - * Otherwise, the function uses the increase operator {@link Iterator.next next()} repeatedly.

+ *

These errors are presumably detectable before the program executes.

* - * @param first Iterator pointing to the initial element. - * @param last Iterator pointing to the final element. This must be reachable from first. + *

It is used as a base class for several logical error exceptions.

* - * @return The number of elements between first and last. + *

+ *

+ * + * @reference http://www.cplusplus.com/reference/stdexcept/logic_error + * @author Jeongho Nam */ - function distance>(first: InputIterator, last: InputIterator): number; + class LogicError extends Exception { + /** + *

Construct from a message.

+ * + * @param message A message representing specification about the Exception. + */ + constructor(message: string); + } /** - *

Advance iterator.

+ *

Domain error exception.

* - *

Advances the iterator it by n elements positions.

- * - * @param it Iterator to be advanced. - * @param n Number of element positions to advance. + *

This class defines the type of objects thrown as exceptions to report domain errors.

* - * @return An iterator to the element n positions before it. - */ - function advance>(it: InputIterator, n: number): InputIterator; - /** - *

Get iterator to previous element.

+ *

Generally, the domain of a mathematical function is the subset of values that it is defined for. + * For example, the square root function is only defined for non-negative numbers. Thus, a negative number + * for such a function would qualify as a domain error.

* - *

Returns an iterator pointing to the element that it would be pointing to if advanced -n positions.

+ *

No component of the standard library throws exceptions of this type. It is designed as a standard + * exception to be thrown by programs.

* - * @param it Iterator to base position. - * @param n Number of element positions offset (1 by default). + *

+ *

* - * @return An iterator to the element n positions before it. + * @reference http://www.cplusplus.com/reference/stdexcept/domain_error + * @author Jeongho Nam */ - function prev>(it: BidirectionalIterator, n?: number): BidirectionalIterator; + class DomainError extends LogicError { + /** + *

Construct from a message.

+ * + * @param message A message representing specification about the Exception. + */ + constructor(message: string); + } /** - *

Get iterator to next element.

+ *

Invalid argument exception.

* - *

Returns an iterator pointing to the element that it would be pointing to if advanced n positions.

+ *

This class defines the type of objects thrown as exceptions to report an invalid argument.

* - * @param it Iterator to base position. - * @param n Number of element positions offset (1 by default). + *

It is a standard exception that can be thrown by programs. Some components of the standard library + * also throw exceptions of this type to signal invalid arguments.

* - * @return An iterator to the element n positions away from it. + *

+ *

+ * + * @reference http://www.cplusplus.com/reference/stdexcept/invalid_argument + * @author Jeongho Nam */ - function next>(it: ForwardIterator, n?: number): ForwardIterator; + class InvalidArgument extends LogicError { + /** + *

Construct from a message.

+ * + * @param message A message representing specification about the Exception. + */ + constructor(message: string); + } /** - *

Iterator to beginning.

+ *

Length error exception.

* - *

Returns an iterator pointing to the first element in the sequence.

+ *

This class defines the type of objects thrown as exceptions to report a length error.

* - *

If the sequence is empty, the returned value shall not be dereferenced.

+ *

It is a standard exception that can be thrown by programs. Some components of the standard library, + * such as vector and string also throw exceptions of this type to signal errors resizing.

* - * @param container A container object of a class type for which member {@link IContainer.begin begin} is defined. + *

+ *

* - * @return The same as returned by {@link IContainer.begin container.begin()}. + * @reference http://www.cplusplus.com/reference/stdexcept/length_error + * @author Jeongho Nam */ - function begin(container: Vector): VectorIterator; + class LengthError extends LogicError { + /** + *

Construct from a message.

+ * + * @param message A message representing specification about the Exception. + */ + constructor(message: string); + } /** - *

Iterator to beginning.

+ *

Out-of-range exception.

* - *

Returns an iterator pointing to the first element in the sequence.

+ *

This class defines the type of objects thrown as exceptions to report an out-of-range error.

* - *

If the sequence is empty, the returned value shall not be dereferenced.

+ *

It is a standard exception that can be thrown by programs. Some components of the standard library, + * such as vector, deque, string and bitset also throw exceptions of this type to signal arguments + * out of range.

* - * @param container A container object of a class type for which member {@link IContainer.begin begin} is defined. + *

+ *

* - * @return The same as returned by {@link IContainer.begin container.begin()}. + * @reference http://www.cplusplus.com/reference/stdexcept/out_of_range + * @author Jeongho Nam */ - function begin(container: List): ListIterator; + class OutOfRange extends LogicError { + /** + *

Construct from a message.

+ * + * @param message A message representing specification about the Exception. + */ + constructor(message: string); + } /** - *

Iterator to beginning.

+ *

Runtime error exception.

* - *

Returns an iterator pointing to the first element in the sequence.

+ *

This class defines the type of objects thrown as exceptions to report errors that can only be + * detected during runtime.

* - *

If the sequence is empty, the returned value shall not be dereferenced.

+ *

It is used as a base class for several runtime error exceptions.

* - * @param container A container object of a class type for which member {@link IContainer.begin begin} is defined. + *

+ *

* - * @return The same as returned by {@link IContainer.begin container.begin()}. + * @reference http://www.cplusplus.com/reference/stdexcept/runtime_error + * @author Jeongho Nam */ - function begin(container: Deque): DequeIterator; + class RuntimeError extends Exception { + /** + *

Construct from a message.

+ * + * @param message A message representing specification about the Exception. + */ + constructor(message: string); + } /** - *

Iterator to beginning.

+ *

Overflow error exception.

* - *

Returns an iterator pointing to the first element in the sequence.

+ *

This class defines the type of objects thrown as exceptions to arithmetic overflow errors.

* - *

If the sequence is empty, the returned value shall not be dereferenced.

+ *

It is a standard exception that can be thrown by programs. Some components of the standard library + * also throw exceptions of this type to signal range errors.

* - * @param container A container object of a class type for which member {@link IContainer.begin begin} is defined. + *

+ *

* - * @return The same as returned by {@link IContainer.begin container.begin()}. + * @reference http://www.cplusplus.com/reference/stdexcept/overflow_error + * @author Jeongho Nam */ - function begin(container: base.SetContainer): SetIterator; + class OverflowError extends RuntimeError { + /** + *

Construct from a message.

+ * + * @param message A message representing specification about the Exception. + */ + constructor(message: string); + } /** - *

Iterator to beginning.

+ *

Underflow error exception.

* - *

Returns an iterator pointing to the first element in the sequence.

+ *

This class defines the type of objects thrown as exceptions to arithmetic underflow errors.

* - *

If the sequence is empty, the returned value shall not be dereferenced.

+ *

No component of the standard library throws exceptions of this type. It is designed as a standard + * exception to be thrown by programs.

* - * @param container A container object of a class type for which member {@link IContainer.begin begin} is defined. + *

+ *

* - * @return The same as returned by {@link IContainer.begin container.begin()}. + * @reference http://www.cplusplus.com/reference/stdexcept/underflow_error + * @author Jeongho Nam */ - function begin(container: base.MapContainer): MapIterator; + class UnderflowError extends RuntimeError { + /** + *

Construct from a message.

+ * + * @param message A message representing specification about the Exception. + */ + constructor(message: string); + } /** - *

Iterator to end.

+ *

Range error exception.

* - *

Returns an iterator pointing to the past-the-end element in the sequence.

+ *

This class defines the type of objects thrown as exceptions to report range errors in internal + * computations.

* - *

If the sequence is {@link IContainer.empty empty}, the returned value compares equal to the one returned by {@link begin} with the same argument.

+ *

It is a standard exception that can be thrown by programs. Some components of the standard library + * also throw exceptions of this type to signal range errors.

* - * @param container A container of a class type for which member {@link IContainer.end end} is defined. + *

+ *

* - * @return The same as returned by {@link IContainer.end container.end()}. + * @reference http://www.cplusplus.com/reference/stdexcept/range_error + * @author Jeongho Nam */ - function end(container: Vector): VectorIterator; + class RangeError extends RuntimeError { + /** + *

Construct from a message.

+ * + * @param message A message representing specification about the Exception. + */ + constructor(message: string); + } +} +declare namespace std { /** - *

Iterator to end.

+ *

Function object class for equality comparison.

* - *

Returns an iterator pointing to the past-the-end element in the sequence.

+ *

Binary function object class whose call returns whether its two arguments compare equal (as returned by + * operator ==).

* - *

If the sequence is {@link IContainer.empty empty}, the returned value compares equal to the one returned by {@link begin} with the same argument.

+ *

Generically, function objects are instances of a class with member function {@link IComparable.equal_to equal_to} + * defined. This member function allows the object to be used with the same syntax as a function call.

* - * @param container A container of a class type for which member {@link IContainer.end end} is defined. + * @param x First element to compare. + * @param y Second element to compare. * - * @return The same as returned by {@link IContainer.end container.end()}. + * @return Whether the arguments are equal. */ - function end(container: List): ListIterator; + function equal_to(x: T, y: T): boolean; /** - *

Iterator to end.

+ *

Function object class for non-equality comparison.

* - *

Returns an iterator pointing to the past-the-end element in the sequence.

+ *

Binary function object class whose call returns whether its two arguments compare not equal (as returned + * by operator operator!=).

* - *

If the sequence is {@link IContainer.empty empty}, the returned value compares equal to the one returned by {@link begin} with the same argument.

+ *

Generically, function objects are instances of a class with member function {@link IComparable.equal_to equal_to} + * defined. This member function allows the object to be used with the same syntax as a function call.

* - * @param container A container of a class type for which member {@link IContainer.end end} is defined. + * @param x First element to compare. + * @param y Second element to compare. * - * @return The same as returned by {@link IContainer.end container.end()}. + * @return Whether the arguments are not equal. */ - function end(container: Deque): DequeIterator; + function not_equal_to(x: T, y: T): boolean; /** - *

Iterator to end.

+ *

Function for less-than inequality comparison.

* - *

Returns an iterator pointing to the past-the-end element in the sequence.

+ *

Binary function returns whether the its first argument compares less than the second.

* - *

If the sequence is {@link IContainer.empty empty}, the returned value compares equal to the one returned by {@link begin} with the same argument.

+ *

Generically, function objects are instances of a class with member function {@link IComparable.less less} + * defined. If an object doesn't have the method, then its own uid will be used to compare insteadly. + * This member function allows the object to be used with the same syntax as a function call.

* - * @param container A container of a class type for which member {@link IContainer.end end} is defined. + *

Objects of this class can be used on standard algorithms such as {@link sort sort()}, + * {@link merge merge()} or {@link TreeMap.lower_bound lower_bound()}.

* - * @return The same as returned by {@link IContainer.end container.end()}. + * @param Type of arguments to compare by the function call. The type shall supporrt the operation + * operator<() or method {@link IComparable.less less}. + * + * @param x First element, the standard of comparison. + * @param y Second element compare with the first. + * + * @return Whether the first parameter is less than the second. */ - function end(container: base.SetContainer): SetIterator; + function less(x: T, y: T): boolean; /** - *

Iterator to end.

+ *

Function object class for less-than-or-equal-to comparison.

* - *

Returns an iterator pointing to the past-the-end element in the sequence.

+ *

Binary function object class whose call returns whether the its first argument compares {@link less less than} or + * {@link equal_to equal to} the second (as returned by operator <=).

* - *

If the sequence is {@link IContainer.empty empty}, the returned value compares equal to the one returned by {@link begin} with the same argument.

+ *

Generically, function objects are instances of a class with member function {@link IComparable.less less} + * and {@link IComparable.equal_to equal_to} defined. This member function allows the object to be used with the same + * syntax as a function call.

* - * @param container A container of a class type for which member {@link IContainer.end end} is defined. + * @param x First element, the standard of comparison. + * @param y Second element compare with the first. * - * @return The same as returned by {@link IContainer.end container.end()}. + * @return Whether the x is {@link less less than} or {@link equal_to equal to} the y. */ - function end(container: base.MapContainer): MapIterator; -} -declare namespace std.base { + function less_equal(x: T, y: T): boolean; /** - *

An abstract map.

+ *

Function for greater-than inequality comparison.

* - *

{@link MapContainer MapContainers} are associative containers that store elements formed by a combination - * of a key value (Key) and a mapped value (T), and which allows for fast retrieval - * of individual elements based on their keys.

+ *

Binary function returns whether the its first argument compares greater than the second.

* - *

In a {@link MapContainer}, the key values are generally used to identify the elements, while the - * mapped values store the content associated to this key. The types of key and - * mapped value may differ, and are grouped together in member type value_type, which is a - * {@link Pair} type combining both:

+ *

Generically, function objects are instances of a class with member function {@link less} and + * {@link equal_to equal_to()} defined. If an object doesn't have those methods, then its own uid will be used + * to compare insteadly. This member function allows the object to be used with the same syntax as a function + * call.

* - *

typedef pair value_type;

+ *

Objects of this class can be used on standard algorithms such as {@link sort sort()}, + * {@link merge merge()} or {@link TreeMap.lower_bound lower_bound()}.

* - *

{@link MapContainer} stores elements, keeps sequence and enables indexing by inserting elements into a - * {@link List} and registering {@link ListIterator iterators} of the {@link data_ list container} to an index - * table like {@link RBTree tree} or {@link HashBuckets hash-table}.

+ * @param Type of arguments to compare by the function call. The type shall supporrt the operation + * operator>() or method {@link IComparable.greater greater}. * - *

- *

+ * @return Whether the x is greater than the y. + */ + function greater(x: T, y: T): boolean; + /** + *

Function object class for greater-than-or-equal-to comparison.

* - *

Container properties

- *
- *
Associative
- *
- * Elements in associative containers are referenced by their key and not by their absolute position - * in the container. - *
+ *

Binary function object class whose call returns whether the its first argument compares + * {@link greater greater than} or {@link equal_to equal to} the second (as returned by operator >=).

* - *
Map
- *
- * Each element associates a key to a mapped value: - * Keys are meant to identify the elements whose main content is the mapped value. - *
- *
+ *

Generically, function objects are instances of a class with member function {@link IComparable.less less} + * defined. If an object doesn't have the method, then its own uid will be used to compare insteadly. + * This member function allows the object to be used with the same syntax as a function call.

* - * @param Type of the keys. Each element in a map is identified by its key value. - * @param Type of the mapped value. Each element in a map stores some data as its mapped value. + * @param x First element, the standard of comparison. + * @param y Second element compare with the first. + * + * @return Whether the x is {@link greater greater than} or {@link equal_to equal to} the y. + */ + function greater_equal(x: T, y: T): boolean; + /** + *

Logical AND function object class.

+ * + *

Binary function object class whose call returns the result of the logical "and" operation between its two + * arguments (as returned by operator &&).

+ * + *

Generically, function objects are instances of a class with member function operator() defined. This member + * function allows the object to be used with the same syntax as a function call.

+ * + * @param x First element. + * @param y Second element. + * + * @return Result of logical AND operation. + */ + function logical_and(x: T, y: T): boolean; + /** + *

Logical OR function object class.

+ * + *

Binary function object class whose call returns the result of the logical "or" operation between its two + * arguments (as returned by operator ||).

+ * + *

Generically, function objects are instances of a class with member function operator() defined. This member + * function allows the object to be used with the same syntax as a function call.

+ * + * @param x First element. + * @param y Second element. + * + * @return Result of logical OR operation. + */ + function logical_or(x: T, y: T): boolean; + /** + *

Logical NOT function object class.

+ * + *

Unary function object class whose call returns the result of the logical "not" operation on its argument + * (as returned by operator !).

+ * + *

Generically, function objects are instances of a class with member function operator() defined. This member + * function allows the object to be used with the same syntax as a function call.

+ * + * @param x Target element. + * + * @return Result of logical NOT operation. + */ + function logical_not(x: T): boolean; + /** + *

Bitwise AND function object class.

+ * + *

Binary function object class whose call returns the result of applying the bitwise "and" operation between + * its two arguments (as returned by operator &).

+ * + * @param x First element. + * @param y Second element. + * + * @return Result of bitwise AND operation. + */ + function bit_and(x: number, y: number): number; + /** + *

Bitwise OR function object class.

+ * + *

Binary function object class whose call returns the result of applying the bitwise "and" operation between + * its two arguments (as returned by operator &).

+ * + * @param x First element. + * @param y Second element. + * + * @return Result of bitwise OR operation. + */ + function bit_or(x: number, y: number): number; + /** + *

Bitwise XOR function object class.

* + *

Binary function object class whose call returns the result of applying the bitwise "exclusive or" + * operation between its two arguments (as returned by operator ^).

+ * + * @param x First element. + * @param y Second element. + * + * @return Result of bitwise XOR operation. + */ + function bit_xor(x: number, y: number): number; + /** + *

Comparable instance.

+ * + *

{@link IComparable} is a common interface for objects who can compare each other.

+ * + * @reference https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html * @author Jeongho Nam */ - abstract class MapContainer extends Container> { - /** - *

{@link List} storing elements.

- * - *

Storing elements and keeping those sequence of the {@link MapContainer} are implemented by - * {@link data_ this list container}. Implementing index-table is also related with {@link data_ this list} - * by storing {@link ListIterator iterators} ({@link MapIterator} references {@link ListIterator}) who are - * created from {@link data_ here}.

- */ - private data_; - /** - * Default Constructor. - */ - constructor(); - /** - * @inheritdoc - */ - assign>>(first: InputIterator, last: InputIterator): void; - /** - * @inheritdoc - */ - clear(): void; + interface IComparable extends Object { /** - *

Get iterator to element.

+ *

Indicates whether some other object is "equal to" this one.

* - *

Searches the container for an element with a identifier equivalent to key and returns an - * iterator to it if found, otherwise it returns an iterator to {@link end end()}.

+ *

The {@link equal_to} method implements an equivalence relation on non-null object references:

* - *

Two keys are considered equivalent if the container's comparison object returns false reflexively - * (i.e., no matter the order in which the elements are passed as arguments).

+ *
    + *
  • + * It is reflexive: for any non-null reference value x, x.equal_to(x) + * should return true. + *
  • + *
  • + * It is symmetric: for any non-null reference values x and y, + * x.equal_to(y) should return true if and only if y.equal_to(x) + * returns true.
  • + *
  • + * It is transitive: for any non-null reference values x, y, and + * z, if x.equal_to(y) returns true and y.equal_to(z) + * returns true, then x.equal_to(z) should return true. + *
  • + *
  • + * It is consistent: for any non-null reference values x and y, multiple + * invocations of x.equal_to(y) consistently return true or consistently return + * false, provided no information used in equal_to comparisons on the objects is modified. + *
  • + *
  • + * For any non-null reference value x, x.equal_to(null) should return + * false. + *
  • + *
* - *

Another member functions, {@link has has()} and {@link count count()}, can be used to just check - * whether a particular key exists.

+ *

The {@link equal_to} method for interface {@link IComparable} implements the most discriminating possible + * equivalence relation on objects; that is, for any non-null reference values x and + * y, this method returns true if and only if x and y + * refer to the same object (x == y has the value true).

* - * @param key Key to be searched for - * @return An iterator to the element, if an element with specified key is found, or - * {@link end end()} otherwise. - */ - abstract find(key: Key): MapIterator; - /** - *

Return iterator to beginning.

+ *

Note that it is generally necessary to override the {@link hash_code} method whenever this method is + * overridden, so as to maintain the general contract for the {@link hash_code} method, which states that + * equal objects must have equal hash codes.

* - *

Returns an iterator referring the first element in the

+ *
    + *
  • {@link IComparable.equal_to} is called by {@link std.equal_to}.
  • + *
* - *

Note

- *

If the container is {@link empty}, the returned iterator is same with {@link end end()}.

+ * @param obj the reference object with which to compare. * - * @return An iterator to the first element in the The iterator containes the first element's value. + * @return true if this object is the same as the obj argument; false otherwise. */ - begin(): MapIterator; + equal_to(obj: T): boolean; /** - *

Return iterator to end.

- *

Returns an iterator referring to the past-the-end element in the

- * - *

The past-the-end element is the theoretical element that would follow the last element in the - * It does not point to any element, and thus shall not be dereferenced.

+ *

Less-than inequality comparison.

* - *

Because the ranges used by functions of the container do not include the element reference by their - * closing iterator, this function is often used in combination with {@link MapContainer}.{@link begin} to - * specify a range including all the elements in the

+ *

Binary method returns whether the the instance compares less than the obj.

* - *

Note

- *

Returned iterator from {@link MapContainer}.{@link end} does not refer any element. Trying to accessing - * element by the iterator will cause throwing exception ({@link OutOfRange}).

+ *
    + *
  • + * {@link IComparable.less} is called by {@link std.less}. Also, this method can be used on standard + * algorithms such as {@link sort sort()}, {@link merge merge()} or + * {@link TreeMap.lower_bound lower_bound()}. + *
  • + *
* - *

If the container is {@link empty}, this function returns the same as {@link begin}.

+ * @param obj the reference object with which to compare. * - * @return An iterator to the end element in the + * @return Whether the first parameter is less than the second. */ - end(): MapIterator; + less(obj: T): boolean; /** - *

Return {@link MapReverseIterator reverse iterator} to reverse beginning.

- * - *

Returns a {@link MapReverseIterator reverse iterator} pointing to the last element in the container - * (i.e., its reverse beginning).

+ *

Issue a hash code.

* - * {@link MapReverseIterator Reverse iterators} iterate backwards: increasing them moves them towards the - * beginning of the container.

- * - *

{@link rbegin} points to the element preceding the one that would be pointed to by member {@link end}. - *

- * - * @return A {@link MapReverseIterator reverse iterator} to the reverse beginning of the sequence - * - */ - rbegin(): MapReverseIterator; - /** - *

Return {@link MapReverseIterator reverse iterator} to reverse end.

- * - *

Returns a {@link MapReverseIterator reverse iterator} pointing to the theoretical element right before - * the first element in the {@link MapContainer map container} (which is considered its reverse end). - *

- * - *

The range between {@link MapContainer}.{@link rbegin} and {@link MapContainer}.{@link rend} contains - * all the elements of the container (in reverse order).

- * - * @return A {@link MapReverseIterator reverse iterator} to the reverse end of the sequence - */ - rend(): MapReverseIterator; - /** - *

Whether have the item or not.

- * - *

Indicates whether a map has an item having the specified identifier.

- * - * @param key Key value of the element whose mapped value is accessed. - * - * @return Whether the map has an item having the specified identifier. - */ - has(key: Key): boolean; - /** - *

Count elements with a specific key.

- * - *

Searches the container for elements whose key is key and returns the number of elements found.

- * - * @param key Key value to be searched for. - * - * @return The number of elements in the container with a key. - */ - abstract count(key: Key): number; - /** - * Return the number of elements in the map. - */ - size(): number; - /** - * @inheritdoc - */ - push(...args: Pair[]): number; - /** - * @inheritdoc - */ - push(...args: [Key, T][]): number; - /** - * Construct and insert element with hint - * - * Inserts a new element in the {@link MapContainer map container}. This new element is constructed in - * place using *args* as the arguments for the element's constructor. *hint* points to a location in the - * container suggested as a hint on where to start the search for its insertion point (the container may or - * may not use this suggestion to optimize the insertion operation). - * - * A similar member function exists, {@link insert}, which either copies or moves an existing object into - * the container, and may also take a position *hint*. - * - * @param hint Hint for the position where the element can be inserted. - * @param key The key used both to look up and to insert if not found. - * @param value Value, the item. - * - * @return An iterator pointing to either the newly inserted element or to the element that already had an - * equivalent key in the {@link MapContainer}. - */ - emplace_hint(hint: MapIterator, key: Key, val: T): MapIterator; - /** - * Construct and insert element with hint - * - * Inserts a new element in the {@link MapContainer map container}. This new element is constructed in - * place using *args* as the arguments for the element's constructor. *hint* points to a location in the - * container suggested as a hint on where to start the search for its insertion point (the container may or - * may not use this suggestion to optimize the insertion operation). - * - * A similar member function exists, {@link insert}, which either copies or moves an existing object into - * the container, and may also take a position *hint*. - * - * @param hint Hint for the position where the element can be inserted. - * @param key The key used both to look up and to insert if not found. - * @param value Value, the item. - * - * @return An {@link MapIterator iterator} pointing to either the newly inserted element or to the element - * that already had an equivalent key in the {@link MapContainer}. - */ - emplace_hint(hint: MapReverseIterator, key: Key, val: T): MapReverseIterator; - /** - * Construct and insert element with hint - * - * Inserts a new element in the {@link MapContainer map container}. This new element is constructed in - * place using *args* as the arguments for the element's constructor. *hint* points to a location in the - * container suggested as a hint on where to start the search for its insertion point (the container may or - * may not use this suggestion to optimize the insertion operation). - * - * A similar member function exists, {@link insert}, which either copies or moves an existing object into - * the container, and may also take a position *hint*. - * - * @param hint Hint for the position where the element can be inserted. - * @param pair A single argument of a {@link Pair} type with a value for the *key* as - * {@link Pair.first first} member, and a *value* for the mapped value as - * {@link Pair.second second}. - * - * @return An iterator pointing to either the newly inserted element or to the element that already had an - * equivalent key in the {@link MapContainer}. - */ - emplace_hint(hint: MapIterator, pair: Pair): MapIterator; - /** - * Construct and insert element with hint - * - * Inserts a new element in the {@link MapContainer map container}. This new element is constructed in - * place using *args* as the arguments for the element's constructor. *hint* points to a location in the - * container suggested as a hint on where to start the search for its insertion point (the container may or - * may not use this suggestion to optimize the insertion operation). - * - * A similar member function exists, {@link insert}, which either copies or moves an existing object into - * the container, and may also take a position *hint*. - * - * @param hint Hint for the position where the element can be inserted. - * @param pair A single argument of a {@link Pair} type with a value for the *key* as - * {@link Pair.first first} member, and a *value* for the mapped value as - * {@link Pair.second second}. - * - * @return An {@link MapIterator iterator} pointing to either the newly inserted element or to the element - * that already had an equivalent key in the {@link MapContainer}. - */ - emplace_hint(hint: MapReverseIterator, pair: Pair): MapReverseIterator; - /** - *

Insert an element.

- * - *

Extends the container by inserting a new element, effectively increasing the container {@link size} - * by the number of element inserted (zero or one).

- * - * @param hint Hint for the position where the element can be inserted. - * @param pair A single argument of a {@link Pair} type with a value for the *key* as - * {@link Pair.first first} member, and a *value* for the mapped value as - * {@link Pair.second second}. - * - * @return An iterator pointing to either the newly inserted element or to the element that already had an - * equivalent key in the {@link MapContainer}. - */ - insert(hint: MapIterator, pair: Pair): MapIterator; - /** - *

Insert an element.

- * - *

Extends the container by inserting a new element, effectively increasing the container {@link size} - * by the number of element inserted (zero or one).

- * - * @param hint Hint for the position where the element can be inserted. - * @param pair A single argument of a {@link Pair} type with a value for the *key* as - * {@link Pair.first first} member, and a *value* for the mapped value as - * {@link Pair.second second}. - * - * @return An iterator pointing to either the newly inserted element or to the element that already had an - * equivalent key in the {@link MapContainer}. - */ - insert(hint: MapReverseIterator, pair: Pair): MapReverseIterator; - /** - *

Insert an element.

- * - *

Extends the container by inserting new elements, effectively increasing the container {@link size} - * by the number of elements inserted.

- * - * @param hint Hint for the position where the element can be inserted. - * @param tuple Tuple represensts the {@link Pair} to be inserted as an element. - * - * @return An iterator pointing to either the newly inserted element or to the element that already had an - * equivalent key in the {@link MapContainer}. - */ - insert(hint: MapIterator, tuple: [L, U]): MapIterator; - /** - *

Insert an element.

- * - *

Extends the container by inserting new elements, effectively increasing the container {@link size} - * by the number of elements inserted.

- * - * @param hint Hint for the position where the element can be inserted. - * @param tuple Tuple represensts the {@link Pair} to be inserted as an element. - * - * @return An iterator pointing to either the newly inserted element or to the element that already had an - * equivalent key in the {@link MapContainer}. - */ - insert(hint: MapReverseIterator, tuple: [L, U]): MapReverseIterator; - /** - *

Insert elements from range iterators.

- * - *

Extends the container by inserting new elements, effectively increasing the container {@link size} by - * the number of elements inserted.

- * - * @param begin Input iterator specifying initial position of a range of elements. - * @param end Input iterator specifying final position of a range of elements. - * Notice that the range includes all the elements between begin and end, - * including the element pointed by begin but not the one pointed by end. - */ - insert>>(first: InputIterator, last: InputIterator): void; - /** - * @hidden - */ - protected abstract _Insert_by_pair(pair: Pair): any; - /** - * @hidden - */ - private insert_by_tuple(tuple); - /** - * @hidden - */ - protected abstract _Insert_by_hint(hint: MapIterator, pair: Pair): MapIterator; - /** - * @hidden - */ - private insert_by_hint_with_tuple(hint, tuple); - /** - * @hidden - */ - protected abstract _Insert_by_range>>(first: InputIterator, last: InputIterator): void; - /** - *

Erase an elemet by key.

- * - *

Removes from the {@link MapContainer map container} a single element.

- * - *

This effectively reduces the container {@link size} by the number of element removed (zero or one), - * which are destroyed.

- * - * @param key Key of the element to be removed from the {@link MapContainer}. - */ - erase(key: Key): number; - /** - *

Erase an elemet by iterator.

- * - *

Removes from the {@link MapContainer map container} a single element.

- * - *

This effectively reduces the container {@link size} by the number of element removed (zero or one), - * which are destroyed.

- * - * @param it Iterator specifying position winthin the {@link MapContainer map contaier} to be removed. - */ - erase(it: MapIterator): MapIterator; - /** - *

Erase elements by range iterators.

- * - *

Removes from the {@link MapContainer map container} a range of elements.

- * - *

This effectively reduces the container {@link size} by the number of elements removed, which are - * destroyed.

- * - * @param begin An iterator specifying initial position of a range within {@link MApContainer map container} - * to be removed. - * @param end An iterator specifying initial position of a range within {@link MApContainer map container} - * to be removed. - * Notice that the range includes all the elements between begin and end, - * including the element pointed by begin but not the one pointed by end. - */ - erase(begin: MapIterator, end: MapIterator): MapIterator; - /** - *

Erase an elemet by iterator.

- * - *

Removes from the {@link MapContainer map container} a single element.

- * - *

This effectively reduces the container {@link size} by the number of element removed (zero or one), - * which are destroyed.

- * - * @param it Iterator specifying position winthin the {@link MapContainer map contaier} to be removed. - */ - erase(it: MapReverseIterator): MapReverseIterator; - /** - *

Erase elements by range iterators.

- * - *

Removes from the {@link MapContainer map container} a range of elements.

- * - *

This effectively reduces the container {@link size} by the number of elements removed, which are - * destroyed.

- * - * @param begin An iterator specifying initial position of a range within {@link MApContainer map container} - * to be removed. - * @param end An iterator specifying initial position of a range within {@link MApContainer map container} - * to be removed. - * Notice that the range includes all the elements between begin and end, - * including the element pointed by begin but not the one pointed by end. - */ - erase(begin: MapReverseIterator, end: MapReverseIterator): MapReverseIterator; - /** - * @hidden - */ - private erase_by_key(key); - /** - * @hidden - */ - private erase_by_iterator(first, last?); - /** - * @hidden - */ - private erase_by_range(begin, end); - /** - *

Abstract method handling insertions for indexing.

- * - *

This method, {@link _Handle_insert} is designed to register the first to last to somewhere storing - * those {@link MapIterator iterators} for indexing, fast accessment and retrievalance.

- * - *

When {@link insert} is called, new elements will be inserted into the {@link data_ list container} and new - * {@link MapIterator iterators} first to last, pointing the inserted elements, will be created and the - * newly created iterators first to last will be shifted into this method {@link _Handle_insert} after the - * insertions.

- * - *

If the derived one is {@link RBTree tree-based} like {@link TreeSet}, the {@link MapIterator iterators} - * will be registered into the {@link TreeSet.tree_ tree} as a {@link XTreeNode tree node item}. Else if the - * derived one is {@link HashBuckets hash-based} like {@link HashSet}, the first to last will be - * registered into the {@link HashSet.hash_buckets_ hash bucket}.

- * - * @param first An {@link MapIterator} to the initial position in a sequence. - * @param last An {@link MapIterator} to the final position in a sequence. The range used is - * [first, last), which contains all the elements between first and last, - * including the element pointed by first but not the element pointed by last. - */ - protected abstract _Handle_insert(first: MapIterator, last: MapIterator): void; - /** - *

Abstract method handling deletions for indexing.

- * - *

This method, {@link _Handle_erase} is designed to unregister the first to last to somewhere storing - * those {@link MapIterator iterators} for indexing, fast accessment and retrievalance.

+ *

Returns a hash code value for the object. This method is supported for the benefit of hash tables such + * as those provided by hash containers; {@link HashSet}, {@link HashMap}, {@link MultiHashSet} and + * {@link MultiHashMap}.

* - *

When {@link erase} is called with first to last, {@link MapIterator iterators} positioning somewhere - * place to be deleted, is memorized and shifted to this method {@link _Handle_erase} after the deletion process is - * terminated.

+ *

As much as is reasonably practical, the {@link hash_code} method defined by interface + * {@link IComparable} does return distinct integers for distinct objects. (This is typically implemented by + * converting the internal address of the object into an integer, but this implementation technique is not + * required by the JavaScript programming language.)

* - *

If the derived one is {@link RBTree tree-based} like {@link TreeSet}, the {@link MapIterator iterators} - * will be unregistered from the {@link TreeSet.tree_ tree} as a {@link XTreeNode tree node item}. Else if the - * derived one is {@link HashBuckets hash-based} like {@link HashSet}, the first to last will be - * unregistered from the {@link HashSet.hash_buckets_ hash bucket}.

+ *
    + *
  • + * {@link IComparable.hash_code} is called by {@link std.hash_code}. If you want to keep basically + * provided hash function, then returns {@link std.Hash.code}; return std.Hash.code(this); + *
  • + *
* - * @param first An {@link MapIterator} to the initial position in a sequence. - * @param last An {@link MapIterator} to the final position in a sequence. The range used is - * [first, last), which contains all the elements between first and last, - * including the element pointed by first but not the element pointed by last. - */ - protected abstract _Handle_erase(first: MapIterator, last: MapIterator): void; - /** - * @hidden + * @return An hash code who represents the object. */ - protected _Swap(obj: MapContainer): void; + hash(): number; } -} -declare namespace std { /** - *

An iterator of {@link MapContainer map container}.

+ *

Default hash function for number.

* - *

- *

+ *

Unary function that defines the default hash function used by the standard library.

* - * @author Jeongho Nam + *

The functional call returns a hash value of its argument: A hash value is a value that depends solely on + * its argument, returning always the same value for the same argument (for a given execution of a program). The + * value returned shall have a small likelihood of being the same as the one returned for a different argument. + *

+ * + * @param val Value to be hashed. + * + * @return Returns a hash value for its argument, as a value of type number. The number is an unsigned integer. */ - class MapIterator extends Iterator> implements IComparable> { - /** - * A {@link ListIterator} pointing {@link Pair} of key and value. - */ - private list_iterator_; - /** - * Construct from the {@link MapContainer source map} and {@link ListIterator list iterator}. - * - * @param source The source {@link MapContainer}. - * @param list_iterator A {@link ListIterator} pointing {@link Pair} of key and value. - */ - constructor(source: base.MapContainer, list_iterator: ListIterator>); - /** - * Get iterator to previous element. - */ - prev(): MapIterator; - /** - * Get iterator to next element. - */ - next(): MapIterator; - /** - * Advances the Iterator by n element positions. - * - * @param step Number of element positions to advance. - * @return An advanced Iterator. - */ - advance(step: number): MapIterator; - /** - * @hidden - */ - private readonly map; - /** - * Get ListIterator. - */ - get_list_iterator(): ListIterator>; - /** - * @inheritdoc - */ - readonly value: Pair; - /** - * Get first, key element. - */ - readonly first: Key; - /** - * Get second, value element. - */ - /** - * Set second value. - */ - second: T; - /** - *

Whether an iterator is equal with the iterator.

- * - *

Compare two iterators and returns whether they are equal or not.

- * - * @param obj An iterator to compare - * @return Indicates whether equal or not. - */ - equal_to(obj: MapIterator): boolean; - less(obj: MapIterator): boolean; - hash(): number; - swap(obj: MapIterator): void; - } + function hash(val: number): number; /** - *

A reverse-iterator of {@link MapContainer map container}.

+ *

Default hash function for string.

+ * + *

Unary function that defines the default hash function used by the standard library.

+ * + *

The functional call returns a hash value of its argument: A hash value is a value that depends solely on + * its argument, returning always the same value for the same argument (for a given execution of a program). The + * value returned shall have a small likelihood of being the same as the one returned for a different argument. + *

+ * + * @param str A string to be hashed. + * + * @return Returns a hash value for its argument, as a value of type number. The number is an unsigned integer. + */ + function hash(str: string): number; + /** + *

Default hash function for Object.

+ * + *

Unary function that defines the default hash function used by the standard library.

+ * + *

The functional call returns a hash value of its argument: A hash value is a value that depends solely on + * its argument, returning always the same value for the same argument (for a given execution of a program). The + * value returned shall have a small likelihood of being the same as the one returned for a different argument. + *

+ * + *

The default {@link hash} function of Object returns a value returned from {@link hash hash(number)} with + * an unique id of each Object. If you want to specify {@link hash} function of a specific class, then + * define a member function public hash(): number in the class.

+ * + * @param obj Object to be hashed. + * + * @return Returns a hash value for its argument, as a value of type number. The number is an unsigned integer. + */ + function hash(obj: Object): number; + /** + *

Exchange contents of {@link IContainers containers}.

+ * + *

The contents of container left are exchanged with those of right. Both container objects must have + * same type of elements (same template parameters), although sizes may differ.

+ * + *

After the call to this member function, the elements in left are those which were in right before + * the call, and the elements of right are those which were in left. All iterators, references and + * pointers remain valid for the swapped objects.

+ * + *

This is an overload of the generic algorithm swap that improves its performance by mutually transferring + * ownership over their assets to the other container (i.e., the containers exchange references to their data, without + * actually performing any element copy or movement): It behaves as if left. + * {@link IContainer.swap swap}(right) was called.

+ * + * @param left A {@link IContainer container} to swap its contents. + * @param right A {@link IContainer container} to swap its contents. + */ + function swap(left: base.IContainer, right: base.IContainer): void; + /** + *

Exchange contents of queues.

+ * + *

Exchanges the contents of left and right.

+ * + * @param left A {@link Queue} container of the same type. Size may differ. + * @param right A {@link Queue} container of the same type. Size may differ. + */ + function swap(left: Queue, right: Queue): void; + /** + *

Exchange contents of {@link PriorityQueue PriorityQueues}.

+ * + *

Exchanges the contents of left and right.

+ * + * @param left A {@link PriorityQueue} container of the same type. Size may differ. + * @param right A {@link PriorityQueue} container of the same type. Size may differ. + */ + function swap(left: PriorityQueue, right: PriorityQueue): void; + /** + *

Exchange contents of {@link Stack Stacks}.

+ * + *

Exchanges the contents of left and right.

+ * + * @param left A {@link Stack} container of the same type. Size may differ. + * @param right A {@link Stack} container of the same type. Size may differ. + */ + function swap(left: Stack, right: Stack): void; + /** + *

Exchanges the contents of two {@link UniqueMap unique maps}.

+ * + *

The contents of container left are exchanged with those of right. Both container objects must + * be of the same type (same template parameters), although sizes may differ.

+ * + *

After the call to this member function, the elements in left are those which were in right + * before the call, and the elements of right are those which were in left. All iterators, references + * and pointers remain valid for the swapped objects.

+ * + *

This is an overload of the generic algorithm swap that improves its performance by mutually transferring + * ownership over their assets to the other container (i.e., the containers exchange references to their data, + * without actually performing any element copy or movement): It behaves as if + * left.{@link UniqueMap.swap swap}(right) was called.

+ * + * @param left An {@link UniqueMap unique map} to swap its conents. + * @param right An {@link UniqueMap unique map} to swap its conents. + */ + function swap(left: base.UniqueMap, right: base.UniqueMap): void; + /** + *

Exchanges the contents of two {@link MultiMap multi maps}.

* - *

- *

+ *

The contents of container left are exchanged with those of right. Both container objects must + * be of the same type (same template parameters), although sizes may differ.

* - * @author Jeongho Nam + *

After the call to this member function, the elements in left are those which were in right + * before the call, and the elements of right are those which were in left. All iterators, references + * and pointers remain valid for the swapped objects.

+ * + *

This is an overload of the generic algorithm swap that improves its performance by mutually transferring + * ownership over their assets to the other container (i.e., the containers exchange references to their data, + * without actually performing any element copy or movement): It behaves as if + * left.{@link MultiMap.swap swap}(right) was called.

+ * + * @param left A {@link MultiMap multi map} to swap its conents. + * @param right A {@link MultiMap multi map} to swap its conents. */ - class MapReverseIterator extends ReverseIterator, MapIterator, MapReverseIterator> { - /** - * Construct from base iterator. - * - * @param base A reference of the base iterator, which iterates in the opposite direction. - */ - constructor(base: MapIterator); - /** - * @hidden - */ - protected create_neighbor(base: MapIterator): MapReverseIterator; - /** - * Get first, key element. - */ - readonly first: Key; - /** - * Get second, value element. - */ - /** - * Set second value. - */ - second: T; - } + function swap(left: base.MultiMap, right: base.MultiMap): void; } -declare namespace std.base { +declare namespace std { /** - *

An abstract multi-map.

+ *

Bind function arguments.

* - *

{@link MultiMap MultiMaps} are associative containers that store elements formed by a combination of a - * key value (Key) and a mapped value (T), and which allows for fast retrieval of - * individual elements based on their keys.

+ *

Returns a function object based on fn, but with its arguments bound to args.

* - *

In a {@link MapContainer}, the key values are generally used to identify the elements, while the - * mapped values store the content associated to this key. The types of key and - * mapped value may differ, and are grouped together in member type value_type, which is a - * {@link Pair} type combining both:

+ *

Each argument may either be bound to a value or be a {@link placeholders placeholder}:

+ *
    + *
  • If bound to a value, calling the returned function object will always use that value as argument.
  • + *
  • + * If a {@link placeholders placeholder}, calling the returned function object forwards an argument passed to the + * call (the one whose order number is specified by the placeholder). + *
  • + *
* - *

typedef pair value_type;

+ *

Calling the returned object returns the same type as fn.

* - *

{@link UniqueMap} stores elements, keeps sequence and enables indexing by inserting elements into a - * {@link List} and registering {@link ListIterator iterators} of the {@link data_ list container} to an index - * table like {@link RBTree tree} or {@link HashBuckets hash-table}.

+ * @param fn A function object, pointer to function or pointer to member. + * @param args List of arguments to bind: either values, or {@link placeholders}. * - *

- *

+ * @return A function object that, when called, calls fn with its arguments bound to args. If fn is + * a pointer to member, the first argument expected by the returned function is an object of the class fn + * is a member. + */ + function bind(fn: (...args: any[]) => Ret, ...args: any[]): (...args: any[]) => Ret; + /** + *

Bind function arguments.

* - *

Container properties

- *
- *
Associative
- *
- * Elements in associative containers are referenced by their key and not by their absolute position - * in the container. - *
+ *

Returns a function object based on fn, but with its arguments bound to args.

* - *
Map
- *
- * Each element associates a key to a mapped value: - * Keys are meant to identify the elements whose main content is the mapped value. - *
+ *

Each argument may either be bound to a value or be a {@link placeholders placeholder}:

+ *
    + *
  • If bound to a value, calling the returned function object will always use that value as argument.
  • + *
  • + * If a {@link placeholders placeholder}, calling the returned function object forwards an argument passed to the + * call (the one whose order number is specified by the placeholder). + *
  • + *
* - *
Multiple equivalent keys
- *
Multiple elements in the container can have equivalent keys.
- *
+ *

Calling the returned object returns the same type as fn.

* - * @param Type of the keys. Each element in a map is identified by its key value. - * @param Type of the mapped value. Each element in a map stores some data as its mapped value. + * @param fn A function object, pointer to function or pointer to member. + * @param thisArg This argument, owner object of the member method fn. + * @param args List of arguments to bind: either values, or {@link placeholders}. * - * @author Jeongho Nam + * @return A function object that, when called, calls fn with its arguments bound to args. If fn is + * a pointer to member, the first argument expected by the returned function is an object of the class fn + * is a member. */ - abstract class MultiMap extends MapContainer { - /** - * Construct and insert element. - * - * Inserts a new element in the {@link MultiMap}. This new element is constructed in place using args - * as the arguments for the element's constructor. - * - * This effectively increases the container {@link size} by one. - * - * A similar member function exists, {@link insert}, which either copies or moves existing objects into the - * container. - * - * @param key The key used both to look up and to insert if not found. - * @param value Value, the item. - * - * @return An {@link MapIterator iterator} to the newly inserted element. - */ - emplace(key: Key, value: T): MapIterator; - /** - * Construct and insert element. - * - * Inserts a new element in the {@link MultiMap}. This new element is constructed in place using args - * as the arguments for the element's constructor. - * - * This effectively increases the container {@link size} by one. - * - * A similar member function exists, {@link insert}, which either copies or moves existing objects into the - * container. - * - * @param pair A single argument of a {@link Pair} type with a value for the *key* as - * {@link Pair.first first} member, and a *value* for the mapped value as - * {@link Pair.second second}. - * @return An {@link MapIterator iterator} to the newly inserted element. - */ - emplace(pair: Pair): MapIterator; - /** - *

Insert elements.

- * - *

Extends the container by inserting new elements, effectively increasing the container {@link size} by - * the number of elements inserted.

- * - * @param pair A single argument of a {@link Pair} type with a value for the *key* as - * {@link Pair.first first} member, and a *value* for the mapped value as - * {@link Pair.second second}. - * - * @return An iterator pointing to the newly inserted element. - */ - insert(pair: Pair): MapIterator; - /** - *

Insert elements.

- * - *

Extends the container by inserting new elements, effectively increasing the container {@link size} by - * the number of elements inserted.

- * - * @param tuple Tuple represensts the {@link Pair} to be inserted as an element. - * - * @return An iterator pointing to the newly inserted element. - */ - insert(tuple: [L, U]): MapIterator; - /** - * @inheritdoc - */ - insert(hint: MapIterator, pair: Pair): MapIterator; - /** - * @inheritdoc - */ - insert(hint: MapReverseIterator, pair: Pair): MapReverseIterator; - /** - * @inheritdoc - */ - insert(hint: MapIterator, tuple: [L, U]): MapIterator; - /** - * @inheritdoc - */ - insert(hint: MapReverseIterator, tuple: [L, U]): MapReverseIterator; - /** - * @inheritdoc - */ - insert>>(first: InputIterator, last: InputIterator): void; + function bind(fn: (...args: any[]) => Ret, thisArg: T, ...args: any[]): (...args: any[]) => Ret; +} +/** + *

Bind argument placeholders.

+ * + *

This namespace declares an unspecified number of objects: _1, _2, _3, ..., which are + * used to specify placeholders in calls to function {@link std.bind}.

+ * + *

When the function object returned by bind is called, an argument with placeholder {@link _1} is replaced by the + * first argument in the call, {@link _2} is replaced by the second argument in the call, and so on... For example:

+ * + * + * let vec: Vector = new Vector(); + * + * let bind = std.bind(Vector.insert, _1, vec.end(), _2, _3); + * bind.apply(vec, 5, 1); // vec.insert(vec.end(), 5, 1); + * // [1, 1, 1, 1, 1] + * + * + *

When a call to {@link bind} is used as a subexpression in another call to bind, the {@link placeholders} + * are relative to the outermost {@link bind} expression.

+ * + * @reference http://www.cplusplus.com/reference/functional/placeholders/ + * @author Jeongho Nam + */ +declare namespace std.placeholders { + /** + * @hidden + */ + class PlaceHolder { + private index_; + constructor(index: number); + index: number; } + /** + * Replaced by the first argument in the function call. + */ + const _1: PlaceHolder; + /** + * Replaced by the second argument in the function call. + */ + const _2: PlaceHolder; + /** + * Replaced by the third argument in the function call. + */ + const _3: PlaceHolder; + const _4: PlaceHolder; + const _5: PlaceHolder; + const _6: PlaceHolder; + const _7: PlaceHolder; + const _8: PlaceHolder; + const _9: PlaceHolder; + const _10: PlaceHolder; + const _11: PlaceHolder; + const _12: PlaceHolder; + const _13: PlaceHolder; + const _14: PlaceHolder; + const _15: PlaceHolder; + const _16: PlaceHolder; + const _17: PlaceHolder; + const _18: PlaceHolder; + const _19: PlaceHolder; + const _20: PlaceHolder; } declare namespace std.base { /** - *

An abstract set.

+ *

An abstract map.

+ * + *

{@link MapContainer MapContainers} are associative containers that store elements formed by a combination + * of a key value (Key) and a mapped value (T), and which allows for fast retrieval + * of individual elements based on their keys.

* - *

{@link SetContainer SetContainers} are containers that store elements allowing fast retrieval of - * individual elements based on their value.

+ *

In a {@link MapContainer}, the key values are generally used to identify the elements, while the + * mapped values store the content associated to this key. The types of key and + * mapped value may differ, and are grouped together in member type value_type, which is a + * {@link Pair} type combining both:

* - *

In an {@link SetContainer}, the value of an element is at the same time its key, used to - * identify it. Keys are immutable, therefore, the elements in an {@link SetContainer} cannot be - * modified once in the container - they can be inserted and removed, though.

+ *

typedef pair value_type;

* - *

{@link SetContainer} stores elements, keeps sequence and enables indexing by inserting elements into a + *

{@link MapContainer} stores elements, keeps sequence and enables indexing by inserting elements into a * {@link List} and registering {@link ListIterator iterators} of the {@link data_ list container} to an index * table like {@link RBTree tree} or {@link HashBuckets hash-table}.

* - *

- *

+ *

+ *

* *

Container properties

*
*
Associative
*
- * Elements in associative containers are referenced by their key and not by their absolute - * position in the container. + * Elements in associative containers are referenced by their key and not by their absolute position + * in the container. *
* - *
Set
- *
The value of an element is also the key used to identify it.
+ *
Map
+ *
+ * Each element associates a key to a mapped value: + * Keys are meant to identify the elements whose main content is the mapped value. + *
*
* - * @param Type of the elements. Each element in a {@link SetContainer} container is also identified - * by this value (each value is itself also the element's key). + * @param Type of the keys. Each element in a map is identified by its key value. + * @param Type of the mapped value. Each element in a map stores some data as its mapped value. * * @author Jeongho Nam */ - abstract class SetContainer extends Container { + abstract class MapContainer extends Container> { /** *

{@link List} storing elements.

* - *

Storing elements and keeping those sequence of the {@link SetContainer} are implemented by + *

Storing elements and keeping those sequence of the {@link MapContainer} are implemented by * {@link data_ this list container}. Implementing index-table is also related with {@link data_ this list} - * by storing {@link ListIterator iterators} ({@link SetIterator} references {@link ListIterator}) who are + * by storing {@link ListIterator iterators} ({@link MapIterator} references {@link ListIterator}) who are * created from {@link data_ here}.

*/ private data_; @@ -5228,7 +4485,7 @@ declare namespace std.base { /** * @inheritdoc */ - assign>(begin: Iterator, end: Iterator): void; + assign>>(first: InputIterator, last: InputIterator): void; /** * @inheritdoc */ @@ -5236,157 +4493,351 @@ declare namespace std.base { /** *

Get iterator to element.

* - *

Searches the container for an element with key as value and returns an iterator to it if found, - * otherwise it returns an iterator to {@link end end()} (the element past the end of the container).

+ *

Searches the container for an element with a identifier equivalent to key and returns an + * iterator to it if found, otherwise it returns an iterator to {@link end end()}.

* - *

Another member function, {@link count count()}, can be used to just check whether a particular element - * exists.

+ *

Two keys are considered equivalent if the container's comparison object returns false reflexively + * (i.e., no matter the order in which the elements are passed as arguments).

* - * @param key Key to be searched for. + *

Another member functions, {@link has has()} and {@link count count()}, can be used to just check + * whether a particular key exists.

* - * @return An iterator to the element, if the specified value is found, or {@link end end()} if it is not - * found in the + * @param key Key to be searched for + * @return An iterator to the element, if an element with specified key is found, or + * {@link end end()} otherwise. */ - abstract find(val: T): SetIterator; + abstract find(key: Key): MapIterator; /** - * @inheritdoc + *

Return iterator to beginning.

+ * + *

Returns an iterator referring the first element in the

+ * + *

Note

+ *

If the container is {@link empty}, the returned iterator is same with {@link end end()}.

+ * + * @return An iterator to the first element in the The iterator containes the first element's value. */ - begin(): SetIterator; + begin(): MapIterator; /** - * @inheritdoc + *

Return iterator to end.

+ *

Returns an iterator referring to the past-the-end element in the

+ * + *

The past-the-end element is the theoretical element that would follow the last element in the + * It does not point to any element, and thus shall not be dereferenced.

+ * + *

Because the ranges used by functions of the container do not include the element reference by their + * closing iterator, this function is often used in combination with {@link MapContainer}.{@link begin} to + * specify a range including all the elements in the

+ * + *

Note

+ *

Returned iterator from {@link MapContainer}.{@link end} does not refer any element. Trying to accessing + * element by the iterator will cause throwing exception ({@link OutOfRange}).

+ * + *

If the container is {@link empty}, this function returns the same as {@link begin}.

+ * + * @return An iterator to the end element in the */ - end(): SetIterator; + end(): MapIterator; /** - * @inheritdoc + *

Return {@link MapReverseIterator reverse iterator} to reverse beginning.

+ * + *

Returns a {@link MapReverseIterator reverse iterator} pointing to the last element in the container + * (i.e., its reverse beginning).

+ * + * {@link MapReverseIterator Reverse iterators} iterate backwards: increasing them moves them towards the + * beginning of the container.

+ * + *

{@link rbegin} points to the element preceding the one that would be pointed to by member {@link end}. + *

+ * + * @return A {@link MapReverseIterator reverse iterator} to the reverse beginning of the sequence + * */ - rbegin(): SetReverseIterator; + rbegin(): MapReverseIterator; /** - * @inheritdoc + *

Return {@link MapReverseIterator reverse iterator} to reverse end.

+ * + *

Returns a {@link MapReverseIterator reverse iterator} pointing to the theoretical element right before + * the first element in the {@link MapContainer map container} (which is considered its reverse end). + *

+ * + *

The range between {@link MapContainer}.{@link rbegin} and {@link MapContainer}.{@link rend} contains + * all the elements of the container (in reverse order).

+ * + * @return A {@link MapReverseIterator reverse iterator} to the reverse end of the sequence */ - rend(): SetReverseIterator; + rend(): MapReverseIterator; /** *

Whether have the item or not.

* - *

Indicates whether a set has an item having the specified identifier.

+ *

Indicates whether a map has an item having the specified identifier.

* * @param key Key value of the element whose mapped value is accessed. * - * @return Whether the set has an item having the specified identifier. + * @return Whether the map has an item having the specified identifier. */ - has(val: T): boolean; + has(key: Key): boolean; /** *

Count elements with a specific key.

* - *

Searches the container for elements with a value of k and returns the number of elements found.

+ *

Searches the container for elements whose key is key and returns the number of elements found.

* - * @param key Value of the elements to be counted. + * @param key Key value to be searched for. * * @return The number of elements in the container with a key. */ - abstract count(val: T): number; + abstract count(key: Key): number; /** - * @inheritdoc + * Return the number of elements in the map. */ size(): number; /** * @inheritdoc */ - push(...args: U[]): number; + push(...args: Pair[]): number; /** - *

Insert an element with hint.

+ * @inheritdoc + */ + push(...args: [Key, T][]): number; + /** + * Construct and insert element with hint * - *

Extends the container by inserting new elements, effectively increasing the container size by the - * number of elements inserted.

+ * Inserts a new element in the {@link MapContainer map container}. This new element is constructed in + * place using *args* as the arguments for the element's constructor. *hint* points to a location in the + * container suggested as a hint on where to start the search for its insertion point (the container may or + * may not use this suggestion to optimize the insertion operation). + * + * A similar member function exists, {@link insert}, which either copies or moves an existing object into + * the container, and may also take a position *hint*. * * @param hint Hint for the position where the element can be inserted. - * @param val Value to be inserted as an element. + * @param key The key used both to look up and to insert if not found. + * @param value Value, the item. * - * @return An iterator pointing to either the newly inserted element or to the element that already had its - * same value in the {@link SetContainer}. + * @return An iterator pointing to either the newly inserted element or to the element that already had an + * equivalent key in the {@link MapContainer}. + */ + emplace_hint(hint: MapIterator, key: Key, val: T): MapIterator; + /** + * Construct and insert element with hint + * + * Inserts a new element in the {@link MapContainer map container}. This new element is constructed in + * place using *args* as the arguments for the element's constructor. *hint* points to a location in the + * container suggested as a hint on where to start the search for its insertion point (the container may or + * may not use this suggestion to optimize the insertion operation). + * + * A similar member function exists, {@link insert}, which either copies or moves an existing object into + * the container, and may also take a position *hint*. + * + * @param hint Hint for the position where the element can be inserted. + * @param key The key used both to look up and to insert if not found. + * @param value Value, the item. + * + * @return An {@link MapIterator iterator} pointing to either the newly inserted element or to the element + * that already had an equivalent key in the {@link MapContainer}. + */ + emplace_hint(hint: MapReverseIterator, key: Key, val: T): MapReverseIterator; + /** + * Construct and insert element with hint + * + * Inserts a new element in the {@link MapContainer map container}. This new element is constructed in + * place using *args* as the arguments for the element's constructor. *hint* points to a location in the + * container suggested as a hint on where to start the search for its insertion point (the container may or + * may not use this suggestion to optimize the insertion operation). + * + * A similar member function exists, {@link insert}, which either copies or moves an existing object into + * the container, and may also take a position *hint*. + * + * @param hint Hint for the position where the element can be inserted. + * @param pair A single argument of a {@link Pair} type with a value for the *key* as + * {@link Pair.first first} member, and a *value* for the mapped value as + * {@link Pair.second second}. + * + * @return An iterator pointing to either the newly inserted element or to the element that already had an + * equivalent key in the {@link MapContainer}. + */ + emplace_hint(hint: MapIterator, pair: Pair): MapIterator; + /** + * Construct and insert element with hint + * + * Inserts a new element in the {@link MapContainer map container}. This new element is constructed in + * place using *args* as the arguments for the element's constructor. *hint* points to a location in the + * container suggested as a hint on where to start the search for its insertion point (the container may or + * may not use this suggestion to optimize the insertion operation). + * + * A similar member function exists, {@link insert}, which either copies or moves an existing object into + * the container, and may also take a position *hint*. + * + * @param hint Hint for the position where the element can be inserted. + * @param pair A single argument of a {@link Pair} type with a value for the *key* as + * {@link Pair.first first} member, and a *value* for the mapped value as + * {@link Pair.second second}. + * + * @return An {@link MapIterator iterator} pointing to either the newly inserted element or to the element + * that already had an equivalent key in the {@link MapContainer}. + */ + emplace_hint(hint: MapReverseIterator, pair: Pair): MapReverseIterator; + /** + *

Insert an element.

+ * + *

Extends the container by inserting a new element, effectively increasing the container {@link size} + * by the number of element inserted (zero or one).

+ * + * @param hint Hint for the position where the element can be inserted. + * @param pair A single argument of a {@link Pair} type with a value for the *key* as + * {@link Pair.first first} member, and a *value* for the mapped value as + * {@link Pair.second second}. + * + * @return An iterator pointing to either the newly inserted element or to the element that already had an + * equivalent key in the {@link MapContainer}. + */ + insert(hint: MapIterator, pair: Pair): MapIterator; + /** + *

Insert an element.

+ * + *

Extends the container by inserting a new element, effectively increasing the container {@link size} + * by the number of element inserted (zero or one).

+ * + * @param hint Hint for the position where the element can be inserted. + * @param pair A single argument of a {@link Pair} type with a value for the *key* as + * {@link Pair.first first} member, and a *value* for the mapped value as + * {@link Pair.second second}. + * + * @return An iterator pointing to either the newly inserted element or to the element that already had an + * equivalent key in the {@link MapContainer}. + */ + insert(hint: MapReverseIterator, pair: Pair): MapReverseIterator; + /** + *

Insert an element.

+ * + *

Extends the container by inserting new elements, effectively increasing the container {@link size} + * by the number of elements inserted.

+ * + * @param hint Hint for the position where the element can be inserted. + * @param tuple Tuple represensts the {@link Pair} to be inserted as an element. + * + * @return An iterator pointing to either the newly inserted element or to the element that already had an + * equivalent key in the {@link MapContainer}. */ - insert(hint: SetIterator, val: T): SetIterator; + insert(hint: MapIterator, tuple: [L, U]): MapIterator; /** - *

Insert an element with hint.

+ *

Insert an element.

* - *

Extends the container by inserting new elements, effectively increasing the container size by the - * number of elements inserted.

+ *

Extends the container by inserting new elements, effectively increasing the container {@link size} + * by the number of elements inserted.

* * @param hint Hint for the position where the element can be inserted. - * @param val Value to be inserted as an element. + * @param tuple Tuple represensts the {@link Pair} to be inserted as an element. * - * @return An iterator pointing to either the newly inserted element or to the element that already had its - * same value in the {@link SetContainer}. + * @return An iterator pointing to either the newly inserted element or to the element that already had an + * equivalent key in the {@link MapContainer}. */ - insert(hint: SetReverseIterator, val: T): SetReverseIterator; + insert(hint: MapReverseIterator, tuple: [L, U]): MapReverseIterator; /** - *

Insert elements with a range of a

+ *

Insert elements from range iterators.

* - *

Extends the container by inserting new elements, effectively increasing the container size by the - * number of elements inserted.

+ *

Extends the container by inserting new elements, effectively increasing the container {@link size} by + * the number of elements inserted.

* - * @param begin An iterator specifying range of the begining element. - * @param end An iterator specifying range of the ending element. + * @param begin Input iterator specifying initial position of a range of elements. + * @param end Input iterator specifying final position of a range of elements. + * Notice that the range includes all the elements between begin and end, + * including the element pointed by begin but not the one pointed by end. */ - insert>(begin: InputIterator, end: InputIterator): void; + insert>>(first: InputIterator, last: InputIterator): void; /** * @hidden */ - protected abstract _Insert_by_val(val: T): any; + protected abstract _Insert_by_pair(pair: Pair): any; /** * @hidden */ - protected abstract _Insert_by_hint(hint: SetIterator, val: T): SetIterator; + private insert_by_tuple(tuple); /** * @hidden */ - protected abstract _Insert_by_range>(begin: InputIterator, end: InputIterator): void; + protected abstract _Insert_by_hint(hint: MapIterator, pair: Pair): MapIterator; /** - *

Erase an element.

- *

Removes from the set container the elements whose value is key.

+ * @hidden + */ + private insert_by_hint_with_tuple(hint, tuple); + /** + * @hidden + */ + protected abstract _Insert_by_range>>(first: InputIterator, last: InputIterator): void; + /** + *

Erase an elemet by key.

* - *

This effectively reduces the container size by the number of elements removed.

+ *

Removes from the {@link MapContainer map container} a single element.

* - * @param key Value of the elements to be erased. + *

This effectively reduces the container {@link size} by the number of element removed (zero or one), + * which are destroyed.

* - * @return Number of elements erased. + * @param key Key of the element to be removed from the {@link MapContainer}. */ - erase(val: T): number; + erase(key: Key): number; /** - * @inheritdoc + *

Erase an elemet by iterator.

+ * + *

Removes from the {@link MapContainer map container} a single element.

+ * + *

This effectively reduces the container {@link size} by the number of element removed (zero or one), + * which are destroyed.

+ * + * @param it Iterator specifying position winthin the {@link MapContainer map contaier} to be removed. */ - erase(it: SetIterator): SetIterator; + erase(it: MapIterator): MapIterator; /** - *

Erase elements.

- *

Removes from the set container a range of elements..

+ *

Erase elements by range iterators.

* - *

This effectively reduces the container size by the number of elements removed.

+ *

Removes from the {@link MapContainer map container} a range of elements.

* - * @param begin An iterator specifying a range of beginning to erase. - * @param end An iterator specifying a range of end to erase. + *

This effectively reduces the container {@link size} by the number of elements removed, which are + * destroyed.

+ * + * @param begin An iterator specifying initial position of a range within {@link MApContainer map container} + * to be removed. + * @param end An iterator specifying initial position of a range within {@link MApContainer map container} + * to be removed. + * Notice that the range includes all the elements between begin and end, + * including the element pointed by begin but not the one pointed by end. */ - erase(begin: SetIterator, end: SetIterator): SetIterator; + erase(begin: MapIterator, end: MapIterator): MapIterator; /** - * @inheritdoc + *

Erase an elemet by iterator.

+ * + *

Removes from the {@link MapContainer map container} a single element.

+ * + *

This effectively reduces the container {@link size} by the number of element removed (zero or one), + * which are destroyed.

+ * + * @param it Iterator specifying position winthin the {@link MapContainer map contaier} to be removed. */ - erase(it: SetReverseIterator): SetReverseIterator; + erase(it: MapReverseIterator): MapReverseIterator; /** - *

Erase elements.

- *

Removes from the set container a range of elements..

+ *

Erase elements by range iterators.

* - *

This effectively reduces the container size by the number of elements removed.

+ *

Removes from the {@link MapContainer map container} a range of elements.

* - * @param begin An iterator specifying a range of beginning to erase. - * @param end An iterator specifying a range of end to erase. + *

This effectively reduces the container {@link size} by the number of elements removed, which are + * destroyed.

+ * + * @param begin An iterator specifying initial position of a range within {@link MApContainer map container} + * to be removed. + * @param end An iterator specifying initial position of a range within {@link MApContainer map container} + * to be removed. + * Notice that the range includes all the elements between begin and end, + * including the element pointed by begin but not the one pointed by end. */ - erase(begin: SetReverseIterator, end: SetReverseIterator): SetReverseIterator; + erase(begin: MapReverseIterator, end: MapReverseIterator): MapReverseIterator; /** * @hidden */ - private erase_by_iterator(first, last?); + private erase_by_key(key); /** * @hidden */ - private erase_by_val(val); + private erase_by_iterator(first, last?); /** * @hidden */ @@ -5395,851 +4846,801 @@ declare namespace std.base { *

Abstract method handling insertions for indexing.

* *

This method, {@link _Handle_insert} is designed to register the first to last to somewhere storing - * those {@link SetIterator iterators} for indexing, fast accessment and retrievalance.

+ * those {@link MapIterator iterators} for indexing, fast accessment and retrievalance.

* *

When {@link insert} is called, new elements will be inserted into the {@link data_ list container} and new - * {@link SetIterator iterators} first to last, pointing the inserted elements, will be created and the + * {@link MapIterator iterators} first to last, pointing the inserted elements, will be created and the * newly created iterators first to last will be shifted into this method {@link _Handle_insert} after the * insertions.

* - *

If the derived one is {@link RBTree tree-based} like {@link TreeSet}, the {@link SetIterator iterators} + *

If the derived one is {@link RBTree tree-based} like {@link TreeSet}, the {@link MapIterator iterators} * will be registered into the {@link TreeSet.tree_ tree} as a {@link XTreeNode tree node item}. Else if the * derived one is {@link HashBuckets hash-based} like {@link HashSet}, the first to last will be * registered into the {@link HashSet.hash_buckets_ hash bucket}.

* - * @param first An {@link SetIterator} to the initial position in a sequence. - * @param last An {@link SetIterator} to the final position in a sequence. The range used is + * @param first An {@link MapIterator} to the initial position in a sequence. + * @param last An {@link MapIterator} to the final position in a sequence. The range used is * [first, last), which contains all the elements between first and last, * including the element pointed by first but not the element pointed by last. */ - protected abstract _Handle_insert(first: SetIterator, last: SetIterator): void; + protected abstract _Handle_insert(first: MapIterator, last: MapIterator): void; /** *

Abstract method handling deletions for indexing.

* *

This method, {@link _Handle_erase} is designed to unregister the first to last to somewhere storing - * those {@link SetIterator iterators} for indexing, fast accessment and retrievalance.

+ * those {@link MapIterator iterators} for indexing, fast accessment and retrievalance.

* - *

When {@link erase} is called with first to last, {@link SetIterator iterators} positioning somewhere + *

When {@link erase} is called with first to last, {@link MapIterator iterators} positioning somewhere * place to be deleted, is memorized and shifted to this method {@link _Handle_erase} after the deletion process is * terminated.

* - *

If the derived one is {@link RBTree tree-based} like {@link TreeSet}, the {@link SetIterator iterators} + *

If the derived one is {@link RBTree tree-based} like {@link TreeSet}, the {@link MapIterator iterators} * will be unregistered from the {@link TreeSet.tree_ tree} as a {@link XTreeNode tree node item}. Else if the * derived one is {@link HashBuckets hash-based} like {@link HashSet}, the first to last will be * unregistered from the {@link HashSet.hash_buckets_ hash bucket}.

* - * @param first An {@link SetIterator} to the initial position in a sequence. - * @param last An {@link SetIterator} to the final position in a sequence. The range used is + * @param first An {@link MapIterator} to the initial position in a sequence. + * @param last An {@link MapIterator} to the final position in a sequence. The range used is * [first, last), which contains all the elements between first and last, * including the element pointed by first but not the element pointed by last. */ - protected abstract _Handle_erase(first: SetIterator, last: SetIterator): void; + protected abstract _Handle_erase(first: MapIterator, last: MapIterator): void; /** * @hidden */ - protected _Swap(obj: SetContainer): void; + protected _Swap(obj: MapContainer): void; } } declare namespace std { /** - *

An iterator of a Set.

+ *

An iterator of {@link MapContainer map container}.

* - *

- *

+ *

+ *

* * @author Jeongho Nam */ - class SetIterator extends Iterator implements IComparable> { + class MapIterator extends Iterator> implements IComparable> { + /** + * A {@link ListIterator} pointing {@link Pair} of key and value. + */ private list_iterator_; /** - *

Construct from source and index number.

- * - *

Note

- *

Do not create iterator directly.

- *

Use begin(), find() or end() in Map instead.

+ * Construct from the {@link MapContainer source map} and {@link ListIterator list iterator}. * - * @param map The source Set to reference. - * @param index Sequence number of the element in the source Set. + * @param source The source {@link MapContainer}. + * @param list_iterator A {@link ListIterator} pointing {@link Pair} of key and value. */ - constructor(source: base.SetContainer, it: ListIterator); + constructor(source: base.MapContainer, list_iterator: ListIterator>); /** - * @inheritdoc + * Get iterator to previous element. */ - prev(): SetIterator; + prev(): MapIterator; /** - * @inheritdoc + * Get iterator to next element. */ - next(): SetIterator; + next(): MapIterator; /** - * @inheritdoc + * Advances the Iterator by n element positions. + * + * @param step Number of element positions to advance. + * @return An advanced Iterator. */ - advance(size: number): SetIterator; + advance(step: number): MapIterator; /** * @hidden */ - private readonly set; - get_list_iterator(): ListIterator; - /** - * @inheritdoc - */ - readonly value: T; - /** - * @inheritdoc - */ - equal_to(obj: SetIterator): boolean; + private map; /** - * @inheritdoc + * Get ListIterator. */ - less(obj: SetIterator): boolean; + get_list_iterator(): ListIterator>; /** * @inheritdoc */ - hash(): number; + value: Pair; /** - * @inheritdoc + * Get first, key element. */ - swap(obj: SetIterator): void; - } - /** - *

A reverse-iterator of Set.

- * - *

- *

- * - * @param Type of the elements. - * - * @author Jeongho Nam - */ - class SetReverseIterator extends ReverseIterator, SetReverseIterator> { + first: Key; /** - * Construct from base iterator. - * - * @param base A reference of the base iterator, which iterates in the opposite direction. + * Get second, value element. */ - constructor(base: SetIterator); /** - * @hidden - */ - protected create_neighbor(base: SetIterator): SetReverseIterator; - } -} -declare namespace std.base { - /** - *

An abstract set.

- * - *

{@link SetContainer SetContainers} are containers that store elements allowing fast retrieval of - * individual elements based on their value.

- * - *

In an {@link SetContainer}, the value of an element is at the same time its key, used to - * identify it. Keys are immutable, therefore, the elements in an {@link SetContainer} cannot be - * modified once in the container - they can be inserted and removed, though.

- * - *

{@link SetContainer} stores elements, keeps sequence and enables indexing by inserting elements into a - * {@link List} and registering {@link ListIterator iterators} of the {@link data_ list container} to an index - * table like {@link RBTree tree} or {@link HashBuckets hash-table}.

- * - *

- *

- * - *

Container properties

- *
- *
Associative
- *
- * Elements in associative containers are referenced by their key and not by their absolute - * position in the container. - *
- * - *
Set
- *
The value of an element is also the key used to identify it.
- * - *
Multiple equivalent keys
- *
Multiple elements in the container can have equivalent keys.
- *
+ * Set second value. + */ + second: T; + /** + *

Whether an iterator is equal with the iterator.

+ * + *

Compare two iterators and returns whether they are equal or not.

+ * + * @param obj An iterator to compare + * @return Indicates whether equal or not. + */ + equal_to(obj: MapIterator): boolean; + less(obj: MapIterator): boolean; + hash(): number; + swap(obj: MapIterator): void; + } + /** + *

A reverse-iterator of {@link MapContainer map container}.

* - * @param Type of the elements. Each element in a {@link SetContainer} container is also identified - * by this value (each value is itself also the element's key). + *

+ *

* * @author Jeongho Nam */ - abstract class MultiSet extends SetContainer { + class MapReverseIterator extends ReverseIterator, MapIterator, MapReverseIterator> { /** - *

Insert an element.

- * - *

Extends the container by inserting new elements, effectively increasing the container {@link size} by - * the number of elements inserted.

- * - * @param key Value to be inserted as an element. + * Construct from base iterator. * - * @return An iterator to the newly inserted element. + * @param base A reference of the base iterator, which iterates in the opposite direction. */ - insert(val: T): SetIterator; + constructor(base: MapIterator); /** - * @inheritdoc + * @hidden */ - insert(hint: SetIterator, val: T): SetIterator; + protected create_neighbor(base: MapIterator): MapReverseIterator; /** - * @inheritdoc + * Get first, key element. */ - insert(hint: SetReverseIterator, val: T): SetReverseIterator; + first: Key; /** - * @inheritdoc + * Get second, value element. */ - insert>(begin: InputIterator, end: InputIterator): void; + /** + * Set second value. + */ + second: T; } } declare namespace std.base { /** - *

Red-black Tree.

- * - *

A red-black tree is a kind of self-balancing - * binary search tree. Each node of the binary tree has an extra bit, and that bit is often interpreted as the - * color (red or black) of the node. These color bits - * are used to ensure the tree remains approximately balanced during insertions and deletions.

- * - *

Balance is preserved by painting each node of the tree with one of two colors (typically called - * 'red' and 'black') in a way that satisfies certain - * properties, which collectively constrain how unbalanced the tree can become in the worst case. When the tree - * is modified, the new tree is subsequently rearranged and repainted to restore the coloring properties. The - * properties are designed in such a way that this rearranging and recoloring can be performed efficiently.

- * - *

The balancing of the tree is not perfect but it is good enough to allow it to guarantee searching in - * O(log n) time, where n is the total number of elements in the tree. The insertion and deletion operations, - * along with the tree rearrangement and recoloring, are also performed in O(log n) time.

- * - *

Tracking the color of each node requires only 1 bit of information per node because there are only two - * colors. The tree does not contain any other data specific to its being a - * red-black tree so its memory footprint is almost - * identical to a classic (uncolored) binary search tree. In many cases the additional bit of information can - * be stored at no additional memory cost.

+ *

An abstract unique-map.

* - *

Properties

- *

In addition to the requirements imposed on a binary search tree the following must be satisfied by a - * red-black tree:

+ *

{@link UniqueMap UniqueMaps} are associative containers that store elements formed by a combination of a + * key value (Key) and a mapped value (T), and which allows for fast retrieval of + * individual elements based on their keys.

* - *
    - *
  1. A node is either red or black.
  2. - *
  3. - * The root is black. This rule is sometimes omitted. Since the root can - * always be changed from red to black, but not - * necessarily vice versa, this rule has little effect on analysis. - *
  4. - *
  5. All leaves (NIL; null) are black.
  6. - *
  7. - * If a node is red, then both its children are - * black. - *
  8. - *
  9. - * Every path from a given node to any of its descendant NIL nodes contains the same number of - * black nodes. Some definitions: the number of - * black nodes from the root to a node is the node's - * black depth; the uniform number of black - * nodes in all paths from root to the leaves is called the black-height of - * the red-black tree. - *
  10. - *
+ *

In a {@link MapContainer}, the key values are generally used to uniquely identify the elements, + * while the mapped values store the content associated to this key. The types of key and + * mapped value may differ, and are grouped together in member type value_type, which is a + * {@link Pair} type combining both:

* - *

+ *

typedef pair value_type;

* - *

These constraints enforce a critical property of red-black trees: the path from the root to the farthest - * leaf is no more than twice as long as the path from the root to the nearest leaf. The result is that the tree - * is roughly height-balanced. Since operations such as inserting, deleting, and finding values require - * worst-case time proportional to the height of the tree, this theoretical upper bound on the height allows - * red-black trees to be efficient in the worst case, unlike ordinary binary search trees.

+ *

{@link UniqueMap} stores elements, keeps sequence and enables indexing by inserting elements into a + * {@link List} and registering {@link ListIterator iterators} of the {@link data_ list container} to an index + * table like {@link RBTree tree} or {@link HashBuckets hash-table}.

* - *

To see why this is guaranteed, it suffices to consider the effect of properties 4 and 5 together. For a - * red-black tree T, let B be the number of black nodes in property 5. Let the - * shortest possible path from the root of T to any leaf consist of B black nodes. - * Longer possible paths may be constructed by inserting red nodes. However, property 4 - * makes it impossible to insert more than one consecutive red node. Therefore, - * ignoring any black NIL leaves, the longest possible path consists of 2*B nodes, - * alternating black and red (this is the worst case). - * Counting the black NIL leaves, the longest possible path consists of 2*B-1 - * nodes.

+ *

+ *

* - *

The shortest possible path has all black nodes, and the longest possible - * path alternates between red and black nodes. Since all - * maximal paths have the same number of black nodes, by property 5, this shows - * that no path is more than twice as long as any other path.

+ *

Container properties

+ *
+ *
Associative
+ *
+ * Elements in associative containers are referenced by their key and not by their absolute position + * in the container. + *
* - * @param Type of elements. + *
Map
+ *
+ * Each element associates a key to a mapped value: + * Keys are meant to identify the elements whose main content is the mapped value. + *
* - * @reference https://en.wikipedia.org/w/index.php?title=Red%E2%80%93black_tree - * @inventor Rudolf Bayer - * @author Migrated by Jeongho Nam - */ - abstract class XTree { - /** - * Root node. - */ - protected root_: XTreeNode; - /** - * Default Constructor. - */ - constructor(); - clear(): void; - /** - * Find a node from its contained value. - * - * @param val Value to find. - */ - find(val: T): XTreeNode; - /** - * Fetch maximum (the rightes?) node from one. - * - * @param node A node to fetch its maximum node. - * @return The maximum node. - */ - protected fetch_maximum(node: XTreeNode): XTreeNode; - abstract is_less(left: T, right: T): boolean; - abstract is_equal_to(left: T, right: T): boolean; - /** - *

Insert an element with a new node.

- * - *

Insertion begins by adding the node as any binary search tree insertion does and by coloring it - * red. Whereas in the binary search tree, we always add a leaf, in the red-black - * tree, leaves contain no information, so instead we add a red interior node, with - * two black leaves, in place of an existing - * black leaf.

- * - *

What happens next depends on the color of other nearby nodes. The term uncle node will be used to - * refer to the sibling of a node's parent, as in human family trees. Note that:

- * - *
    - *
  • property 3 (all leaves are black) always holds.
  • - *
  • - * property 4 (both children of every red node are - * black) is threatened only by adding a red - * node, repainting a black node red, or a - * rotation. - *
  • - *
  • - * property 5 (all paths from any given node to its leaf nodes contain the same number of - * black nodes) is threatened only by adding a - * black node, repainting a red node - * black (or vice versa), or a rotation. - *
  • - *
- * - *

Notes

- *
    - *
  1. - * The label N will be used to denote the current node (colored - * red). In the diagrams N carries a blue contour. At the - * beginning, this is the new node being inserted, but the entire procedure may also be applied - * recursively to other nodes (see case 3). {@link XTreeNode.parent P} will denote - * N's parent node, {@link XTreeNode.grand_parent G} will denote N's - * grandparent, and {@link XTreeNode.uncle U} will denote N's uncle. In between - * some cases, the roles and labels of the nodes are exchanged, but in each case, every label continues - * to represent the same node it represented at the beginning of the case. - *
  2. - *
  3. - * If a node in the right (target) half of a diagram carries a blue contour it will become the current - * node in the next iteration and there the other nodes will be newly assigned relative to it. Any - * color shown in the diagram is either assumed in its case or implied by those assumptions. - *
  4. - *
  5. - * A numbered triangle represents a subtree of unspecified depth. A black - * circle atop a triangle means that black-height of subtree is greater - * by one compared to subtree without this circle.
  6. - *
- * - *

There are several cases of red-black tree insertion to handle:

- * - *
    - *
  • N is the root node, i.e., first node of red-black tree.
  • - *
  • - * N's parent ({@link XTreeNode.parent P}) is black. - *
  • - *
  • - * N's parent ({@link XTreeNode.parent P}) and uncle - * ({@link XTreeNode.uncle U}) are red. - *
  • - *
  • - * N is added to right of left child of grandparent, or N is added to left - * of right child of grandparent ({@link XTreeNode.parent P} is red and - * {@link XTreeNode.uncle U} is black). - *
  • - *
  • - * N is added to left of left child of grandparent, or N is added to right - * of right child of grandparent ({@link XTreeNode.parent P} is red and - * {@link XTreeNode.uncle U} is black). - *
  • - *
- * - *

Note

- *

Note that inserting is actually in-place, since all the calls above use tail recursion.

- * - *

In the algorithm above, all cases are chained in order, except in insert case 3 where it can recurse - * to case 1 back to the grandparent node: this is the only case where an iterative implementation will - * effectively loop. Because the problem of repair is escalated to the next higher level but one, it takes - * maximally h⁄2 iterations to repair the tree (where h is the height of the tree). Because the probability - * for escalation decreases exponentially with each iteration the average insertion cost is constant.

- * - * @param val An element to insert. + *
Unique keys
+ *
No two elements in the container can have equivalent keys.
+ *
+ * + * @param Type of the keys. Each element in a map is uniquely identified by its key value. + * @param Type of the mapped value. Each element in a map stores some data as its mapped value. + * + * @author Jeongho Nam + */ + abstract class UniqueMap extends MapContainer { + /** + * @inheritdoc */ - insert(val: T): void; + count(key: Key): number; /** - *

N is the root node, i.e., first node of red-black tree.

+ *

Get an element

* - *

The current node N is at the {@link root_ root} of the tree.

+ *

Returns a reference to the mapped value of the element identified with key.

* - *

In this case, it is repainted black to satisfy property 2 (the root is - * black). Since this adds one black node to - * every path at once, property 5 (all paths from any given node to its leaf nodes contain the same number - * of black nodes) is not violated.

+ * @param key Key value of the element whose mapped value is accessed. * - * @param N A node to be inserted or swapped. + * @throw exception out of range + * + * @return A reference object of the mapped value (_Ty) */ - private insert_case1(N); + get(key: Key): T; /** - *

N's parent ({@link XTreeNode.parent P}) is black.

- * - *

The current node's parent {@link XTreeNode.parent P} is black, - * so property 4 (both children of every red node are - * black) is not invalidated.

+ *

Set an item as the specified identifier.

* - *

In this case, the tree is still valid. Property 5 (all paths from any given node to its leaf nodes - * contain the same number of black nodes) is not threatened, because the - * current node N has two black leaf children, but because - * N is red, the paths through each of its children have the same - * number of black nodes as the path through the leaf it replaced, which was - * black, and so this property remains satisfied.

+ *

If the identifier is already in map, change value of the identifier. If not, then insert the object + * with the identifier.

* - * @param N A node to be inserted or swapped. + * @param key Key value of the element whose mapped value is accessed. + * @param val Value, the item. */ - private insert_case2(N); + set(key: Key, val: T): void; /** - *

N's parent ({@link XTreeNode.parent P}) and uncle - * ({@link XTreeNode.uncle U}) are red.

- * - *

If both the parent {@link XTreeNode.parent P} and the uncle {@link XTreeNode.uncle U} - * are red, then both of them can be repainted black - * and the grandparent {@link XTreeNode.grand_parent G} becomes red (to - * maintain property 5 (all paths from any given node to its leaf nodes contain the same number of - * black nodes)).

- * - *

Now, the current red node N has a - * black parent. Since any path through the parent or uncle must pass through - * the grandparent, the number of black nodes on these paths has not changed. - * - *

However, the grandparent {@link XTreeNode.grand_parent G} may now violate properties 2 (The - * root is black) or 4 (Both children of every red - * node are black) (property 4 possibly being violated since - * {@link XTreeNode.grand_parent G} may have a red parent).

+ *

Extract an element.

* - *

To fix this, the entire procedure is recursively performed on {@link XTreeNode.grand_parent G} - * from case 1. Note that this is a tail-recursive call, so it could be rewritten as a loop; since this is - * the only loop, and any rotations occur after this loop, this proves that a constant number of rotations - * occur.

+ *

Extracts the element pointed to by key and erases it from the {@link UniqueMap}.

* - *

+ * @param key Key value of the element whose mapped value is accessed. * - * @param N A node to be inserted or swapped. + * @return A {@link Pair} containing the value pointed to by key. */ - private insert_case3(N); + extract(key: Key): Pair; /** - *

N is added to right of left child of grandparent, or N is added to left - * of right child of grandparent ({@link XTreeNode.parent P} is red and - * {@link XTreeNode.uncle U} is black).

+ *

Extract an element.

* - *

The parent {@link XTreeNode.parent P} is red but the uncle - * {@link XTreeNode.uncle U} is black; also, the current node - * N is the right child of {@link XTreeNode.parent P}, and - * {@link XTreeNode.parent P} in turn is the left child of its parent - * {@link XTreeNode.grand_parent G}.

+ *

Extracts the element pointed to by key and erases it from the {@link UniqueMap}.

* - *

In this case, a left rotation on {@link XTreeNode.parent P} that switches the roles of the - * current node N and its parent {@link XTreeNode.parent P} can be performed; then, - * the former parent node {@link XTreeNode.parent P} is dealt with using case 5 - * (relabeling N and {@link XTreeNode.parent P}) because property 4 (both children of - * every red node are black) is still violated.

+ * @param it An iterator pointing an element to extract. * - *

The rotation causes some paths (those in the sub-tree labelled "1") to pass through the node - * N where they did not before. It also causes some paths (those in the sub-tree labelled "3") - * not to pass through the node {@link XTreeNode.parent P} where they did before. However, both of - * these nodes are red, so property 5 (all paths from any given node to its leaf - * nodes contain the same number of black nodes) is not violated by the - * rotation.

+ * @return An iterator pointing to the element immediately following it prior to the element being + * erased. If no such element exists,returns {@link end end()}. + */ + extract(it: MapIterator): MapIterator; + /** + *

Extract an element.

* - *

After this case has been completed, property 4 (both children of every red - * node are black) is still violated, but now we can resolve this by - * continuing to case 5.

+ *

Extracts the element pointed to by key and erases it from the {@link UniqueMap}.

* - *

+ * @param it An iterator pointing an element to extract. * - * @param N A node to be inserted or swapped. + * @return An iterator pointing to the element immediately following it prior to the element being + * erased. If no such element exists,returns {@link end end()}. */ - private insert_case4(node); + extract(it: MapReverseIterator): MapReverseIterator; /** - *

N is added to left of left child of grandparent, or N is added to right - * of right child of grandparent ({@link XTreeNode.parent P} is red and - * {@link XTreeNode.uncle U} is black).

+ * @hidden + */ + private extract_by_key(key); + /** + * @hidden + */ + private extract_by_iterator(it); + /** + * @hidden + */ + private extract_by_reverse_iterator(it); + /** + * Construct and insert element. * - *

The parent {@link XTreeNode.parent P} is red but the uncle - * {@link XTreeNode.uncle U} is black, the current node N - * is the left child of {@link XTreeNode.parent P}, and {@link XTreeNode.parent P} is the left - * child of its parent {@link XTreeNode.grand_parent G}.

+ * Inserts a new element in the {@link UniqueMap} if its *key* is unique. This new element is constructed in + * place using args as the arguments for the construction of a *value_type* (which is an object of a + * {@link Pair} type). * - *

In this case, a right rotation on {@link XTreeNode.grand_parent G} is performed; the result is a - * tree where the former parent {@link XTreeNode.parent P} is now the parent of both the current node - * N and the former grandparent {@link XTreeNode.grand_parent G}.

+ * The insertion only takes place if no other element in the container has a *key equivalent* to the one + * being emplaced (*keys* in a {@link UniqueMap} container are unique). * - *

{@link XTreeNode.grand_parent G} is known to be black, since its - * former child {@link XTreeNode.parent P} could not have been red otherwise - * (without violating property 4). Then, the colors of {@link XTreeNode.parent P} and - * {@link XTreeNode.grand_parent G} are switched, and the resulting tree satisfies property 4 (both - * children of every red node are black). Property 5 - * (all paths from any given node to its leaf nodes contain the same number of - * black nodes) also remains satisfied, since all paths that went through any - * of these three nodes went through {@link XTreeNode.grand_parent G} before, and now they all go - * through {@link XTreeNode.parent P}. In each case, this is the only - * black node of the three.

+ * If inserted, this effectively increases the container {@link size} by one. * - *

+ * A similar member function exists, {@link insert}, which either copies or moves existing objects into the + * container. * - * @param N A node to be inserted or swapped. + * @param key The key used both to look up and to insert if not found. + * @param value Value, the item. + * + * @return If the function successfully inserts the element (because no equivalent element existed already in + * the {@link UniqueMap}), the function returns a {@link Pair} of an {@link MapIterator iterator} to + * the newly inserted element and a value of true. Otherwise, it returns an + * {@link MapIterator iterator} to the equivalent element within the container and a value of false. */ - private insert_case5(node); + emplace(key: Key, value: T): Pair, boolean>; /** - *

Erase an element with its node.

- * - *

In a regular binary search tree when deleting a node with two non-leaf children, we find either the - * maximum element in its left subtree (which is the in-order predecessor) or the minimum element in its - * right subtree (which is the in-order successor) and move its value into the node being deleted (as shown - * here). We then delete the node we copied the value from, which must have fewer than two non-leaf children. - * (Non-leaf children, rather than all children, are specified here because unlike normal binary search - * trees, red-black trees can have leaf nodes anywhere, so that all nodes are either internal nodes with - * two children or leaf nodes with, by definition, zero children. In effect, internal nodes having two leaf - * children in a red-black tree are like the leaf nodes in a regular binary search tree.) Because merely - * copying a value does not violate any red-black properties, this reduces to the problem of deleting a node - * with at most one non-leaf child. Once we have solved that problem, the solution applies equally to the - * case where the node we originally want to delete has at most one non-leaf child as to the case just - * considered where it has two non-leaf children.

+ * Construct and insert element. * - *

Therefore, for the remainder of this discussion we address the deletion of a node with at most one - * non-leaf child. We use the label M to denote the node to be deleted; C will denote a - * selected child of M, which we will also call "its child". If M does have a non-leaf child, - * call that its child, C; otherwise, choose either leaf as its child, C.

+ * Inserts a new element in the {@link UniqueMap} if its *key* is unique. This new element is constructed in + * place using args as the arguments for the construction of a *value_type* (which is an object of a + * {@link Pair} type). * - *

If M is a red node, we simply replace it with its child C, - * which must be black by property 4. (This can only occur when M has - * two leaf children, because if the red node M had a - * black non-leaf child on one side but just a leaf child on the other side, - * then the count of black nodes on both sides would be different, thus the - * tree would violate property 5.) All paths through the deleted node will simply pass through one fewer - * red node, and both the deleted node's parent and child must be - * black, so property 3 (all leaves are black) - * and property 4 (both children of every red node are - * black) still hold.

+ * The insertion only takes place if no other element in the container has a *key equivalent* to the one + * being emplaced (*keys* in a {@link UniqueMap} container are unique). * - *

Another simple case is when M is black and C is - * red. Simply removing a black node could break - * Properties 4 (“Both children of every red node are - * black”) and 5 (“All paths from any given node to its leaf nodes contain the - * same number of black nodes”), but if we repaint C - * black, both of these properties are preserved.

+ * If inserted, this effectively increases the container {@link size} by one. * - *

The complex case is when both M and C are black. (This - * can only occur when deleting a black node which has two leaf children, - * because if the black node M had a black - * non-leaf child on one side but just a leaf child on the other side, then the count of - * black nodes on both sides would be different, thus the tree would have been - * an invalid red-black tree by violation of property 5.) We begin by replacing M with its child - * C. We will relabel this child C (in its new position) N, and its sibling (its - * new parent's other child) {@link XTreeNode.sibling S}. ({@link XTreeNode.sibling S} was - * previously the sibling of M.)

+ * A similar member function exists, {@link insert}, which either copies or moves existing objects into the + * container. * - *

In the diagrams below, we will also use {@link XTreeNode.parent P} for N's new - * parent (M's old parent), SL for {@link XTreeNode.sibling S}'s left child, and - * SR for {@link XTreeNode.sibling S}'s right child ({@link XTreeNode.sibling S} cannot - * be a leaf because if M and C were black, then - * {@link XTreeNode.parent P}'s one subtree which included M counted two - * black-height and thus {@link XTreeNode.parent P}'s other subtree - * which includes {@link XTreeNode.sibling S} must also count two - * black-height, which cannot be the case if {@link XTreeNode.sibling S} - * is a leaf node).

+ * @param pair A single argument of a {@link Pair} type with a value for the *key* as + * {@link Pair.first first} member, and a *value* for the mapped value as + * {@link Pair.second second}. * - *

Notes

- *
    - *
  1. - * The label N will be used to denote the current node (colored - * black). In the diagrams N carries a blue contour. At the - * beginning, this is the replacement node and a leaf, but the entire procedure may also be applied - * recursively to other nodes (see case 3). In between some cases, the roles and labels of the nodes - * are exchanged, but in each case, every label continues to represent the same node it represented at - * the beginning of the case. - *
  2. - *
  3. - * If a node in the right (target) half of a diagram carries a blue contour it will become the current - * node in the next iteration and there the other nodes will be newly assigned relative to it. Any - * color shown in the diagram is either assumed in its case or implied by those assumptions. - * White represents an arbitrary color (either red or - * black), but the same in both halves of the diagram. - *
  4. - *
  5. - * A numbered triangle represents a subtree of unspecified depth. A black - * circle atop a triangle means that black-height of subtree is greater - * by one compared to subtree without this circle. - *
  6. - *
+ * @return If the function successfully inserts the element (because no equivalent element existed already in + * the {@link UniqueMap}), the function returns a {@link Pair} of an {@link MapIterator iterator} to + * the newly inserted element and a value of true. Otherwise, it returns an + * {@link MapIterator iterator} to the equivalent element within the container and a value of false. + */ + emplace(pair: Pair): Pair, boolean>; + /** + *

Insert an element.

* - *

If both N and its original parent are black, then - * deleting this original parent causes paths which proceed through N to have one fewer - * black node than paths that do not. As this violates property 5 (all paths - * from any given node to its leaf nodes contain the same number of black - * nodes), the tree must be rebalanced. There are several cases to consider:

+ *

Extends the container by inserting new elements, effectively increasing the container {@link size} by + * one.

* - *
    - *
  1. N is the new root.
  2. - *
  3. {@link XTreeNode.sibling S} is red.
  4. - *
  5. - * {@link XTreeNode.parent P}, {@link XTreeNode.sibling S}, and - * {@link XTreeNode.sibling S}'s children are black.
  6. - *
  7. - * {@link XTreeNode.sibling S} and {@link XTreeNode.sibling S}'s children are - * black, but {@link XTreeNode.parent P} is - * red. - *
  8. - *
  9. - * {@link XTreeNode.sibling S} is black, - * {@link XTreeNode.sibling S}'s left child is red, - * {@link XTreeNode.sibling S}'s right child is black, and - * N is the left child of its parent. - *
  10. - *
  11. - * {@link XTreeNode.sibling S} is black, - * {@link XTreeNode.sibling S}'s right child is red, and - * N is the left child of its parent {@link XTreeNode.parent P}. - *
  12. - *
+ *

Because element keys in a {@link UniqueMap} are unique, the insertion operation checks whether + * each inserted element has a key equivalent to the one of an element already in the container, and + * if so, the element is not inserted, returning an iterator to this existing element (if the function + * returns a value).

* - *

Again, the function calls all use tail recursion, so the algorithm is in-place.

+ *

For a similar container allowing for duplicate elements, see {@link MultiMap}.

* - *

In the algorithm above, all cases are chained in order, except in delete case 3 where it can recurse - * to case 1 back to the parent node: this is the only case where an iterative implementation will - * effectively loop. No more than h loops back to case 1 will occur (where h is the height of the tree). - * And because the probability for escalation decreases exponentially with each iteration the average - * removal cost is constant.

+ * @param pair A single argument of a {@link Pair} type with a value for the *key* as + * {@link Pair.first first} member, and a *value* for the mapped value as + * {@link Pair.second second}. * - *

Additionally, no tail recursion ever occurs on a child node, so the tail recursion loop can only - * move from a child back to its successive ancestors. If a rotation occurs in case 2 (which is the only - * possibility of rotation within the loop of cases 1–3), then the parent of the node N - * becomes red after the rotation and we will exit the loop. Therefore, at most one - * rotation will occur within this loop. Since no more than two additional rotations will occur after - * exiting the loop, at most three rotations occur in total.

+ * @return A {@link Pair}, with its member {@link Pair.first} set to an iterator pointing to either the newly + * inserted element or to the element with an equivalent key in the {@link UniqueMap}. The + * {@link Pair.second} element in the {@link Pair} is set to true if a new element was inserted or + * false if an equivalent key already existed. + */ + insert(pair: Pair): Pair, boolean>; + /** + *

Insert an element.

* - * @param val An element to erase. + *

Extends the container by inserting a new element, effectively increasing the container size by the + * number of elements inserted.

+ * + *

Because element keys in a {@link UniqueMap} are unique, the insertion operation checks whether + * each inserted element has a key equivalent to the one of an element already in the container, and + * if so, the element is not inserted, returning an iterator to this existing element (if the function + * returns a value).

+ * + *

For a similar container allowing for duplicate elements, see {@link MultiMap}.

+ * + * @param tuple Tuple represensts the {@link Pair} to be inserted as an element. + * + * @return A {@link Pair}, with its member {@link Pair.first} set to an iterator pointing to either the newly + * inserted element or to the element with an equivalent key in the {@link UniqueMap}. The + * {@link Pair.second} element in the {@link Pair} is set to true if a new element was inserted or + * false if an equivalent key already existed. */ - erase(val: T): void; + insert(tuple: [L, U]): Pair, boolean>; /** - *

N is the new root.

+ * @inheritdoc + */ + insert(hint: MapIterator, pair: Pair): MapIterator; + /** + * @inheritdoc + */ + insert(hint: MapReverseIterator, pair: Pair): MapReverseIterator; + /** + * @inheritdoc + */ + insert(hint: MapIterator, tuple: [L, U]): MapIterator; + /** + * @inheritdoc + */ + insert(hint: MapReverseIterator, tuple: [L, U]): MapReverseIterator; + /** + * @inheritdoc + */ + insert>>(first: InputIterator, last: InputIterator): void; + /** + *

Insert or assign an element.

* - *

In this case, we are done. We removed one black node from every path, - * and the new root is black, so the properties are preserved.

+ *

Inserts an element or assigns to the current element if the key already exists.

* - *

Note

- *

In cases 2, 5, and 6, we assume N is the left child of its parent - * {@link XTreeNode.parent P}. If it is the right child, left and right should be reversed throughout - * these three cases. Again, the code examples take both cases into account.

+ *

Because element keys in a {@link UniqueMap} are unique, the insertion operation checks whether + * each inserted element has a key equivalent to the one of an element already in the container, and + * if so, the element is assigned, returning an iterator to this existing element (if the function returns a + * value).

* - * @param N A node to be erased or swapped. + *

For a similar container allowing for duplicate elements, see {@link MultiMap}.

+ * + * @param key The key used both to look up and to insert if not found. + * @param value Value, the item. + * + * @return A {@link Pair}, with its member {@link Pair.first} set to an iterator pointing to either the newly + * inserted element or to the element with an equivalent key in the {@link UniqueMap}. The + * {@link Pair.second} element in the {@link Pair} is set to true if a new element was inserted or + * false if an equivalent key already existed so the value is assigned. */ - private erase_case1(N); + insert_or_assign(key: Key, value: T): Pair, boolean>; /** - *

{@link XTreeNode.sibling S} is red.

+ *

Insert or assign an element.

* - *

+ *

Inserts an element or assigns to the current element if the key already exists.

* - *

In this case we reverse the colors of {@link XTreeNode.parent P} and - * {@link XTreeNode.sibling S}, and then rotate left at {@link XTreeNode.parent P}, turning - * {@link XTreeNode.sibling S} into N's grandparent.

+ *

Because element keys in a {@link UniqueMap} are unique, the insertion operation checks whether + * each inserted element has a key equivalent to the one of an element already in the container, and + * if so, the element is assigned, returning an iterator to this existing element (if the function returns a + * value).

* - *

Note that {@link XTreeNode.parent P} has to be black as it had a - * red child. The resulting subtree has a path short one - * black node so we are not done. Now N has a - * black sibling and a red parent, so we can proceed - * to step 4, 5, or 6. (Its new sibling is black because it was once the child - * of the red {@link XTreeNode.sibling S}.) In later cases, we will re-label - * N's new sibling as {@link XTreeNode.sibling S}.

+ *

For a similar container allowing for duplicate elements, see {@link MultiMap}.

* - * @param N A node to be erased or swapped. + * @param hint Hint for the position where the element can be inserted. + * @param key The key used both to look up and to insert if not found. + * @param value Value, the item. + * + * @return An iterator pointing to either the newly inserted element or to the element that already had an + * equivalent key in the {@link UniqueMap}. */ - private erase_case2(N); + insert_or_assign(hint: MapIterator, key: Key, value: T): MapIterator; /** - *

{@link XTreeNode.parent P}, {@link XTreeNode.sibling S}, and {@link XTreeNode.sibling - * S}'s children are black.

+ *

Insert or assign an element.

* - *

+ *

Inserts an element or assigns to the current element if the key already exists.

* - *

In this case, we simply repaint {@link XTreeNode.sibling S} red. The - * result is that all paths passing through {@link XTreeNode.sibling S}, which are precisely those - * paths not passing through N, have one less black node. - * Because deleting N's original parent made all paths passing through N have - * one less black node, this evens things up.

+ *

Because element keys in a {@link UniqueMap} are unique, the insertion operation checks whether + * each inserted element has a key equivalent to the one of an element already in the container, and + * if so, the element is assigned, returning an iterator to this existing element (if the function returns a + * value).

* - *

However, all paths through {@link XTreeNode.parent P} now have one fewer - * black node than paths that do not pass through - * {@link XTreeNode.parent P}, so property 5 (all paths from any given node to its leaf nodes contain - * the same number of black nodes) is still violated.

+ *

For a similar container allowing for duplicate elements, see {@link MultiMap}.

* - *

To correct this, we perform the rebalancing procedure on {@link XTreeNode.parent P}, starting - * at case 1.

+ * @param hint Hint for the position where the element can be inserted. + * @param key The key used both to look up and to insert if not found. + * @param value Value, the item. * - * @param N A node to be erased or swapped. + * @return An iterator pointing to either the newly inserted element or to the element that already had an + * equivalent key in the {@link UniqueMap}. */ - private erase_case3(N); + insert_or_assign(hint: MapReverseIterator, key: Key, value: T): MapReverseIterator; /** - *

{@link XTreeNode.sibling S} and {@link XTreeNode.sibling S}'s children are - * black, but {@link XTreeNode.parent P} is red.

+ * @hidden + */ + private insert_or_assign_with_key_value(key, value); + /** + * @hidden + */ + private insert_or_assign_with_hint(hint, key, value); + } +} +declare namespace std.base { + /** + *

An abstract multi-map.

+ * + *

{@link MultiMap MultiMaps} are associative containers that store elements formed by a combination of a + * key value (Key) and a mapped value (T), and which allows for fast retrieval of + * individual elements based on their keys.

+ * + *

In a {@link MapContainer}, the key values are generally used to identify the elements, while the + * mapped values store the content associated to this key. The types of key and + * mapped value may differ, and are grouped together in member type value_type, which is a + * {@link Pair} type combining both:

+ * + *

typedef pair value_type;

+ * + *

{@link UniqueMap} stores elements, keeps sequence and enables indexing by inserting elements into a + * {@link List} and registering {@link ListIterator iterators} of the {@link data_ list container} to an index + * table like {@link RBTree tree} or {@link HashBuckets hash-table}.

+ * + *

+ *

+ * + *

Container properties

+ *
+ *
Associative
+ *
+ * Elements in associative containers are referenced by their key and not by their absolute position + * in the container. + *
+ * + *
Map
+ *
+ * Each element associates a key to a mapped value: + * Keys are meant to identify the elements whose main content is the mapped value. + *
+ * + *
Multiple equivalent keys
+ *
Multiple elements in the container can have equivalent keys.
+ *
+ * + * @param Type of the keys. Each element in a map is identified by its key value. + * @param Type of the mapped value. Each element in a map stores some data as its mapped value. + * + * @author Jeongho Nam + */ + abstract class MultiMap extends MapContainer { + /** + * Construct and insert element. * - *

+ * Inserts a new element in the {@link MultiMap}. This new element is constructed in place using args + * as the arguments for the element's constructor. + * + * This effectively increases the container {@link size} by one. + * + * A similar member function exists, {@link insert}, which either copies or moves existing objects into the + * container. * - *

In this case, we simply exchange the colors of {@link XTreeNode.sibling S} and - * {@link XTreeNode.parent P}. This does not affect the number of black - * nodes on paths going through {@link XTreeNode.sibling S}, but it does add one to the number of - * black nodes on paths going through N, making up for the - * deleted black node on those paths.

+ * @param key The key used both to look up and to insert if not found. + * @param value Value, the item. * - * @param N A node to be erased or swapped. + * @return An {@link MapIterator iterator} to the newly inserted element. */ - private erase_case4(N); + emplace(key: Key, value: T): MapIterator; /** - *

{@link XTreeNode.sibling S} is black, {@link XTreeNode.sibling S}'s - * left child is red, {@link XTreeNode.sibling S}'s right child is - * black, and N is the left child of its parent.

+ * Construct and insert element. * - *

+ * Inserts a new element in the {@link MultiMap}. This new element is constructed in place using args + * as the arguments for the element's constructor. * - *

In this case we rotate right at {@link XTreeNode.sibling S}, so that - * {@link XTreeNode.sibling S}'s left child becomes {@link XTreeNode.sibling S}'s parent and - * N's new sibling. We then exchange the colors of {@link XTreeNode.sibling S} and its - * new parent.

+ * This effectively increases the container {@link size} by one. * - *

All paths still have the same number of black nodes, but now - * N has a black sibling whose right child is - * red, so we fall into case 6. Neither N nor its parent are affected - * by this transformation. (Again, for case 6, we relabel N's new sibling as - * {@link XTreeNode.sibling S}.)

+ * A similar member function exists, {@link insert}, which either copies or moves existing objects into the + * container. * - * @param N A node to be erased or swapped. + * @param pair A single argument of a {@link Pair} type with a value for the *key* as + * {@link Pair.first first} member, and a *value* for the mapped value as + * {@link Pair.second second}. + * @return An {@link MapIterator iterator} to the newly inserted element. */ - private erase_case5(N); + emplace(pair: Pair): MapIterator; /** - *

{@link XTreeNode.sibling S} is black, - * {@link XTreeNode.sibling S}'s right child is red, and N is - * the left child of its parent {@link XTreeNode.parent P}.

+ *

Insert elements.

* - *

In this case we rotate left at {@link XTreeNode.parent P}, so that - * {@link XTreeNode.sibling S} becomes the parent of {@link XTreeNode.parent P} and - * {@link XTreeNode.sibling S}'s right child. We then exchange the colors of - * {@link XTreeNode.parent P} and {@link XTreeNode.sibling S}, and make - * {@link XTreeNode.sibling S}'s right child black.

+ *

Extends the container by inserting new elements, effectively increasing the container {@link size} by + * the number of elements inserted.

* - *

The subtree still has the same color at its root, so Properties 4 (Both children of every - * red node are black) and 5 (All paths from any - * given node to its leaf nodes contain the same number of black nodes) are - * not violated. However, N now has one additional black - * ancestor: either {@link XTreeNode.parent P} has become black, or it - * was black and {@link XTreeNode.sibling S} was added as a - * black grandparent.

+ * @param pair A single argument of a {@link Pair} type with a value for the *key* as + * {@link Pair.first first} member, and a *value* for the mapped value as + * {@link Pair.second second}. * - *

Thus, the paths passing through N pass through one additional - * black node.

+ * @return An iterator pointing to the newly inserted element. + */ + insert(pair: Pair): MapIterator; + /** + *

Insert elements.

* - *

+ *

Extends the container by inserting new elements, effectively increasing the container {@link size} by + * the number of elements inserted.

* - *

Meanwhile, if a path does not go through N, then there are two possibilities:

- *
    - *
  1. - * It goes through N's new sibling SL, a node with arbitrary color and the root of - * the subtree labeled 3 (s. diagram). Then, it must go through {@link XTreeNode.sibling S} and - * {@link XTreeNode.parent P}, both formerly and currently, as they have only exchanged colors - * and places. Thus the path contains the same number of black nodes. - *
  2. - *
  3. - * It goes through N's new uncle, {@link XTreeNode.sibling S}'s right child. Then, - * it formerly went through {@link XTreeNode.sibling S}, {@link XTreeNode.sibling S}'s - * parent, and {@link XTreeNode.sibling S}'s right child SR (which was - * red), but now only goes through {@link XTreeNode.sibling S}, which - * has assumed the color of its former parent, and {@link XTreeNode.sibling S}'s right child, - * which has changed from red to black (assuming - * {@link XTreeNode.sibling S}'s color: black). The net effect is - * that this path goes through the same number of black nodes. - *
  4. - *
+ * @param tuple Tuple represensts the {@link Pair} to be inserted as an element. * - *

Either way, the number of black nodes on these paths does not change. - * Thus, we have restored Properties 4 (Both children of every red node are - * black) and 5 (All paths from any given node to its leaf nodes contain the - * same number of black nodes). The white node in the diagram can be either - * red or black, but must refer to the same color - * both before and after the transformation.

+ * @return An iterator pointing to the newly inserted element. + */ + insert(tuple: [L, U]): MapIterator; + /** + * @inheritdoc + */ + insert(hint: MapIterator, pair: Pair): MapIterator; + /** + * @inheritdoc + */ + insert(hint: MapReverseIterator, pair: Pair): MapReverseIterator; + /** + * @inheritdoc + */ + insert(hint: MapIterator, tuple: [L, U]): MapIterator; + /** + * @inheritdoc + */ + insert(hint: MapReverseIterator, tuple: [L, U]): MapReverseIterator; + /** + * @inheritdoc + */ + insert>>(first: InputIterator, last: InputIterator): void; + } +} +declare namespace std.HashMap { + type iterator = std.MapIterator; + type reverse_iterator = std.MapReverseIterator; +} +declare namespace std { + /** + *

Hashed, unordered map.

+ * + *

{@link HashMap}s are associative containers that store elements formed by the combination of a key value + * and a mapped value, and which allows for fast retrieval of individual elements based on their keys. + *

+ * + *

In an {@link HashMap}, the key value is generally used to uniquely identify the element, while the + * mapped value is an object with the content associated to this key. Types of key and + * mapped value may differ.

+ * + *

Internally, the elements in the {@link HashMap} are not sorted in any particular order with respect to either + * their key or mapped values, but organized into buckets depending on their hash values to allow + * for fast access to individual elements directly by their key values (with a constant average time complexity + * on average).

+ * + *

{@link HashMap} containers are faster than {@link TreeMap} containers to access individual elements by their + * key, although they are generally less efficient for range iteration through a subset of their elements.

+ * + *

+ * + *

+ * + *

Container properties

+ *
+ *
Associative
+ *
Elements in associative containers are referenced by their key and not by their absolute + * position in the container.
+ * + *
Hashed
+ *
Hashed containers organize their elements using hash tables that allow for fast access to elements + * by their key.
+ * + *
Map
+ *
Each element associates a key to a mapped value: + * Keys are meant to identify the elements whose main content is the mapped value.
+ * + *
Unique keys
+ *
No two elements in the container can have equivalent keys.
+ *
+ * + * @param Type of the key values. + * Each element in an {@link HashMap} is uniquely identified by its key value. + * @param Type of the mapped value. + * Each element in an {@link HashMap} is used to store some data as its mapped value. + * + * @reference http://www.cplusplus.com/reference/unordered_map/unordered_map + * @author Jeongho Nam + */ + class HashMap extends base.UniqueMap implements base.IHashMap { + /** + * @hidden + */ + private hash_buckets_; + /** + * Default Constructor. + */ + constructor(); + /** + * Construct from elements. + */ + constructor(items: Pair[]); + /** + * Contruct from tuples. * - * @param N A node to be erased or swapped. + * @param array Tuples to be contained. + */ + constructor(array: [Key, T][]); + /** + * Copy Constructor. + */ + constructor(container: HashMap); + /** + * Construct from range iterators. + */ + constructor(begin: Iterator>, end: Iterator>); + /** + * @inheritdoc + */ + clear(): void; + /** + * @inheritdoc + */ + find(key: Key): MapIterator; + /** + * @inheritdoc + */ + begin(): MapIterator; + /** + * @inheritdoc + */ + begin(index: number): MapIterator; + /** + * @inheritdoc + */ + end(): MapIterator; + /** + * @inheritdoc + */ + end(index: number): MapIterator; + /** + * @inheritdoc + */ + rbegin(): MapReverseIterator; + /** + * @inheritdoc + */ + rbegin(index: number): MapReverseIterator; + /** + * @inheritdoc + */ + rend(): MapReverseIterator; + /** + * @inheritdoc + */ + rend(index: number): MapReverseIterator; + /** + * @inheritdoc + */ + bucket_count(): number; + /** + * @inheritdoc + */ + bucket_size(index: number): number; + /** + * @inheritdoc + */ + max_load_factor(): number; + /** + * @inheritdoc */ - private erase_case6(node); + max_load_factor(z: number): void; /** - * Rotate a node left. - * - * @param node Node to rotate left. + * @inheritdoc */ - protected rotate_left(node: XTreeNode): void; + bucket(key: Key): number; /** - * Rotate a node to right. - * - * @param node A node to rotate right. + * @inheritdoc */ - protected rotate_right(node: XTreeNode): void; + reserve(n: number): void; /** - * Replace a node. - * - * @param oldNode Ordinary node to be replaced. - * @param newNode Target node to replace. + * @inheritdoc */ - protected replace_node(oldNode: XTreeNode, newNode: XTreeNode): void; + rehash(n: number): void; /** - * Fetch color from a node. + * @hidden + */ + protected _Insert_by_pair(pair: Pair): any; + /** + * @hidden + */ + protected _Insert_by_hint(hint: MapIterator, pair: Pair): MapIterator; + /** + * @hidden + */ + protected _Insert_by_range>>(first: InputIterator, last: InputIterator): void; + /** + * @inheritdoc + */ + protected _Handle_insert(first: MapIterator, last: MapIterator): void; + /** + * @inheritdoc + */ + protected _Handle_erase(first: MapIterator, last: MapIterator): void; + /** + *

Swap content.

* - * @param node A node to fetch color. - * @retur color. + *

Exchanges the content of the container by the content of obj, which is another + * {@link HashMap map} of the same type. Sizes abd container type may differ.

+ * + *

After the call to this member function, the elements in this container are those which were + * in obj before the call, and the elements of obj are those which were in this. All + * iterators, references and pointers remain valid for the swapped objects.

+ * + *

Notice that a non-member function exists with the same name, {@link std.swap swap}, overloading that + * algorithm with an optimization that behaves like this member function.

+ * + * @param obj Another {@link HashMap map container} of the same type of elements as this (i.e., + * with the same template parameters, Key and T) whose content is swapped + * with that of this {@link HashMap container}. */ - private fetch_color(node); + swap(obj: HashMap): void; + /** + * @inheritdoc + */ + swap(obj: base.IContainer>): void; } } -declare namespace std.base { +declare namespace std.HashMultiMap { + type iterator = std.MapIterator; + type reverse_iterator = std.MapReverseIterator; +} +declare namespace std { /** - *

Common interface for tree-structured map.

- * - *

{@link ITreeMap ITreeMaps} are associative containers that store elements formed by a combination of - * a key value and a mapped value, following a specific order.

- * - *

In a {@link ITreeMap}, the key values are generally used to sort and uniquely identify - * the elements, while the mapped values store the content associated to this key. The types of - * key and mapped value may differ, and are grouped together in member type - * value_type, which is a {@link Pair} type combining both:

+ *

Hashed, unordered Multimap.

* - *

typedef Pair value_type;

+ *

{@link HashMultiMap}s are associative containers that store elements formed by the combination of + * a key value and a mapped value, much like {@link HashMultiMap} containers, but allowing + * different elements to have equivalent keys.

* - *

Internally, the elements in a {@link ITreeMap}are always sorted by its key following a - * strict weak ordering criterion indicated by its internal comparison method (of {@link less}).

+ *

In an {@link HashMultiMap}, the key value is generally used to uniquely identify the + * element, while the mapped value is an object with the content associated to this key. + * Types of key and mapped value may differ.

* - *

{@link ITreeMap}containers are generally slower than {@link IHashMap} containers - * to access individual elements by their key, but they allow the direct iteration on subsets based - * on their order.

+ *

Internally, the elements in the {@link HashMultiMap} are not sorted in any particular order with + * respect to either their key or mapped values, but organized into buckets depending on + * their hash values to allow for fast access to individual elements directly by their key values + * (with a constant average time complexity on average).

* - *

{@link ITreeMap TreeMultiMaps} are typically implemented as binary search trees.

+ *

Elements with equivalent keys are grouped together in the same bucket and in such a way that + * an iterator can iterate through all of them. Iterators in the container are doubly linked iterators.

* - *

- *

+ *

+ * + *

* *

Container properties

*
@@ -6247,292 +5648,186 @@ declare namespace std.base { *
Elements in associative containers are referenced by their key and not by their absolute * position in the container.
* - *
Ordered
- *
The elements in the container follow a strict order at all times. All inserted elements are - * given a position in this order.
+ *
Hashed
+ *
Hashed containers organize their elements using hash tables that allow for fast access to elements + * by their key.
* *
Map
*
Each element associates a key to a mapped value: * Keys are meant to identify the elements whose main content is the mapped value.
+ * + *
Multiple equivalent keys
+ *
The container can hold multiple elements with equivalent keys.
*
* - * @param Type of the keys. Each element in a map is uniquely identified by its key value. - * @param Type of the mapped value. Each element in a map stores some data as its mapped value. + * @param Type of the key values. + * Each element in an {@link HashMultiMap} is identified by a key value. + * @param Type of the mapped value. + * Each element in an {@link HashMultiMap} is used to store some data as its mapped value. * - * @reference http://www.cplusplus.com/reference/map + * @reference http://www.cplusplus.com/reference/unordered_map/unordered_multimap * @author Jeongho Nam */ - interface ITreeMap { + class HashMultiMap extends base.MultiMap { /** - *

Return key comparison function.

- * - *

Returns a references of the comparison function used by the container to compare keys.

- * - *

The comparison object of a {@link ITreeMap tree-map object} is set on - * {@link TreeMap.constructor construction}. Its type (Key) is the last parameter of the - * {@link ITreeMap.constructor constructors}. By default, this is a {@link less} function, which returns the same - * as operator<.

- * - *

This function determines the order of the elements in the container: it is a function pointer that takes - * two arguments of the same type as the element keys, and returns true if the first argument - * is considered to go before the second in the strict weak ordering it defines, and false otherwise. - *

- * - *

Two keys are considered equivalent if {@link key_comp} returns false reflexively (i.e., no - * matter the order in which the keys are passed as arguments).

- * - * @return The comparison function. + * @hidden */ - key_comp(): (x: Key, y: Key) => boolean; + private hash_buckets_; /** - *

Return value comparison function.

- * - *

Returns a comparison function that can be used to compare two elements to get whether the key of the first - * one goes before the second.

- * - *

The arguments taken by this function object are of member type std.Pair (defined in - * {@link ITreeMap}), but the mapped type (T) part of the value is not taken into consideration in this - * comparison.

- * - *

This comparison class returns true if the {@link Pair.first key} of the first argument - * is considered to go before that of the second (according to the strict weak ordering specified by the - * container's comparison function, {@link key_comp}), and false otherwise.

- * - * @return The comparison function for element values. + * Default Constructor. */ - value_comp(): (x: Pair, y: Pair) => boolean; + constructor(); /** - *

Return iterator to lower bound.

- * - *

Returns an iterator pointing to the first element in the container whose key is not considered to - * go before k (i.e., either it is equivalent or goes after).

- * - *

The function uses its internal comparison object (key_comp) to determine this, returning an - * iterator to the first element for which key_comp(k, element_key) would return false.

- * - *

If the {@link ITreeMap} class is instantiated with the default comparison type ({@link less}), - * the function returns an iterator to the first element whose key is not less than k

. - * - *

A similar member function, {@link upper_bound}, has the same behavior as {@link lower_bound}, except - * in the case that the {@link ITreeMap} contains an element with a key equivalent to k: In this - * case, {@link lower_bound} returns an iterator pointing to that element, whereas {@link upper_bound} - * returns an iterator pointing to the next element.

- * - * @param k Key to search for. - * - * @return An iterator to the the first element in the container whose key is not considered to go before - * k, or {@link ITreeMap.end} if all keys are considered to go before k. + * Construct from elements. */ - lower_bound(key: Key): MapIterator; + constructor(items: Pair[]); /** - *

Return iterator to upper bound.

- * - *

Returns an iterator pointing to the first element in the container whose key is considered to - * go after k

. - * - *

The function uses its internal comparison object (key_comp) to determine this, returning an - * iterator to the first element for which key_comp(k, element_key) would return true.

- * - *

If the {@link ITreeMap} class is instantiated with the default comparison type ({@link less}), - * the function returns an iterator to the first element whose key is greater than k

. - * - *

A similar member function, {@link lower_bound}, has the same behavior as {@link upper_bound}, except - * in the case that the map contains an element with a key equivalent to k: In this case - * {@link lower_bound} returns an iterator pointing to that element, whereas {@link upper_bound} returns an - * iterator pointing to the next element.

- * - * @param k Key to search for. + * Contruct from tuples. * - * @return An iterator to the the first element in the container whose key is considered to go after - * k, or {@link TreeMap.end end} if no keys are considered to go after k. + * @param array Tuples to be contained. + */ + constructor(array: [Key, T][]); + /** + * Copy Constructor. + */ + constructor(container: HashMultiMap); + /** + * Construct from range iterators. + */ + constructor(begin: Iterator>, end: Iterator>); + /** + * @inheritdoc + */ + clear(): void; + /** + * @inheritdoc + */ + find(key: Key): MapIterator; + /** + * @inheritdoc + */ + count(key: Key): number; + /** + * @inheritdoc + */ + begin(): MapIterator; + /** + * @inheritdoc + */ + begin(index: number): MapIterator; + /** + * @inheritdoc + */ + end(): MapIterator; + /** + * @inheritdoc + */ + end(index: number): MapIterator; + /** + * @inheritdoc + */ + rbegin(): MapReverseIterator; + /** + * @inheritdoc + */ + rbegin(index: number): MapReverseIterator; + /** + * @inheritdoc + */ + rend(): MapReverseIterator; + /** + * @inheritdoc */ - upper_bound(key: Key): MapIterator; + rend(index: number): MapReverseIterator; /** - *

Get range of equal elements.

- * - *

Returns the bounds of a range that includes all the elements in the container which have a key - * equivalent to k

. - * - *

If no matches are found, the range returned has a length of zero, with both iterators pointing to - * the first element that has a key considered to go after k according to the container's internal - * comparison object (key_comp).

- * - *

Two keys are considered equivalent if the container's comparison object returns false reflexively - * (i.e., no matter the order in which the keys are passed as arguments).

- * - * @param k Key to search for. - * - * @return The function returns a {@link Pair}, whose member {@link Pair.first} is the lower bound of - * the range (the same as {@link lower_bound}), and {@link Pair.second} is the upper bound - * (the same as {@link upper_bound}). + * @inheritdoc */ - equal_range(key: Key): Pair, MapIterator>; - } -} -declare namespace std.base { - /** - *

A red-black tree storing {@link MapIterator MapIterators}.

- * - *

- *

- * - * @author Jeongho Nam - */ - class PairTree extends XTree> { + bucket_count(): number; /** - * @hidden + * @inheritdoc */ - private map_; + bucket_size(n: number): number; /** - * @hidden + * @inheritdoc */ - private compare_; + max_load_factor(): number; /** - * Default Constructor. + * @inheritdoc */ - constructor(map: TreeMap | TreeMultiMap, compare?: (x: Key, y: Key) => boolean); - find(key: Key): XTreeNode>; - find(it: MapIterator): XTreeNode>; + max_load_factor(z: number): void; + /** + * @inheritdoc + */ + bucket(key: Key): number; + /** + * @inheritdoc + */ + reserve(n: number): void; + /** + * @inheritdoc + */ + rehash(n: number): void; /** * @hidden */ - private find_by_key(key); + protected _Insert_by_pair(pair: Pair): any; /** - *

Return iterator to lower bound.

- * - *

Returns an iterator pointing to the first element in the container whose key is not considered to - * go before k (i.e., either it is equivalent or goes after).

- * - *

The function uses its internal comparison object (key_comp) to determine this, returning an - * iterator to the first element for which key_comp(k, element_key) would return false.

- * - *

If the {@link ITreeMap} class is instantiated with the default comparison type ({@link less}), - * the function returns an iterator to the first element whose key is not less than k

. - * - *

A similar member function, {@link upper_bound}, has the same behavior as {@link lower_bound}, except - * in the case that the {@link ITreeMap} contains an element with a key equivalent to k: In this - * case, {@link lower_bound} returns an iterator pointing to that element, whereas {@link upper_bound} - * returns an iterator pointing to the next element.

- * - * @param k Key to search for. - * - * @return An iterator to the the first element in the container whose key is not considered to go before - * k, or {@link ITreeMap.end} if all keys are considered to go before k. + * @hidden */ - lower_bound(key: Key): MapIterator; + protected _Insert_by_hint(hint: MapIterator, pair: Pair): MapIterator; /** - *

Return iterator to upper bound.

- * - *

Returns an iterator pointing to the first element in the container whose key is considered to - * go after k

. - * - *

The function uses its internal comparison object (key_comp) to determine this, returning an - * iterator to the first element for which key_comp(k, element_key) would return true.

- * - *

If the {@link ITreeMap} class is instantiated with the default comparison type ({@link less}), - * the function returns an iterator to the first element whose key is greater than k

. - * - *

A similar member function, {@link lower_bound}, has the same behavior as {@link upper_bound}, except - * in the case that the map contains an element with a key equivalent to k: In this case - * {@link lower_bound} returns an iterator pointing to that element, whereas {@link upper_bound} returns an - * iterator pointing to the next element.

- * - * @param k Key to search for. - * - * @return An iterator to the the first element in the container whose key is considered to go after - * k, or {@link TreeMap.end end} if no keys are considered to go after k. + * @hidden */ - upper_bound(key: Key): MapIterator; + protected _Insert_by_range>>(first: InputIterator, last: InputIterator): void; /** - *

Get range of equal elements.

- * - *

Returns the bounds of a range that includes all the elements in the container which have a key - * equivalent to k

. - * - *

If no matches are found, the range returned has a length of zero, with both iterators pointing to - * the first element that has a key considered to go after k according to the container's internal - * comparison object (key_comp).

- * - *

Two keys are considered equivalent if the container's comparison object returns false reflexively - * (i.e., no matter the order in which the keys are passed as arguments).

- * - * @param k Key to search for. - * - * @return The function returns a {@link Pair}, whose member {@link Pair.first} is the lower bound of - * the range (the same as {@link lower_bound}), and {@link Pair.second} is the upper bound - * (the same as {@link upper_bound}). + * @inheritdoc */ - equal_range(key: Key): Pair, MapIterator>; + protected _Handle_insert(first: MapIterator, last: MapIterator): void; /** - *

Return key comparison function.

- * - *

Returns a references of the comparison function used by the container to compare keys.

- * - *

The comparison object of a {@link ITreeMap tree-map object} is set on - * {@link TreeMap.constructor construction}. Its type (Key) is the last parameter of the - * {@link ITreeMap.constructor constructors}. By default, this is a {@link less} function, which returns the same - * as operator<.

- * - *

This function determines the order of the elements in the container: it is a function pointer that takes - * two arguments of the same type as the element keys, and returns true if the first argument - * is considered to go before the second in the strict weak ordering it defines, and false otherwise. - *

- * - *

Two keys are considered equivalent if {@link key_comp} returns false reflexively (i.e., no - * matter the order in which the keys are passed as arguments).

- * - * @return The comparison function. + * @inheritdoc */ - key_comp(): (x: Key, y: Key) => boolean; + protected _Handle_erase(first: MapIterator, last: MapIterator): void; /** - *

Return value comparison function.

+ *

Swap content.

* - *

Returns a comparison function that can be used to compare two elements to get whether the key of the first - * one goes before the second.

+ *

Exchanges the content of the container by the content of obj, which is another + * {@link HashMultiMap map} of the same type. Sizes abd container type may differ.

* - *

The arguments taken by this function object are of member type std.Pair (defined in - * {@link ITreeMap}), but the mapped type (T) part of the value is not taken into consideration in this - * comparison.

+ *

After the call to this member function, the elements in this container are those which were + * in obj before the call, and the elements of obj are those which were in this. All + * iterators, references and pointers remain valid for the swapped objects.

* - *

This comparison class returns true if the {@link Pair.first key} of the first argument - * is considered to go before that of the second (according to the strict weak ordering specified by the - * container's comparison function, {@link key_comp}), and false otherwise.

+ *

Notice that a non-member function exists with the same name, {@link std.swap swap}, overloading that + * algorithm with an optimization that behaves like this member function.

* - * @return The comparison function for element values. - */ - value_comp(): (x: Pair, y: Pair) => boolean; - /** - * @inheritdoc + * @param obj Another {@link HashMultiMap map container} of the same type of elements as this (i.e., + * with the same template parameters, Key and T) whose content is swapped + * with that of this {@link HashMultiMap container}. */ - is_equal_to(left: MapIterator, right: MapIterator): boolean; + swap(obj: HashMultiMap): void; /** * @inheritdoc */ - is_less(left: MapIterator, right: MapIterator): boolean; + swap(obj: base.IContainer>): void; } } declare namespace std.base { /** - *

A common interface for tree-structured set.

- * - *

{@link ITreeSet TreeMultiSets} are containers that store elements following a specific order.

- * - *

In a {@link ITreeSet}, the value of an element also identifies it (the value is itself - * the key, of type T). The value of the elements in a {@link ITreeSet} cannot - * be modified once in the container (the elements are always const), but they can be inserted or removed - * from the

+ *

An abstract set.

* - *

Internally, the elements in a {@link ITreeSet TreeMultiSets} are always sorted following a strict - * weak ordering criterion indicated by its internal comparison method (of {@link IComparable.less less}).

+ *

{@link SetContainer SetContainers} are containers that store elements allowing fast retrieval of + * individual elements based on their value.

* - *

{@link ITreeSet} containers are generally slower than {@link IHashSet} containers - * to access individual elements by their key, but they allow the direct iteration on subsets based on - * their order.

+ *

In an {@link SetContainer}, the value of an element is at the same time its key, used to + * identify it. Keys are immutable, therefore, the elements in an {@link SetContainer} cannot be + * modified once in the container - they can be inserted and removed, though.

* - *

{@link ITreeSet TreeMultiSets} are typically implemented as binary search trees.

+ *

{@link SetContainer} stores elements, keeps sequence and enables indexing by inserting elements into a + * {@link List} and registering {@link ListIterator iterators} of the {@link data_ list container} to an index + * table like {@link RBTree tree} or {@link HashBuckets hash-table}.

* - *

- *

+ *

+ *

* *

Container properties

*
@@ -6542,577 +5837,575 @@ declare namespace std.base { * position in the container. * * - *
Ordered
- *
- * The elements in the container follow a strict order at all times. All inserted elements are - * given a position in this order. - *
- * *
Set
*
The value of an element is also the key used to identify it.
*
* - * @param Type of the elements. Each element in a {@link ITreeSet} container is also identified + * @param Type of the elements. Each element in a {@link SetContainer} container is also identified * by this value (each value is itself also the element's key). * - * @reference http://www.cplusplus.com/reference/set * @author Jeongho Nam */ - interface ITreeSet { + abstract class SetContainer extends Container { + /** + *

{@link List} storing elements.

+ * + *

Storing elements and keeping those sequence of the {@link SetContainer} are implemented by + * {@link data_ this list container}. Implementing index-table is also related with {@link data_ this list} + * by storing {@link ListIterator iterators} ({@link SetIterator} references {@link ListIterator}) who are + * created from {@link data_ here}.

+ */ + private data_; + /** + * Default Constructor. + */ + constructor(); + /** + * @inheritdoc + */ + assign>(begin: Iterator, end: Iterator): void; + /** + * @inheritdoc + */ + clear(): void; + /** + *

Get iterator to element.

+ * + *

Searches the container for an element with key as value and returns an iterator to it if found, + * otherwise it returns an iterator to {@link end end()} (the element past the end of the container).

+ * + *

Another member function, {@link count count()}, can be used to just check whether a particular element + * exists.

+ * + * @param key Key to be searched for. + * + * @return An iterator to the element, if the specified value is found, or {@link end end()} if it is not + * found in the + */ + abstract find(val: T): SetIterator; + /** + * @inheritdoc + */ + begin(): SetIterator; /** - *

Return comparison function.

+ * @inheritdoc + */ + end(): SetIterator; + /** + * @inheritdoc + */ + rbegin(): SetReverseIterator; + /** + * @inheritdoc + */ + rend(): SetReverseIterator; + /** + *

Whether have the item or not.

* - *

Returns a copy of the comparison function used by the container.

+ *

Indicates whether a set has an item having the specified identifier.

* - *

By default, this is a {@link less} object, which returns the same as operator<.

+ * @param key Key value of the element whose mapped value is accessed. * - *

This object determines the order of the elements in the container: it is a function pointer or a function - * object that takes two arguments of the same type as the container elements, and returns true if - * the first argument is considered to go before the second in the strict weak ordering it - * defines, and false otherwise.

+ * @return Whether the set has an item having the specified identifier. + */ + has(val: T): boolean; + /** + *

Count elements with a specific key.

* - *

Two elements of a {@link ITreeSet} are considered equivalent if {@link key_comp} returns false - * reflexively (i.e., no matter the order in which the elements are passed as arguments).

+ *

Searches the container for elements with a value of k and returns the number of elements found.

* - *

In {@link ITreeSet} containers, the keys to sort the elements are the values (T) themselves, - * therefore {@link key_comp} and its sibling member function {@link value_comp} are equivalent.

+ * @param key Value of the elements to be counted. * - * @return The comparison function. + * @return The number of elements in the container with a key. */ - key_comp(): (x: T, y: T) => boolean; + abstract count(val: T): number; /** - *

Return comparison function.

+ * @inheritdoc + */ + size(): number; + /** + * @inheritdoc + */ + push(...args: U[]): number; + /** + *

Insert an element with hint.

* - *

Returns a copy of the comparison function used by the container.

+ *

Extends the container by inserting new elements, effectively increasing the container size by the + * number of elements inserted.

* - *

By default, this is a {@link less} object, which returns the same as operator<.

+ * @param hint Hint for the position where the element can be inserted. + * @param val Value to be inserted as an element. * - *

This object determines the order of the elements in the container: it is a function pointer or a function - * object that takes two arguments of the same type as the container elements, and returns true if - * the first argument is considered to go before the second in the strict weak ordering it - * defines, and false otherwise.

+ * @return An iterator pointing to either the newly inserted element or to the element that already had its + * same value in the {@link SetContainer}. + */ + insert(hint: SetIterator, val: T): SetIterator; + /** + *

Insert an element with hint.

* - *

Two elements of a {@link ITreeSet} are considered equivalent if {@link key_comp} returns false - * reflexively (i.e., no matter the order in which the elements are passed as arguments).

+ *

Extends the container by inserting new elements, effectively increasing the container size by the + * number of elements inserted.

* - *

In {@link ITreeSet} containers, the keys to sort the elements are the values (T) themselves, - * therefore {@link key_comp} and its sibling member function {@link value_comp} are equivalent.

+ * @param hint Hint for the position where the element can be inserted. + * @param val Value to be inserted as an element. * - * @return The comparison function. + * @return An iterator pointing to either the newly inserted element or to the element that already had its + * same value in the {@link SetContainer}. */ - value_comp(): (x: T, y: T) => boolean; + insert(hint: SetReverseIterator, val: T): SetReverseIterator; /** - *

Return iterator to lower bound.

+ *

Insert elements with a range of a

* - *

Returns an iterator pointing to the first element in the container which is not considered to - * go before val (i.e., either it is equivalent or goes after).

+ *

Extends the container by inserting new elements, effectively increasing the container size by the + * number of elements inserted.

* - *

The function uses its internal comparison object (key_comp) to determine this, returning an - * iterator to the first element for which key_comp(element,val) would return false.

+ * @param begin An iterator specifying range of the begining element. + * @param end An iterator specifying range of the ending element. + */ + insert>(begin: InputIterator, end: InputIterator): void; + /** + * @hidden + */ + protected abstract _Insert_by_val(val: T): any; + /** + * @hidden + */ + protected abstract _Insert_by_hint(hint: SetIterator, val: T): SetIterator; + /** + * @hidden + */ + protected abstract _Insert_by_range>(begin: InputIterator, end: InputIterator): void; + /** + *

Erase an element.

+ *

Removes from the set container the elements whose value is key.

* - *

If the {@link ITreeSet} class is instantiated with the default comparison type ({@link less}), - * the function returns an iterator to the first element that is not less than val.

- - *

A similar member function, {@link upper_bound}, has the same behavior as {@link lower_bound}, except - * in the case that the {@link ITreeSet} contains elements equivalent to val: In this case - * {@link lower_bound} returns an iterator pointing to the first of such elements, whereas - * {@link upper_bound} returns an iterator pointing to the element following the last.

+ *

This effectively reduces the container size by the number of elements removed.

* - * @param val Value to compare. + * @param key Value of the elements to be erased. * - * @return An iterator to the the first element in the container which is not considered to go before - * val, or {@link ITreeSet.end} if all elements are considered to go before val. + * @return Number of elements erased. */ - lower_bound(val: T): SetIterator; + erase(val: T): number; /** - *

Return iterator to upper bound.

+ * @inheritdoc + */ + erase(it: SetIterator): SetIterator; + /** + *

Erase elements.

+ *

Removes from the set container a range of elements..

* - *

Returns an iterator pointing to the first element in the container which is considered to go after - * val.

- - *

The function uses its internal comparison object (key_comp) to determine this, returning an - * iterator to the first element for which key_comp(val,element) would return true.

- - *

If the {@code ITreeSet} class is instantiated with the default comparison type (less), the - * function returns an iterator to the first element that is greater than val.

+ *

This effectively reduces the container size by the number of elements removed.

* - *

A similar member function, {@link lower_bound}, has the same behavior as {@link upper_bound}, except - * in the case that the {@ITreeSet} contains elements equivalent to val: In this case - * {@link lower_bound} returns an iterator pointing to the first of such elements, whereas - * {@link upper_bound} returns an iterator pointing to the element following the last.

+ * @param begin An iterator specifying a range of beginning to erase. + * @param end An iterator specifying a range of end to erase. + */ + erase(begin: SetIterator, end: SetIterator): SetIterator; + /** + * @inheritdoc + */ + erase(it: SetReverseIterator): SetReverseIterator; + /** + *

Erase elements.

+ *

Removes from the set container a range of elements..

* - * @param val Value to compare. + *

This effectively reduces the container size by the number of elements removed.

* - * @return An iterator to the the first element in the container which is considered to go after - * val, or {@link TreeSet.end end} if no elements are considered to go after val. + * @param begin An iterator specifying a range of beginning to erase. + * @param end An iterator specifying a range of end to erase. */ - upper_bound(val: T): SetIterator; + erase(begin: SetReverseIterator, end: SetReverseIterator): SetReverseIterator; /** - *

Get range of equal elements.

+ * @hidden + */ + private erase_by_iterator(first, last?); + /** + * @hidden + */ + private erase_by_val(val); + /** + * @hidden + */ + private erase_by_range(begin, end); + /** + *

Abstract method handling insertions for indexing.

* - *

Returns the bounds of a range that includes all the elements in the container that are equivalent - * to val.

+ *

This method, {@link _Handle_insert} is designed to register the first to last to somewhere storing + * those {@link SetIterator iterators} for indexing, fast accessment and retrievalance.

* - *

If no matches are found, the range returned has a length of zero, with both iterators pointing to - * the first element that is considered to go after val according to the container's - * internal comparison object (key_comp).

+ *

When {@link insert} is called, new elements will be inserted into the {@link data_ list container} and new + * {@link SetIterator iterators} first to last, pointing the inserted elements, will be created and the + * newly created iterators first to last will be shifted into this method {@link _Handle_insert} after the + * insertions.

* - *

Two elements of a multiset are considered equivalent if the container's comparison object returns - * false reflexively (i.e., no matter the order in which the elements are passed as arguments).

+ *

If the derived one is {@link RBTree tree-based} like {@link TreeSet}, the {@link SetIterator iterators} + * will be registered into the {@link TreeSet.tree_ tree} as a {@link XTreeNode tree node item}. Else if the + * derived one is {@link HashBuckets hash-based} like {@link HashSet}, the first to last will be + * registered into the {@link HashSet.hash_buckets_ hash bucket}.

* - * @param key Value to search for. + * @param first An {@link SetIterator} to the initial position in a sequence. + * @param last An {@link SetIterator} to the final position in a sequence. The range used is + * [first, last), which contains all the elements between first and last, + * including the element pointed by first but not the element pointed by last. + */ + protected abstract _Handle_insert(first: SetIterator, last: SetIterator): void; + /** + *

Abstract method handling deletions for indexing.

* - * @return The function returns a {@link Pair}, whose member {@link Pair.first} is the lower bound of - * the range (the same as {@link lower_bound}), and {@link Pair.second} is the upper bound - * (the same as {@link upper_bound}). + *

This method, {@link _Handle_erase} is designed to unregister the first to last to somewhere storing + * those {@link SetIterator iterators} for indexing, fast accessment and retrievalance.

+ * + *

When {@link erase} is called with first to last, {@link SetIterator iterators} positioning somewhere + * place to be deleted, is memorized and shifted to this method {@link _Handle_erase} after the deletion process is + * terminated.

+ * + *

If the derived one is {@link RBTree tree-based} like {@link TreeSet}, the {@link SetIterator iterators} + * will be unregistered from the {@link TreeSet.tree_ tree} as a {@link XTreeNode tree node item}. Else if the + * derived one is {@link HashBuckets hash-based} like {@link HashSet}, the first to last will be + * unregistered from the {@link HashSet.hash_buckets_ hash bucket}.

+ * + * @param first An {@link SetIterator} to the initial position in a sequence. + * @param last An {@link SetIterator} to the final position in a sequence. The range used is + * [first, last), which contains all the elements between first and last, + * including the element pointed by first but not the element pointed by last. */ - equal_range(val: T): Pair, SetIterator>; + protected abstract _Handle_erase(first: SetIterator, last: SetIterator): void; + /** + * @hidden + */ + protected _Swap(obj: SetContainer): void; } } -declare namespace std.base { +declare namespace std { /** - *

A red-black Tree storing {@link SetIterator SetIterators}.

+ *

An iterator of a Set.

* - *

- *

+ *

+ *

* * @author Jeongho Nam */ - class AtomicTree extends XTree> { + class SetIterator extends Iterator implements IComparable> { + private list_iterator_; + /** + *

Construct from source and index number.

+ * + *

Note

+ *

Do not create iterator directly.

+ *

Use begin(), find() or end() in Map instead.

+ * + * @param map The source Set to reference. + * @param index Sequence number of the element in the source Set. + */ + constructor(source: base.SetContainer, it: ListIterator); + /** + * @inheritdoc + */ + prev(): SetIterator; + /** + * @inheritdoc + */ + next(): SetIterator; + /** + * @inheritdoc + */ + advance(size: number): SetIterator; /** * @hidden */ - private set_; + private set; + get_list_iterator(): ListIterator; /** - * @hidden + * @inheritdoc */ - private compare_; + value: T; /** - * Default Constructor. + * @inheritdoc */ - constructor(set: TreeSet | TreeMultiSet, compare?: (x: T, y: T) => boolean); - find(val: T): XTreeNode>; - find(it: SetIterator): XTreeNode>; + equal_to(obj: SetIterator): boolean; /** - * @hidden + * @inheritdoc */ - private find_by_val(val); + less(obj: SetIterator): boolean; /** - *

Return iterator to lower bound.

- * - *

Returns an iterator pointing to the first element in the container which is not considered to - * go before val (i.e., either it is equivalent or goes after).

- * - *

The function uses its internal comparison object (key_comp) to determine this, returning an - * iterator to the first element for which key_comp(element,val) would return false.

- * - *

If the {@link ITreeSet} class is instantiated with the default comparison type ({@link less}), - * the function returns an iterator to the first element that is not less than val.

- - *

A similar member function, {@link upper_bound}, has the same behavior as {@link lower_bound}, except - * in the case that the {@link ITreeSet} contains elements equivalent to val: In this case - * {@link lower_bound} returns an iterator pointing to the first of such elements, whereas - * {@link upper_bound} returns an iterator pointing to the element following the last.

- * - * @param val Value to compare. - * - * @return An iterator to the the first element in the container which is not considered to go before - * val, or {@link ITreeSet.end} if all elements are considered to go before val. + * @inheritdoc */ - lower_bound(val: T): SetIterator; + hash(): number; /** - *

Return iterator to upper bound.

- * - *

Returns an iterator pointing to the first element in the container which is considered to go after - * val.

- - *

The function uses its internal comparison object (key_comp) to determine this, returning an - * iterator to the first element for which key_comp(val,element) would return true.

- - *

If the {@code ITreeSet} class is instantiated with the default comparison type (less), the - * function returns an iterator to the first element that is greater than val.

- * - *

A similar member function, {@link lower_bound}, has the same behavior as {@link upper_bound}, except - * in the case that the {@ITreeSet} contains elements equivalent to val: In this case - * {@link lower_bound} returns an iterator pointing to the first of such elements, whereas - * {@link upper_bound} returns an iterator pointing to the element following the last.

- * - * @param val Value to compare. - * - * @return An iterator to the the first element in the container which is considered to go after - * val, or {@link TreeSet.end end} if no elements are considered to go after val. + * @inheritdoc */ - upper_bound(val: T): SetIterator; + swap(obj: SetIterator): void; + } + /** + *

A reverse-iterator of Set.

+ * + *

+ *

+ * + * @param Type of the elements. + * + * @author Jeongho Nam + */ + class SetReverseIterator extends ReverseIterator, SetReverseIterator> { /** - *

Get range of equal elements.

- * - *

Returns the bounds of a range that includes all the elements in the container that are equivalent - * to val.

- * - *

If no matches are found, the range returned has a length of zero, with both iterators pointing to - * the first element that is considered to go after val according to the container's - * internal comparison object (key_comp).

- * - *

Two elements of a multiset are considered equivalent if the container's comparison object returns - * false reflexively (i.e., no matter the order in which the elements are passed as arguments).

- * - * @param key Value to search for. + * Construct from base iterator. * - * @return The function returns a {@link Pair}, whose member {@link Pair.first} is the lower bound of - * the range (the same as {@link lower_bound}), and {@link Pair.second} is the upper bound - * (the same as {@link upper_bound}). + * @param base A reference of the base iterator, which iterates in the opposite direction. */ - equal_range(val: T): Pair, SetIterator>; + constructor(base: SetIterator); /** - *

Return comparison function.

- * - *

Returns a copy of the comparison function used by the container.

- * - *

By default, this is a {@link less} object, which returns the same as operator<.

- * - *

This object determines the order of the elements in the container: it is a function pointer or a function - * object that takes two arguments of the same type as the container elements, and returns true if - * the first argument is considered to go before the second in the strict weak ordering it - * defines, and false otherwise.

- * - *

Two elements of a {@link ITreeSet} are considered equivalent if {@link key_comp} returns false - * reflexively (i.e., no matter the order in which the elements are passed as arguments).

- * - *

In {@link ITreeSet} containers, the keys to sort the elements are the values (T) themselves, - * therefore {@link key_comp} and its sibling member function {@link value_comp} are equivalent.

- * - * @return The comparison function. + * @hidden */ - key_comp(): (x: T, y: T) => boolean; + protected create_neighbor(base: SetIterator): SetReverseIterator; + } +} +declare namespace std.base { + /** + *

An abstract set.

+ * + *

{@link SetContainer SetContainers} are containers that store elements allowing fast retrieval of + * individual elements based on their value.

+ * + *

In an {@link SetContainer}, the value of an element is at the same time its key, used to + * identify it. Keys are immutable, therefore, the elements in an {@link SetContainer} cannot be + * modified once in the container - they can be inserted and removed, though.

+ * + *

{@link SetContainer} stores elements, keeps sequence and enables indexing by inserting elements into a + * {@link List} and registering {@link ListIterator iterators} of the {@link data_ list container} to an index + * table like {@link RBTree tree} or {@link HashBuckets hash-table}.

+ * + *

+ *

+ * + *

Container properties

+ *
+ *
Associative
+ *
+ * Elements in associative containers are referenced by their key and not by their absolute + * position in the container. + *
+ * + *
Set
+ *
The value of an element is also the key used to identify it.
+ * + *
Multiple equivalent keys
+ *
Multiple elements in the container can have equivalent keys.
+ *
+ * + * @param Type of the elements. Each element in a {@link SetContainer} container is also identified + * by this value (each value is itself also the element's key). + * + * @author Jeongho Nam + */ + abstract class MultiSet extends SetContainer { /** - *

Return comparison function.

- * - *

Returns a copy of the comparison function used by the container.

- * - *

By default, this is a {@link less} object, which returns the same as operator<.

- * - *

This object determines the order of the elements in the container: it is a function pointer or a function - * object that takes two arguments of the same type as the container elements, and returns true if - * the first argument is considered to go before the second in the strict weak ordering it - * defines, and false otherwise.

+ *

Insert an element.

* - *

Two elements of a {@link ITreeSet} are considered equivalent if {@link key_comp} returns false - * reflexively (i.e., no matter the order in which the elements are passed as arguments).

+ *

Extends the container by inserting new elements, effectively increasing the container {@link size} by + * the number of elements inserted.

* - *

In {@link ITreeSet} containers, the keys to sort the elements are the values (T) themselves, - * therefore {@link key_comp} and its sibling member function {@link value_comp} are equivalent.

+ * @param key Value to be inserted as an element. * - * @return The comparison function. + * @return An iterator to the newly inserted element. */ - value_comp(): (x: T, y: T) => boolean; + insert(val: T): SetIterator; /** * @inheritdoc */ - is_equal_to(left: SetIterator, right: SetIterator): boolean; + insert(hint: SetIterator, val: T): SetIterator; /** * @inheritdoc */ - is_less(left: SetIterator, right: SetIterator): boolean; + insert(hint: SetReverseIterator, val: T): SetReverseIterator; + /** + * @inheritdoc + */ + insert>(begin: InputIterator, end: InputIterator): void; } } -declare namespace std.base { +declare namespace std.HashMultiSet { + type iterator = std.SetIterator; + type reverse_iterator = std.SetReverseIterator; +} +declare namespace std { /** - *

An abstract unique-map.

+ *

Hashed, unordered Multiset.

* - *

{@link UniqueMap UniqueMaps} are associative containers that store elements formed by a combination of a - * key value (Key) and a mapped value (T), and which allows for fast retrieval of - * individual elements based on their keys.

+ *

{@link HashMultiSet HashMultiSets} are containers that store elements in no particular order, allowing fast + * retrieval of individual elements based on their value, much like {@link HashMultiSet} containers, + * but allowing different elements to have equivalent values.

* - *

In a {@link MapContainer}, the key values are generally used to uniquely identify the elements, - * while the mapped values store the content associated to this key. The types of key and - * mapped value may differ, and are grouped together in member type value_type, which is a - * {@link Pair} type combining both:

+ *

In an {@link HashMultiSet}, the value of an element is at the same time its key, used to + * identify it. Keys are immutable, therefore, the elements in an {@link HashMultiSet} cannot be + * modified once in the container - they can be inserted and removed, though.

* - *

typedef pair value_type;

+ *

Internally, the elements in the {@link HashMultiSet} are not sorted in any particular, but + * organized into buckets depending on their hash values to allow for fast access to individual + * elements directly by their values (with a constant average time complexity on average).

* - *

{@link UniqueMap} stores elements, keeps sequence and enables indexing by inserting elements into a - * {@link List} and registering {@link ListIterator iterators} of the {@link data_ list container} to an index - * table like {@link RBTree tree} or {@link HashBuckets hash-table}.

+ *

Elements with equivalent values are grouped together in the same bucket and in such a way that an + * iterator can iterate through all of them. Iterators in the container are doubly linked iterators.

* - *

- *

+ *

+ *

* *

Container properties

*
*
Associative
- *
- * Elements in associative containers are referenced by their key and not by their absolute position - * in the container. - *
+ *
Elements in associative containers are referenced by their key and not by their absolute + * position in the container.
* - *
Map
- *
- * Each element associates a key to a mapped value: - * Keys are meant to identify the elements whose main content is the mapped value. - *
+ *
Hashed
+ *
Hashed containers organize their elements using hash tables that allow for fast access to elements + * by their key.
* - *
Unique keys
- *
No two elements in the container can have equivalent keys.
+ *
Set
+ *
The value of an element is also the key used to identify it.
+ * + *
Multiple equivalent keys
+ *
The container can hold multiple elements with equivalent keys.
*
* - * @param Type of the keys. Each element in a map is uniquely identified by its key value. - * @param Type of the mapped value. Each element in a map stores some data as its mapped value. + * @param Type of the elements. + * Each element in an {@link UnorderedMultiSet} is also identified by this value.. * + * @reference http://www.cplusplus.com/reference/unordered_set/unordered_multiset * @author Jeongho Nam */ - abstract class UniqueMap extends MapContainer { + class HashMultiSet extends base.MultiSet { + /** + * @hidden + */ + private hash_buckets_; + /** + * Default Constructor. + */ + constructor(); + /** + * Construct from elements. + */ + constructor(items: T[]); + /** + * Copy Constructor. + */ + constructor(container: HashMultiSet); + /** + * Construct from range iterators. + */ + constructor(begin: Iterator, end: Iterator); /** * @inheritdoc */ - count(key: Key): number; + clear(): void; /** - *

Get an element

- * - *

Returns a reference to the mapped value of the element identified with key.

- * - * @param key Key value of the element whose mapped value is accessed. - * - * @throw exception out of range - * - * @return A reference object of the mapped value (_Ty) + * @inheritdoc */ - get(key: Key): T; + find(key: T): SetIterator; /** - *

Set an item as the specified identifier.

- * - *

If the identifier is already in map, change value of the identifier. If not, then insert the object - * with the identifier.

- * - * @param key Key value of the element whose mapped value is accessed. - * @param val Value, the item. + * @inheritdoc */ - set(key: Key, val: T): void; + count(key: T): number; /** - *

Extract an element.

- * - *

Extracts the element pointed to by key and erases it from the {@link UniqueMap}.

- * - * @param key Key value of the element whose mapped value is accessed. - * - * @return A {@link Pair} containing the value pointed to by key. + * @inheritdoc */ - extract(key: Key): Pair; + begin(): SetIterator; /** - *

Extract an element.

- * - *

Extracts the element pointed to by key and erases it from the {@link UniqueMap}.

- * - * @param it An iterator pointing an element to extract. - * - * @return An iterator pointing to the element immediately following it prior to the element being - * erased. If no such element exists,returns {@link end end()}. + * @inheritdoc */ - extract(it: MapIterator): MapIterator; + begin(index: number): SetIterator; /** - *

Extract an element.

- * - *

Extracts the element pointed to by key and erases it from the {@link UniqueMap}.

- * - * @param it An iterator pointing an element to extract. - * - * @return An iterator pointing to the element immediately following it prior to the element being - * erased. If no such element exists,returns {@link end end()}. + * @inheritdoc */ - extract(it: MapReverseIterator): MapReverseIterator; + end(): SetIterator; /** - * @hidden + * @inheritdoc */ - private extract_by_key(key); + end(index: number): SetIterator; /** - * @hidden + * @inheritdoc */ - private extract_by_iterator(it); + rbegin(): SetReverseIterator; /** - * @hidden + * @inheritdoc */ - private extract_by_reverse_iterator(it); + rbegin(index: number): SetReverseIterator; /** - * Construct and insert element. - * - * Inserts a new element in the {@link UniqueMap} if its *key* is unique. This new element is constructed in - * place using args as the arguments for the construction of a *value_type* (which is an object of a - * {@link Pair} type). - * - * The insertion only takes place if no other element in the container has a *key equivalent* to the one - * being emplaced (*keys* in a {@link UniqueMap} container are unique). - * - * If inserted, this effectively increases the container {@link size} by one. - * - * A similar member function exists, {@link insert}, which either copies or moves existing objects into the - * container. - * - * @param key The key used both to look up and to insert if not found. - * @param value Value, the item. - * - * @return If the function successfully inserts the element (because no equivalent element existed already in - * the {@link UniqueMap}), the function returns a {@link Pair} of an {@link MapIterator iterator} to - * the newly inserted element and a value of true. Otherwise, it returns an - * {@link MapIterator iterator} to the equivalent element within the container and a value of false. + * @inheritdoc */ - emplace(key: Key, value: T): Pair, boolean>; + rend(): SetReverseIterator; /** - * Construct and insert element. - * - * Inserts a new element in the {@link UniqueMap} if its *key* is unique. This new element is constructed in - * place using args as the arguments for the construction of a *value_type* (which is an object of a - * {@link Pair} type). - * - * The insertion only takes place if no other element in the container has a *key equivalent* to the one - * being emplaced (*keys* in a {@link UniqueMap} container are unique). - * - * If inserted, this effectively increases the container {@link size} by one. - * - * A similar member function exists, {@link insert}, which either copies or moves existing objects into the - * container. - * - * @param pair A single argument of a {@link Pair} type with a value for the *key* as - * {@link Pair.first first} member, and a *value* for the mapped value as - * {@link Pair.second second}. - * - * @return If the function successfully inserts the element (because no equivalent element existed already in - * the {@link UniqueMap}), the function returns a {@link Pair} of an {@link MapIterator iterator} to - * the newly inserted element and a value of true. Otherwise, it returns an - * {@link MapIterator iterator} to the equivalent element within the container and a value of false. + * @inheritdoc */ - emplace(pair: Pair): Pair, boolean>; + rend(index: number): SetReverseIterator; /** - *

Insert an element.

- * - *

Extends the container by inserting new elements, effectively increasing the container {@link size} by - * one.

- * - *

Because element keys in a {@link UniqueMap} are unique, the insertion operation checks whether - * each inserted element has a key equivalent to the one of an element already in the container, and - * if so, the element is not inserted, returning an iterator to this existing element (if the function - * returns a value).

- * - *

For a similar container allowing for duplicate elements, see {@link MultiMap}.

- * - * @param pair A single argument of a {@link Pair} type with a value for the *key* as - * {@link Pair.first first} member, and a *value* for the mapped value as - * {@link Pair.second second}. - * - * @return A {@link Pair}, with its member {@link Pair.first} set to an iterator pointing to either the newly - * inserted element or to the element with an equivalent key in the {@link UniqueMap}. The - * {@link Pair.second} element in the {@link Pair} is set to true if a new element was inserted or - * false if an equivalent key already existed. + * @inheritdoc */ - insert(pair: Pair): Pair, boolean>; + bucket_count(): number; /** - *

Insert an element.

- * - *

Extends the container by inserting a new element, effectively increasing the container size by the - * number of elements inserted.

- * - *

Because element keys in a {@link UniqueMap} are unique, the insertion operation checks whether - * each inserted element has a key equivalent to the one of an element already in the container, and - * if so, the element is not inserted, returning an iterator to this existing element (if the function - * returns a value).

- * - *

For a similar container allowing for duplicate elements, see {@link MultiMap}.

- * - * @param tuple Tuple represensts the {@link Pair} to be inserted as an element. - * - * @return A {@link Pair}, with its member {@link Pair.first} set to an iterator pointing to either the newly - * inserted element or to the element with an equivalent key in the {@link UniqueMap}. The - * {@link Pair.second} element in the {@link Pair} is set to true if a new element was inserted or - * false if an equivalent key already existed. + * @inheritdoc */ - insert(tuple: [L, U]): Pair, boolean>; + bucket_size(n: number): number; /** * @inheritdoc */ - insert(hint: MapIterator, pair: Pair): MapIterator; + max_load_factor(): number; /** * @inheritdoc */ - insert(hint: MapReverseIterator, pair: Pair): MapReverseIterator; + max_load_factor(z: number): void; /** * @inheritdoc */ - insert(hint: MapIterator, tuple: [L, U]): MapIterator; + bucket(key: T): number; /** * @inheritdoc */ - insert(hint: MapReverseIterator, tuple: [L, U]): MapReverseIterator; + reserve(n: number): void; /** * @inheritdoc */ - insert>>(first: InputIterator, last: InputIterator): void; + rehash(n: number): void; /** - *

Insert or assign an element.

- * - *

Inserts an element or assigns to the current element if the key already exists.

- * - *

Because element keys in a {@link UniqueMap} are unique, the insertion operation checks whether - * each inserted element has a key equivalent to the one of an element already in the container, and - * if so, the element is assigned, returning an iterator to this existing element (if the function returns a - * value).

- * - *

For a similar container allowing for duplicate elements, see {@link MultiMap}.

- * - * @param key The key used both to look up and to insert if not found. - * @param value Value, the item. - * - * @return A {@link Pair}, with its member {@link Pair.first} set to an iterator pointing to either the newly - * inserted element or to the element with an equivalent key in the {@link UniqueMap}. The - * {@link Pair.second} element in the {@link Pair} is set to true if a new element was inserted or - * false if an equivalent key already existed so the value is assigned. + * @hidden */ - insert_or_assign(key: Key, value: T): Pair, boolean>; + protected _Insert_by_val(val: T): any; /** - *

Insert or assign an element.

- * - *

Inserts an element or assigns to the current element if the key already exists.

- * - *

Because element keys in a {@link UniqueMap} are unique, the insertion operation checks whether - * each inserted element has a key equivalent to the one of an element already in the container, and - * if so, the element is assigned, returning an iterator to this existing element (if the function returns a - * value).

- * - *

For a similar container allowing for duplicate elements, see {@link MultiMap}.

- * - * @param hint Hint for the position where the element can be inserted. - * @param key The key used both to look up and to insert if not found. - * @param value Value, the item. - * - * @return An iterator pointing to either the newly inserted element or to the element that already had an - * equivalent key in the {@link UniqueMap}. + * @hidden */ - insert_or_assign(hint: MapIterator, key: Key, value: T): MapIterator; + protected _Insert_by_hint(hint: SetIterator, val: T): SetIterator; /** - *

Insert or assign an element.

- * - *

Inserts an element or assigns to the current element if the key already exists.

- * - *

Because element keys in a {@link UniqueMap} are unique, the insertion operation checks whether - * each inserted element has a key equivalent to the one of an element already in the container, and - * if so, the element is assigned, returning an iterator to this existing element (if the function returns a - * value).

+ * @hidden + */ + protected _Insert_by_range>(first: InputIterator, last: InputIterator): void; + /** + * @inheritdoc + */ + protected _Handle_insert(first: SetIterator, last: SetIterator): void; + /** + * @inheritdoc + */ + protected _Handle_erase(first: SetIterator, last: SetIterator): void; + /** + *

Swap content.

* - *

For a similar container allowing for duplicate elements, see {@link MultiMap}.

+ *

Exchanges the content of the container by the content of obj, which is another + * {@link HashMultiSet set} of the same type. Sizes abd container type may differ.

* - * @param hint Hint for the position where the element can be inserted. - * @param key The key used both to look up and to insert if not found. - * @param value Value, the item. + *

After the call to this member function, the elements in this container are those which were + * in obj before the call, and the elements of obj are those which were in this. All + * iterators, references and pointers remain valid for the swapped objects.

* - * @return An iterator pointing to either the newly inserted element or to the element that already had an - * equivalent key in the {@link UniqueMap}. - */ - insert_or_assign(hint: MapReverseIterator, key: Key, value: T): MapReverseIterator; - /** - * @hidden + *

Notice that a non-member function exists with the same name, {@link std.swap swap}, overloading that + * algorithm with an optimization that behaves like this member function.

+ * + * @param obj Another {@link HashMultiSet set container} of the same type of elements as this (i.e., + * with the same template parameters, Key and T) whose content is swapped + * with that of this {@link HashMultiSet container}. */ - private insert_or_assign_with_key_value(key, value); + swap(obj: HashMultiSet): void; /** - * @hidden + * @inheritdoc */ - private insert_or_assign_with_hint(hint, key, value); + swap(obj: base.IContainer): void; } } declare namespace std.base { @@ -7236,137 +6529,250 @@ declare namespace std.base { insert>(begin: InputIterator, end: InputIterator): void; } } -declare namespace std.base { +declare namespace std.HashSet { + type iterator = std.SetIterator; + type reverse_iterator = std.SetReverseIterator; +} +declare namespace std { /** - *

A node in an XTree.

+ *

Hashed, unordered set.

* - * @param Type of elements. + *

{@link HashSet}s are containers that store unique elements in no particular order, and which + * allow for fast retrieval of individual elements based on their value.

* - * @inventor Rudolf Bayer - * @author Migrated by Jeongho Nam + *

In an {@link HashSet}, the value of an element is at the same time its key, that + * identifies it uniquely. Keys are immutable, therefore, the elements in an {@link HashSet} cannot be + * modified once in the container - they can be inserted and removed, though.

+ * + *

Internally, the elements in the {@link HashSet} are not sorted in any particular order, but + * organized into buckets depending on their hash values to allow for fast access to individual elements + * directly by their values (with a constant average time complexity on average).

+ * + *

{@link HashSet} containers are faster than {@link TreeSet} containers to access individual + * elements by their key, although they are generally less efficient for range iteration through a + * subset of their elements.

+ * + *

+ *

+ * + *

Container properties

+ *
+ *
Associative
+ *
Elements in associative containers are referenced by their key and not by their absolute + * position in the container.
+ * + *
Hashed
+ *
Hashed containers organize their elements using hash tables that allow for fast access to elements + * by their key.
+ * + *
Set
+ *
The value of an element is also the key used to identify it.
+ * + *
Unique keys
+ *
No two elements in the container can have equivalent keys.
+ *
+ * + * @param Type of the elements. + * Each element in an {@link HashSet} is also uniquely identified by this value. + * + * @reference http://www.cplusplus.com/reference/unordered_set/unordered_set + * @author Jeongho Nam */ - class XTreeNode { + class HashSet extends base.UniqueSet implements base.IHashSet { /** - * Parent of the node. + * @hidden */ - parent: XTreeNode; + private hash_buckets_; /** - * Left child in the node. + * Default Constructor. */ - left: XTreeNode; + constructor(); /** - * Right child in the node. + * Construct from elements. */ - right: XTreeNode; + constructor(items: T[]); /** - * Value stored in the node. + * Copy Constructor. */ - value: T; + constructor(container: HashSet); /** - * Color of the node. + * Construct from range iterators. */ - color: Color; + constructor(begin: Iterator, end: Iterator); /** - * Construct from value and color of node. - * - * @param value Value to be stored in. - * @param color Color of the node, red or black. + * @inheritdoc */ - constructor(value: T, color: Color); + clear(): void; /** - * Get grand-parent. + * @inheritdoc */ - readonly grand_parent: XTreeNode; + find(key: T): SetIterator; /** - * Get sibling, opposite side node in same parent. + * @inheritdoc + */ + begin(): SetIterator; + /** + * @inheritdoc */ - readonly sibling: XTreeNode; + begin(index: number): SetIterator; /** - * Get uncle, parent's sibling. + * @inheritdoc + */ + end(): SetIterator; + /** + * @inheritdoc + */ + end(index: number): SetIterator; + /** + * @inheritdoc + */ + rbegin(): SetReverseIterator; + /** + * @inheritdoc + */ + rbegin(index: number): SetReverseIterator; + /** + * @inheritdoc + */ + rend(): SetReverseIterator; + /** + * @inheritdoc + */ + rend(index: number): SetReverseIterator; + /** + * @inheritdoc + */ + bucket_count(): number; + /** + * @inheritdoc + */ + bucket_size(n: number): number; + /** + * @inheritdoc + */ + max_load_factor(): number; + /** + * @inheritdoc + */ + max_load_factor(z: number): void; + /** + * @inheritdoc + */ + bucket(key: T): number; + /** + * @inheritdoc + */ + reserve(n: number): void; + /** + * @inheritdoc + */ + rehash(n: number): void; + /** + * @hidden + */ + protected _Insert_by_val(val: T): any; + /** + * @hidden + */ + protected _Insert_by_hint(hint: SetIterator, val: T): SetIterator; + /** + * @hidden + */ + protected _Insert_by_range>(first: InputIterator, last: InputIterator): void; + /** + * @inheritdoc + */ + protected _Handle_insert(first: SetIterator, last: SetIterator): void; + /** + * @inheritdoc + */ + protected _Handle_erase(first: SetIterator, last: SetIterator): void; + /** + *

Swap content.

+ * + *

Exchanges the content of the container by the content of obj, which is another + * {@link HashSet set} of the same type. Sizes abd container type may differ.

+ * + *

After the call to this member function, the elements in this container are those which were + * in obj before the call, and the elements of obj are those which were in this. All + * iterators, references and pointers remain valid for the swapped objects.

+ * + *

Notice that a non-member function exists with the same name, {@link std.swap swap}, overloading that + * algorithm with an optimization that behaves like this member function.

+ * + * @param obj Another {@link HashSet set container} of the same type of elements as this (i.e., + * with the same template parameters, Key and T) whose content is swapped + * with that of this {@link HashSet container}. + */ + swap(obj: HashSet): void; + /** + * @inheritdoc */ - readonly uncle: XTreeNode; + swap(obj: base.IContainer): void; } } -declare namespace std.Deque { - type iterator = std.DequeIterator; - type reverse_iterator = std.DequeReverseIterator; +declare namespace std.List { + type iterator = std.ListIterator; + type reverse_iterator = std.ListReverseIterator; } declare namespace std { /** - *

Double ended queue.

+ *

Doubly linked list.

* - *

{@link Deque} (usually pronounced like "deck") is an irregular acronym of - * double-ended queue. Double-ended queues are sequence containers with dynamic sizes that can be - * expanded or contracted on both ends (either its front or its back).

+ *

{@link List}s are sequence containers that allow constant time insert and erase operations anywhere within the + * sequence, and iteration in both directions.

* - *

Specific libraries may implement deques in different ways, generally as some form of dynamic array. But in any - * case, they allow for the individual elements to be accessed directly through random access iterators, with storage - * handled automatically by expanding and contracting the container as needed.

+ *

List containers are implemented as doubly-linked lists; Doubly linked lists can store each of the elements they + * contain in different and unrelated storage locations. The ordering is kept internally by the association to each + * element of a link to the element preceding it and a link to the element following it.

* - *

Therefore, they provide a functionality similar to vectors, but with efficient insertion and deletion of - * elements also at the beginning of the sequence, and not only at its end. But, unlike {@link Vector Vectors}, - * {@link Deque Deques} are not guaranteed to store all its elements in contiguous storage locations: accessing - * elements in a deque by offsetting a pointer to another element causes undefined behavior.

+ *

They are very similar to forward_list: The main difference being that forward_list objects are single-linked + * lists, and thus they can only be iterated forwards, in exchange for being somewhat smaller and more efficient.

* - *

Both {@link Vector}s and {@link Deque}s provide a very similar interface and can be used for similar purposes, - * but internally both work in quite different ways: While {@link Vector}s use a single array that needs to be - * occasionally reallocated for growth, the elements of a {@link Deque} can be scattered in different chunks of - * storage, with the container keeping the necessary information internally to provide direct access to any of its - * elements in constant time and with a uniform sequential interface (through iterators). Therefore, - * {@link Deque Deques} are a little more complex internally than {@link Vector}s, but this allows them to grow more - * efficiently under certain circumstances, especially with very long sequences, where reallocations become more - * expensive.

+ *

Compared to other base standard sequence containers (array, vector and deque), lists perform generally better + * in inserting, extracting and moving elements in any position within the container for which an iterator has already + * been obtained, and therefore also in algorithms that make intensive use of these, like sorting algorithms.

* - *

For operations that involve frequent insertion or removals of elements at positions other than the beginning or - * the end, {@link Deque Deques} perform worse and have less consistent iterators and references than - * {@link List Lists}.

+ *

The main drawback of lists and forward_lists compared to these other sequence containers is that they lack + * direct access to the elements by their position; For example, to access the sixth element in a list, one has to + * iterate from a known position (like the beginning or the end) to that position, which takes linear time in the + * distance between these. They also consume some extra memory to keep the linking information associated to each + * element (which may be an important factor for large lists of small-sized elements).

* *

- * + * *

* *

Container properties

*
- *
Sequence
- *
Elements in sequence containers are ordered in a strict linear sequence. Individual elements - * are accessed by their position in this sequence.
- * - *
Dynamic array
- *
Generally implemented as a dynamic array, it allows direct access to any element in the - * sequence and provides relatively fast addition/removal of elements at the beginning or the end - * of the sequence.
+ *
Sequence
+ *
Elements in sequence containers are ordered in a strict linear sequence. Individual elements are accessed by + * their position in this sequence.
+ * + *
Doubly-linked list
+ *
Each element keeps information on how to locate the next and the previous elements, allowing constant time + * insert and erase operations before or after a specific element (even of entire ranges), but no direct random + * access.
*
* * @param Type of the elements. * - * @reference http://www.cplusplus.com/reference/deque/deque/ + * @reference http://www.cplusplus.com/reference/list/list/ * @author Jeongho Nam */ - class Deque extends base.Container implements base.IArrayContainer, base.IDequeContainer { - /** - * @hidden - */ - private static readonly ROW; + class List extends base.Container implements base.IDequeContainer { /** * @hidden */ - private static readonly MIN_CAPACITY; + private begin_; /** * @hidden */ - private matrix_; + private end_; /** * @hidden */ private size_; - /** - * @hidden - */ - private capacity_; - /** - * @hidden - */ - private get_col_size(); /** *

Default Constructor.

* @@ -7399,7 +6805,7 @@ declare namespace std { * @param container Another container object of the same type (with the same class template * arguments T), whose contents are either copied or acquired. */ - constructor(container: Deque); + constructor(container: List); /** *

Range Constructor.

* @@ -7410,10 +6816,6 @@ declare namespace std { * @param end Input interator of the final position in a sequence. */ constructor(begin: Iterator, end: Iterator); - /** - * @inheritdoc - */ - assign>(begin: InputIterator, end: InputIterator): void; /** * @inheritdoc */ @@ -7421,7 +6823,7 @@ declare namespace std { /** * @inheritdoc */ - reserve(capacity: number): void; + assign>(begin: InputIterator, end: InputIterator): void; /** * @inheritdoc */ @@ -7429,39 +6831,23 @@ declare namespace std { /** * @inheritdoc */ - begin(): DequeIterator; + begin(): ListIterator; /** * @inheritdoc */ - end(): DequeIterator; + end(): ListIterator; /** * @inheritdoc */ - rbegin(): DequeReverseIterator; + rbegin(): ListReverseIterator; /** * @inheritdoc */ - rend(): DequeReverseIterator; + rend(): ListReverseIterator; /** * @inheritdoc */ size(): number; - /** - * @inheritdoc - */ - empty(): boolean; - /** - * @inheritdoc - */ - capacity(): number; - /** - * @inheritdoc - */ - at(index: number): T; - /** - * @inheritdoc - */ - set(index: number, val: T): void; /** * @inheritdoc */ @@ -7470,16 +6856,10 @@ declare namespace std { * @inheritdoc */ back(): T; - /** - // Fetch row and column's index. - /** - * @hidden - */ - private fetch_index(index); /** * @inheritdoc */ - push(...items: T[]): number; + push(...items: U[]): number; /** * @inheritdoc */ @@ -7497,1251 +6877,1407 @@ declare namespace std { */ pop_back(): void; /** - * @inheritdoc - */ - insert(position: DequeIterator, val: T): DequeIterator; - /** - * @inheritdoc - */ - insert(position: DequeIterator, n: number, val: T): DequeIterator; - /** - * @inheritdoc - */ - insert>(position: DequeIterator, begin: InputIterator, end: InputIterator): DequeIterator; - /** - * @inheritdoc - */ - insert(position: DequeReverseIterator, val: T): DequeReverseIterator; - /** - * @inheritdoc - */ - insert(position: DequeReverseIterator, n: number, val: T): DequeReverseIterator; - /** - * @inheritdoc - */ - insert>(position: DequeReverseIterator, begin: InputIterator, end: InputIterator): DequeReverseIterator; - /** - * @hidden - */ - private insert_by_val(position, val); - /** - * @hidden - */ - protected _Insert_by_repeating_val(position: DequeIterator, n: number, val: T): DequeIterator; - /** - * @hidden - */ - protected _Insert_by_range>(position: DequeIterator, begin: InputIterator, end: InputIterator): DequeIterator; - /** - * @hidden - */ - private insert_by_items(position, items); - /** - * @inheritdoc - */ - erase(position: DequeIterator): DequeIterator; - /** - * @inheritdoc - */ - erase(first: DequeIterator, last: DequeIterator): DequeIterator; - /** - * @inheritdoc - */ - erase(position: DequeReverseIterator): DequeReverseIterator; - /** - * @inheritdoc - */ - erase(first: DequeReverseIterator, last: DequeReverseIterator): DequeReverseIterator; - /** - * @hidden - */ - protected _Erase_by_range(first: DequeIterator, last: DequeIterator): DequeIterator; - /** - *

Swap content.

+ *

Insert an element.

* - *

Exchanges the content of the container by the content of obj, which is another - * {@link Deque container} object with same type of elements. Sizes and container type may differ.

+ *

The container is extended by inserting a new element before the element at the specified + * position. This effectively increases the {@link List.size List size} by the amount of elements + * inserted.

* - *

After the call to this member function, the elements in this container are those which were in obj - * before the call, and the elements of obj are those which were in this. All iterators, references and - * pointers remain valid for the swapped objects.

+ *

Unlike other standard sequence containers, {@link List} is specifically designed to be efficient + * inserting and removing elements in any position, even in the middle of the sequence.

* - *

Notice that a non-member function exists with the same name, {@link std.swap swap}, overloading that - * algorithm with an optimization that behaves like this member function.

+ * @param position Position in the container where the new element is inserted. + * {@link iterator}> is a member type, defined as a + * {@link ListIterator bidirectional iterator} type that points to elements. + * @param val Value to be inserted as an element. * - * @param obj Another {@link Deque container} of the same type of elements (i.e., instantiated - * with the same template parameter, T) whose content is swapped with that of this - * {@link container Deque}. - */ - swap(obj: Deque): void; - /** - * @inheritdoc + * @return An iterator that points to the newly inserted element; val. */ - swap(obj: base.IContainer): void; - } -} -declare namespace std { - /** - *

An iterator of {@link Deque}.

- * - *

- * - *

- * - * @author Jeongho Nam - */ - class DequeIterator extends Iterator implements base.IArrayIterator { + insert(position: ListIterator, val: T): ListIterator; /** - * Sequence number of iterator in the source {@link Deque}. + *

Insert elements by repeated filling.

+ * + *

The container is extended by inserting a new element before the element at the specified + * position. This effectively increases the {@link List.size List size} by the amount of elements + * inserted.

+ * + *

Unlike other standard sequence containers, {@link List} is specifically designed to be efficient + * inserting and removing elements in any position, even in the middle of the sequence.

+ * + * @param position Position in the container where the new elements are inserted. The {@link iterator} is a + * member type, defined as a {@link ListIterator bidirectional iterator} type that points to + * elements. + * @param size Number of elements to insert. + * @param val Value to be inserted as an element. + * + * @return An iterator that points to the first of the newly inserted elements. */ - private index_; + insert(position: ListIterator, size: number, val: T): ListIterator; /** - *

Construct from the source {@link Deque container}.

+ *

Insert elements by range iterators.

* - *

Note

- *

Do not create the iterator directly, by yourself.

- *

Use {@link Deque.begin begin()}, {@link Deque.end end()} in {@link Deque container} instead.

+ *

The container is extended by inserting a new element before the element at the specified + * position. This effectively increases the {@link List.size List size} by the amount of elements + * inserted.

* - * @param source The source {@link Deque container} to reference. - * @param index Sequence number of the element in the source {@link Deque}. + *

Unlike other standard sequence containers, {@link List} is specifically designed to be efficient + * inserting and removing elements in any position, even in the middle of the sequence.

+ * + * @param position Position in the container where the new elements are inserted. The {@link iterator} is a + * member type, defined as a {@link ListIterator bidirectional iterator} type that points to + * elements. + * @param begin An iterator specifying range of the begining element. + * @param end An iterator specifying range of the ending element. + * + * @return An iterator that points to the first of the newly inserted elements. */ - constructor(source: Deque, index: number); + insert>(position: ListIterator, begin: InputIterator, end: InputIterator): ListIterator; /** - * @hidden + *

Insert an element.

+ * + *

The container is extended by inserting a new element before the element at the specified + * position. This effectively increases the {@link List.size List size} by the amount of elements + * inserted.

+ * + *

Unlike other standard sequence containers, {@link List} is specifically designed to be efficient + * inserting and removing elements in any position, even in the middle of the sequence.

+ * + * @param position Position in the container where the new element is inserted. + * {@link iterator}> is a member type, defined as a + * {@link ListReverseIterator bidirectional iterator} type that points to elements. + * @param val Value to be inserted as an element. + * + * @return An iterator that points to the newly inserted element; val. */ - private readonly deque; + insert(position: ListReverseIterator, val: T): ListReverseIterator; /** - * @inheritdoc + *

Insert elements by repeated filling.

+ * + *

The container is extended by inserting a new element before the element at the specified + * position. This effectively increases the {@link List.size List size} by the amount of elements + * inserted.

+ * + *

Unlike other standard sequence containers, {@link List} is specifically designed to be efficient + * inserting and removing elements in any position, even in the middle of the sequence.

+ * + * @param position Position in the container where the new elements are inserted. The {@link iterator} is a + * member type, defined as a {@link ListReverseIterator bidirectional iterator} type that points to + * elements. + * @param size Number of elements to insert. + * @param val Value to be inserted as an element. + * + * @return An iterator that points to the first of the newly inserted elements. */ + insert(position: ListReverseIterator, size: number, val: T): ListReverseIterator; /** - * Set value of the iterator is pointing to. + *

Insert elements by range iterators.

+ * + *

The container is extended by inserting a new element before the element at the specified + * position. This effectively increases the {@link List.size List size} by the amount of elements + * inserted.

+ * + *

Unlike other standard sequence containers, {@link List} is specifically designed to be efficient + * inserting and removing elements in any position, even in the middle of the sequence.

+ * + * @param position Position in the container where the new elements are inserted. The {@link iterator} is a + * member type, defined as a {@link ListReverseIterator bidirectional iterator} type that points to + * elements. + * @param begin An iterator specifying range of the begining element. + * @param end An iterator specifying range of the ending element. * - * @param val Value to set. + * @return An iterator that points to the first of the newly inserted elements. */ - value: T; + insert>(position: ListReverseIterator, begin: InputIterator, end: InputIterator): ListReverseIterator; /** - * @inheritdoc + * @hidden */ - readonly index: number; + private insert_by_val(position, val); /** - * @inheritdoc + * @hidden */ - prev(): DequeIterator; + protected _Insert_by_repeating_val(position: ListIterator, size: number, val: T): ListIterator; /** - * @inheritdoc + * @hidden */ - next(): DequeIterator; + protected _Insert_by_range>(position: ListIterator, begin: InputIterator, end: InputIterator): ListIterator; /** - * @inheritdoc + *

Erase an element.

+ * + *

Removes from the {@link List} either a single element; position.

+ * + *

This effectively reduces the container size by the number of element removed.

+ * + *

Unlike other standard sequence containers, {@link List} objects are specifically designed to be + * efficient inserting and removing elements in any position, even in the middle of the sequence.

+ * + * @param position Iterator pointing to a single element to be removed from the {@link List}. + * + * @return An iterator pointing to the element that followed the last element erased by the function call. + * This is the {@link end end()} if the operation erased the last element in the sequence. */ - advance(n: number): DequeIterator; + erase(position: ListIterator): ListIterator; /** - *

Whether an iterator is equal with the iterator.

+ *

Erase elements.

* - *

Compare two iterators and returns whether they are equal or not.

+ *

Removes from the {@link List} container a range of elements.

* - *

Note

- *

Iterator's equal_to() only compare souce container and index number.

+ *

This effectively reduces the container {@link size} by the number of elements removed.

* - *

Although elements in a pair, key and value are equal_to, if the source map or - * index number is different, then the {@link equal_to equal_to()} will return false. If you want to - * compare the elements of a pair, compare them directly by yourself.

+ *

Unlike other standard sequence containers, {@link List} objects are specifically designed to be + * efficient inserting and removing elements in any position, even in the middle of the sequence.

* - * @param obj An iterator to compare - * @return Indicates whether equal or not. + * @param begin An iterator specifying a range of beginning to erase. + * @param end An iterator specifying a range of end to erase. + * + * @return An iterator pointing to the element that followed the last element erased by the function call. + * This is the {@link end end()} if the operation erased the last element in the sequence. */ - equal_to(obj: DequeIterator): boolean; + erase(begin: ListIterator, end: ListIterator): ListIterator; /** - * @inheritdoc + *

Erase an element.

+ * + *

Removes from the {@link List} either a single element; position.

+ * + *

This effectively reduces the container size by the number of element removed.

+ * + *

Unlike other standard sequence containers, {@link List} objects are specifically designed to be + * efficient inserting and removing elements in any position, even in the middle of the sequence.

+ * + * @param position Iterator pointing to a single element to be removed from the {@link List}. + * + * @return An iterator pointing to the element that followed the last element erased by the function call. + * This is the {@link rend rend()} if the operation erased the last element in the sequence. */ - swap(obj: DequeIterator): void; - } -} -declare namespace std { - /** - *

A reverse-iterator of Deque.

- * - *

- * - *

- * - * @param Type of the elements. - * - * @author Jeongho Nam - */ - class DequeReverseIterator extends ReverseIterator, DequeReverseIterator> implements base.IArrayIterator { + erase(position: ListReverseIterator): ListReverseIterator; /** - * Construct from base iterator. + *

Erase elements.

* - * @param base A reference of the base iterator, which iterates in the opposite direction. + *

Removes from the {@link List} container a range of elements.

+ * + *

This effectively reduces the container {@link size} by the number of elements removed.

+ * + *

Unlike other standard sequence containers, {@link List} objects are specifically designed to be + * efficient inserting and removing elements in any position, even in the middle of the sequence.

+ * + * @param begin An iterator specifying a range of beginning to erase. + * @param end An iterator specifying a range of end to erase. + * + * @return An iterator pointing to the element that followed the last element erased by the function call. + * This is the {@link rend rend()} if the operation erased the last element in the sequence. */ - constructor(base: DequeIterator); + erase(begin: ListReverseIterator, end: ListReverseIterator): ListReverseIterator; /** * @hidden */ - protected create_neighbor(base: DequeIterator): DequeReverseIterator; + protected _Erase_by_range(first: ListIterator, last: ListIterator): ListIterator; /** - * @inheritdoc + *

Remove duplicate values.

+ * + *

Removes all but the first element from every consecutive group of equal elements in the

+ * + *

Notice that an element is only removed from the {@link List} container if it compares equal to the + * element immediately preceding it. Thus, this function is especially useful for sorted lists.

*/ + unique(): void; /** - * Set value of the iterator is pointing to. + *

Remove duplicate values.

* - * @param val Value to set. + *

Removes all but the first element from every consecutive group of equal elements in the

+ * + *

The argument binary_pred is a specific comparison function that determine the uniqueness + * of an element. In fact, any behavior can be implemented (and not only an equality comparison), but notice + * that the function will call binary_pred(it.value, it.prev().value) for all pairs of elements + * (where it is an iterator to an element, starting from the second) and remove it + * from the {@link List} if the predicate returns true. + * + *

Notice that an element is only removed from the {@link List} container if it compares equal to the + * element immediately preceding it. Thus, this function is especially useful for sorted lists.

+ * + * @param binary_pred Binary predicate that, taking two values of the same type than those contained in the + * {@link List}, returns true to remove the element passed as first argument + * from the container, and false otherwise. This shall be a function pointer + * or a function object. */ - value: T; + unique(binary_pred: (left: T, right: T) => boolean): void; /** - * Get index. + *

Remove elements with specific value.

+ * + *

Removes from the container all the elements that compare equal to val. This calls the + * destructor of these objects and reduces the container {@link size} by the number of elements removed.

+ * + *

Unlike member function {@link List.erase}, which erases elements by their position (using an + * iterator), this function ({@link List.remove}) removes elements by their value.

+ * + *

A similar function, {@link List.remove_if}, exists, which allows for a condition other than an + * equality comparison to determine whether an element is removed.

+ * + * @param val Value of the elements to be removed. */ - readonly index: number; - } -} -declare namespace std { - /** - *

Function handling termination on exception

- * - *

Calls the current terminate handler.

- * - *

By default, the terminate handler calls abort. But this behavior can be redefined by calling - * {@link set_terminate}.

- * - *

This function is automatically called when no catch handler can be found for a thrown exception, - * or for some other exceptional circumstance that makes impossible to continue the exception handling process.

- * - *

This function is provided so that the terminate handler can be explicitly called by a program that needs to - * abnormally terminate, and works even if {@link set_terminate} has not been used to set a custom terminate handler - * (calling abort in this case).

- */ - function terminate(): void; - /** - *

Set terminate handler function.

- * - *

A terminate handler function is a function automatically called when the exception handling process has - * to be abandoned for some reason. This happens when no catch handler can be found for a thrown exception, or for - * some other exceptional circumstance that makes impossible to continue the exception handling process.

- * - *

Before this function is called by the program for the first time, the default behavior is to call abort.

- * - *

A program may explicitly call the current terminate handler function by calling {@link terminate}.

- * - * @param f Function that takes no parameters and returns no value (void). - */ - function set_terminate(f: () => void): void; - /** - *

Get terminate handler function.

- * - *

The terminate handler function is automatically called when no catch handler can be found - * for a thrown exception, or for some other exceptional circumstance that makes impossible to continue the exception - * handling process.

- * - *

If no such function has been set by a previous call to {@link set_terminate}, the function returns a - * null-pointer.

- * - * @return If {@link set_terminate} has previously been called by the program, the function returns the current - * terminate handler function. Otherwise, it returns a null-pointer. - */ - function get_terminate(): () => void; - /** - *

Standard exception class.

- * - *

Base class for standard exceptions.

- * - *

All objects thrown by components of the standard library are derived from this class. - * Therefore, all standard exceptions can be caught by catching this type by reference.

- * - *

- *

- * - * @reference http://www.cplusplus.com/reference/exception/exception - * @author Jeongho Nam - */ - class Exception extends Error { + remove(val: T): void; /** - * A message representing specification about the Exception. + *

Remove elements fulfilling condition.

+ * + *

Removes from the container all the elements for which pred returns true. This + * calls the destructor of these objects and reduces the container {@link size} by the number of elements + * removed.

+ * + *

The function calls pred(it.value) for each element (where it is an iterator + * to that element). Any of the elements in the list for which this returns true, are removed + * from the

+ * + * @param pred Unary predicate that, taking a value of the same type as those contained in the forward_list + * object, returns true for those values to be removed from the container, and + * false for those remaining. This can either be a function pointer or a function + * object. */ - private description; + remove_if(pred: (val: T) => boolean): void; /** - * Default Constructor. + *

Merge sorted {@link List Lists}.

+ * + *

Merges obj into the {@link List} by transferring all of its elements at their respective + * ordered positions into the container (both containers shall already be ordered). + *

+ * + *

This effectively removes all the elements in obj (which becomes {@link empty}), and inserts + * them into their ordered position within container (which expands in {@link size} by the number of elements + * transferred). The operation is performed without constructing nor destroying any element: they are + * transferred, no matter whether obj is an lvalue or an rvalue, or whether the value_type supports + * move-construction or not.

+ * + *

This function requires that the {@link List} containers have their elements already ordered by value + * ({@link less}) before the call. For an alternative on unordered {@link List Lists}, see + * {@link List.splice}.

+ * + *

Assuming such ordering, each element of obj is inserted at the position that corresponds to its + * value according to the strict weak ordering defined by {@link less}. The resulting order of equivalent + * elements is stable (i.e., equivalent elements preserve the relative order they had before the call, and + * existing elements precede those equivalent inserted from obj).

+ * + * The function does nothing if this == obj. + * + * @param obj A {@link List} object of the same type (i.e., with the same template parameters, T). + * Note that this function modifies obj no matter whether an lvalue or rvalue reference is + * passed. + */ + merge(obj: List): void; + /** + *

Merge sorted {@link List Lists}.

+ * + *

Merges obj into the {@link List} by transferring all of its elements at their respective + * ordered positions into the container (both containers shall already be ordered). + *

+ * + *

This effectively removes all the elements in obj (which becomes {@link empty}), and inserts + * them into their ordered position within container (which expands in {@link size} by the number of elements + * transferred). The operation is performed without constructing nor destroying any element: they are + * transferred, no matter whether obj is an lvalue or an rvalue, or whether the value_type supports + * move-construction or not.

+ * + *

The argument compare is a specific predicate to perform the comparison operation between + * elements. This comparison shall produce a strict weak ordering of the elements (i.e., a consistent + * transitive comparison, without considering its reflexiveness). + * + *

This function requires that the {@link List} containers have their elements already ordered by + * compare before the call. For an alternative on unordered {@link List Lists}, see + * {@link List.splice}.

+ * + *

Assuming such ordering, each element of obj is inserted at the position that corresponds to its + * value according to the strict weak ordering defined by compare. The resulting order of equivalent + * elements is stable (i.e., equivalent elements preserve the relative order they had before the call, and + * existing elements precede those equivalent inserted from obj).

+ * + * The function does nothing if this == obj. + * + * @param obj A {@link List} object of the same type (i.e., with the same template parameters, T). + * Note that this function modifies obj no matter whether an lvalue or rvalue reference is + * passed. + * @param compare Binary predicate that, taking two values of the same type than those contained in the + * {@link list}, returns true if the first argument is considered to go before + * the second in the strict weak ordering it defines, and false otherwise. + * This shall be a function pointer or a function object. */ - constructor(); + merge(obj: List, compare: (left: T, right: T) => boolean): void; /** - *

Construct from a message.

+ *

Transfer elements from {@link List} to {@link List}.

* - * @param message A message representing specification about the Exception. + *

Transfers elements from obj into the container, inserting them at position.

+ * + *

This effectively inserts all elements into the container and removes them from obj, altering + * the sizes of both containers. The operation does not involve the construction or destruction of any + * element. They are transferred, no matter whether obj is an lvalue or an rvalue, or whether the + * value_type supports move-construction or not.

+ * + *

This first version (1) transfers all the elements of obj into the

+ * + * @param position Position within the container where the elements of obj are inserted. + * @param obj A {@link List} object of the same type (i.e., with the same template parameters, T). */ - constructor(message: string); + splice(position: ListIterator, obj: List): void; /** - *

Get string identifying exception.

- *

Returns a string that may be used to identify the exception.

+ *

Transfer an element from {@link List} to {@link List}.

* - *

The particular representation pointed by the returned value is implementation-defined. - * As a virtual function, derived classes may redefine this function so that specify value are - * returned.

+ *

Transfers an element from obj, which is pointed by an {@link ListIterator iterator} it, + * into the container, inserting the element at specified position.

+ * + *

This effectively inserts an element into the container and removes it from obj, altering the + * sizes of both containers. The operation does not involve the construction or destruction of any element. + * They are transferred, no matter whether obj is an lvalue or an rvalue, or whether the value_type + * supports move-construction or not.

+ * + *

This second version (2) transfers only the element pointed by it from obj into the + *

+ * + * @param position Position within the container where the element of obj is inserted. + * @param obj A {@link List} object of the same type (i.e., with the same template parameters, T). + * This parameter may be this if position points to an element not actually + * being spliced. + * @param it {@link ListIterator Iterator} to an element in obj. Only this single element is + * transferred. */ - what(): string; + splice(position: ListIterator, obj: List, it: ListIterator): void; /** - * @inheritdoc + *

Transfer elements from {@link List} to {@link List}.

+ * + *

Transfers elements from obj into the container, inserting them at position.

+ * + *

This effectively inserts those elements into the container and removes them from obj, altering + * the sizes of both containers. The operation does not involve the construction or destruction of any + * element. They are transferred, no matter whether obj is an lvalue or an rvalue, or whether the + * value_type supports move-construction or not.

+ * + *

This third version (3) transfers the range [begin, end) from obj into the + *

+ * + * @param position Position within the container where the elements of obj are inserted. + * @param obj A {@link List} object of the same type (i.e., with the same template parameters, T). + * This parameter may be this if position points to an element not actually + * being spliced. + * @param begin {@link ListIterator An Iterator} specifying initial position of a range of elements in + * obj. Transfers the elements in the range [begin, end) to + * position. + * @param end {@link ListIterator An Iterator} specifying final position of a range of elements in + * obj. Transfers the elements in the range [begin, end) to + * position. Notice that the range includes all the elements between begin and + * end, including the element pointed by begin but not the one pointed by end. */ - readonly message: string; + splice(position: ListIterator, obj: List, begin: ListIterator, end: ListIterator): void; /** - * @inheritdoc + *

Sort elements in

+ * + *

Sorts the elements in the {@link List}, altering their position within the

+ * + *

The sorting is performed by applying an algorithm that uses {@link less}. This comparison shall + * produce a strict weak ordering of the elements (i.e., a consistent transitive comparison, without + * considering its reflexiveness).

+ * + *

The resulting order of equivalent elements is stable: i.e., equivalent elements preserve the relative + * order they had before the call.

+ * + *

The entire operation does not involve the construction, destruction or copy of any element object. + * Elements are moved within the

*/ - readonly name: string; - } - /** - *

Logic error exception.

- * - *

This class defines the type of objects thrown as exceptions to report errors in the internal - * logical of the program, such as violation of logical preconditions or class invariants.

- * - *

These errors are presumably detectable before the program executes.

- * - *

It is used as a base class for several logical error exceptions.

- * - *

- *

- * - * @reference http://www.cplusplus.com/reference/stdexcept/logic_error - * @author Jeongho Nam - */ - class LogicError extends Exception { + sort(): void; /** - *

Construct from a message.

+ *

Sort elements in

* - * @param message A message representing specification about the Exception. + *

Sorts the elements in the {@link List}, altering their position within the

+ * + *

The sorting is performed by applying an algorithm that uses compare. This comparison shall + * produce a strict weak ordering of the elements (i.e., a consistent transitive comparison, without + * considering its reflexiveness).

+ * + *

The resulting order of equivalent elements is stable: i.e., equivalent elements preserve the relative + * order they had before the call.

+ * + *

The entire operation does not involve the construction, destruction or copy of any element object. + * Elements are moved within the

+ * + * @param compare Binary predicate that, taking two values of the same type of those contained in the + * {@link List}, returns true if the first argument goes before the second + * argument in the strict weak ordering it defines, and false otherwise. This + * shall be a function pointer or a function object. */ - constructor(message: string); - } - /** - *

Domain error exception.

- * - *

This class defines the type of objects thrown as exceptions to report domain errors.

- * - *

Generally, the domain of a mathematical function is the subset of values that it is defined for. - * For example, the square root function is only defined for non-negative numbers. Thus, a negative number - * for such a function would qualify as a domain error.

- * - *

No component of the standard library throws exceptions of this type. It is designed as a standard - * exception to be thrown by programs.

- * - *

- *

- * - * @reference http://www.cplusplus.com/reference/stdexcept/domain_error - * @author Jeongho Nam - */ - class DomainError extends LogicError { + sort(compare: (left: T, right: T) => boolean): void; /** - *

Construct from a message.

- * - * @param message A message representing specification about the Exception. + * @hidden */ - constructor(message: string); - } - /** - *

Invalid argument exception.

- * - *

This class defines the type of objects thrown as exceptions to report an invalid argument.

- * - *

It is a standard exception that can be thrown by programs. Some components of the standard library - * also throw exceptions of this type to signal invalid arguments.

- * - *

- *

- * - * @reference http://www.cplusplus.com/reference/stdexcept/invalid_argument - * @author Jeongho Nam - */ - class InvalidArgument extends LogicError { + private qsort(first, last, compare); /** - *

Construct from a message.

- * - * @param message A message representing specification about the Exception. + * @hidden */ - constructor(message: string); - } - /** - *

Length error exception.

- * - *

This class defines the type of objects thrown as exceptions to report a length error.

- * - *

It is a standard exception that can be thrown by programs. Some components of the standard library, - * such as vector and string also throw exceptions of this type to signal errors resizing.

- * - *

- *

- * - * @reference http://www.cplusplus.com/reference/stdexcept/length_error - * @author Jeongho Nam - */ - class LengthError extends LogicError { + private partition(first, last, compare); /** - *

Construct from a message.

+ *

Swap content.

* - * @param message A message representing specification about the Exception. + *

Exchanges the content of the container by the content of obj, which is another + * {@link List container} object with same type of elements. Sizes and container type may differ.

+ * + *

After the call to this member function, the elements in this container are those which were in obj + * before the call, and the elements of obj are those which were in this. All iterators, references and + * pointers remain valid for the swapped objects.

+ * + *

Notice that a non-member function exists with the same name, {@link std.swap swap}, overloading that + * algorithm with an optimization that behaves like this member function.

+ * + * @param obj Another {@link List container} of the same type of elements (i.e., instantiated + * with the same template parameter, T) whose content is swapped with that of this + * {@link container List}. */ - constructor(message: string); - } - /** - *

Out-of-range exception.

- * - *

This class defines the type of objects thrown as exceptions to report an out-of-range error.

- * - *

It is a standard exception that can be thrown by programs. Some components of the standard library, - * such as vector, deque, string and bitset also throw exceptions of this type to signal arguments - * out of range.

- * - *

- *

- * - * @reference http://www.cplusplus.com/reference/stdexcept/out_of_range - * @author Jeongho Nam - */ - class OutOfRange extends LogicError { + swap(obj: List): void; /** - *

Construct from a message.

- * - * @param message A message representing specification about the Exception. + * @inheritdoc */ - constructor(message: string); + swap(obj: base.IContainer): void; } +} +declare namespace std { /** - *

Runtime error exception.

- * - *

This class defines the type of objects thrown as exceptions to report errors that can only be - * detected during runtime.

- * - *

It is used as a base class for several runtime error exceptions.

+ *

An iterator, node of a List.

* - *

- *

+ *

+ * + *

* - * @reference http://www.cplusplus.com/reference/stdexcept/runtime_error * @author Jeongho Nam */ - class RuntimeError extends Exception { + class ListIterator extends Iterator { /** - *

Construct from a message.

- * - * @param message A message representing specification about the Exception. + * @hidden */ - constructor(message: string); - } - /** - *

Overflow error exception.

- * - *

This class defines the type of objects thrown as exceptions to arithmetic overflow errors.

- * - *

It is a standard exception that can be thrown by programs. Some components of the standard library - * also throw exceptions of this type to signal range errors.

- * - *

- *

- * - * @reference http://www.cplusplus.com/reference/stdexcept/overflow_error - * @author Jeongho Nam - */ - class OverflowError extends RuntimeError { + private prev_; /** - *

Construct from a message.

- * - * @param message A message representing specification about the Exception. + * @hidden */ - constructor(message: string); - } - /** - *

Underflow error exception.

- * - *

This class defines the type of objects thrown as exceptions to arithmetic underflow errors.

- * - *

No component of the standard library throws exceptions of this type. It is designed as a standard - * exception to be thrown by programs.

- * - *

- *

- * - * @reference http://www.cplusplus.com/reference/stdexcept/underflow_error - * @author Jeongho Nam - */ - class UnderflowError extends RuntimeError { + private next_; /** - *

Construct from a message.

+ * @hidden + */ + private value_; + /** + *

Construct from the source {@link List container}.

* - * @param message A message representing specification about the Exception. + *

Note

+ *

Do not create the iterator directly, by yourself.

+ *

Use {@link List.begin begin()}, {@link List.end end()} in {@link List container} instead.

+ * + * @param source The source {@link List container} to reference. + * @param prev A refenrece of previous node ({@link ListIterator iterator}). + * @param next A refenrece of next node ({@link ListIterator iterator}). + * @param value Value to be stored in the node (iterator). */ - constructor(message: string); - } - /** - *

Range error exception.

- * - *

This class defines the type of objects thrown as exceptions to report range errors in internal - * computations.

- * - *

It is a standard exception that can be thrown by programs. Some components of the standard library - * also throw exceptions of this type to signal range errors.

- * - *

- *

- * - * @reference http://www.cplusplus.com/reference/stdexcept/range_error - * @author Jeongho Nam - */ - class RangeError extends RuntimeError { + constructor(source: List, prev: ListIterator, next: ListIterator, value: T); + private list(); /** - *

Construct from a message.

+ * @inheritdoc + */ + prev(): ListIterator; + /** + * @inheritdoc + */ + next(): ListIterator; + /** + * @inheritdoc + */ + advance(step: number): ListIterator; + /** + * @inheritdoc + */ + /** + * Set value of the iterator is pointing to. * - * @param message A message representing specification about the Exception. + * @param val Value to set. */ - constructor(message: string); - } -} -declare namespace std { - /** - *

Function object class for equality comparison.

- * - *

Binary function object class whose call returns whether its two arguments compare equal (as returned by - * operator ==).

- * - *

Generically, function objects are instances of a class with member function {@link IComparable.equal_to equal_to} - * defined. This member function allows the object to be used with the same syntax as a function call.

- * - * @param x First element to compare. - * @param y Second element to compare. - * - * @return Whether the arguments are equal. - */ - function equal_to(x: T, y: T): boolean; - /** - *

Function object class for non-equality comparison.

- * - *

Binary function object class whose call returns whether its two arguments compare not equal (as returned - * by operator operator!=).

- * - *

Generically, function objects are instances of a class with member function {@link IComparable.equal_to equal_to} - * defined. This member function allows the object to be used with the same syntax as a function call.

- * - * @param x First element to compare. - * @param y Second element to compare. - * - * @return Whether the arguments are not equal. - */ - function not_equal_to(x: T, y: T): boolean; - /** - *

Function for less-than inequality comparison.

- * - *

Binary function returns whether the its first argument compares less than the second.

- * - *

Generically, function objects are instances of a class with member function {@link IComparable.less less} - * defined. If an object doesn't have the method, then its own uid will be used to compare insteadly. - * This member function allows the object to be used with the same syntax as a function call.

- * - *

Objects of this class can be used on standard algorithms such as {@link sort sort()}, - * {@link merge merge()} or {@link TreeMap.lower_bound lower_bound()}.

- * - * @param Type of arguments to compare by the function call. The type shall supporrt the operation - * operator<() or method {@link IComparable.less less}. - * - * @param x First element, the standard of comparison. - * @param y Second element compare with the first. - * - * @return Whether the first parameter is less than the second. - */ - function less(x: T, y: T): boolean; - /** - *

Function object class for less-than-or-equal-to comparison.

- * - *

Binary function object class whose call returns whether the its first argument compares {@link less less than} or - * {@link equal_to equal to} the second (as returned by operator <=).

- * - *

Generically, function objects are instances of a class with member function {@link IComparable.less less} - * and {@link IComparable.equal_to equal_to} defined. This member function allows the object to be used with the same - * syntax as a function call.

- * - * @param x First element, the standard of comparison. - * @param y Second element compare with the first. - * - * @return Whether the x is {@link less less than} or {@link equal_to equal to} the y. - */ - function less_equal(x: T, y: T): boolean; - /** - *

Function for greater-than inequality comparison.

- * - *

Binary function returns whether the its first argument compares greater than the second.

- * - *

Generically, function objects are instances of a class with member function {@link less} and - * {@link equal_to equal_to()} defined. If an object doesn't have those methods, then its own uid will be used - * to compare insteadly. This member function allows the object to be used with the same syntax as a function - * call.

- * - *

Objects of this class can be used on standard algorithms such as {@link sort sort()}, - * {@link merge merge()} or {@link TreeMap.lower_bound lower_bound()}.

- * - * @param Type of arguments to compare by the function call. The type shall supporrt the operation - * operator>() or method {@link IComparable.greater greater}. - * - * @return Whether the x is greater than the y. - */ - function greater(x: T, y: T): boolean; - /** - *

Function object class for greater-than-or-equal-to comparison.

- * - *

Binary function object class whose call returns whether the its first argument compares - * {@link greater greater than} or {@link equal_to equal to} the second (as returned by operator >=).

- * - *

Generically, function objects are instances of a class with member function {@link IComparable.less less} - * defined. If an object doesn't have the method, then its own uid will be used to compare insteadly. - * This member function allows the object to be used with the same syntax as a function call.

- * - * @param x First element, the standard of comparison. - * @param y Second element compare with the first. - * - * @return Whether the x is {@link greater greater than} or {@link equal_to equal to} the y. - */ - function greater_equal(x: T, y: T): boolean; - /** - *

Logical AND function object class.

- * - *

Binary function object class whose call returns the result of the logical "and" operation between its two - * arguments (as returned by operator &&).

- * - *

Generically, function objects are instances of a class with member function operator() defined. This member - * function allows the object to be used with the same syntax as a function call.

- * - * @param x First element. - * @param y Second element. - * - * @return Result of logical AND operation. - */ - function logical_and(x: T, y: T): boolean; - /** - *

Logical OR function object class.

- * - *

Binary function object class whose call returns the result of the logical "or" operation between its two - * arguments (as returned by operator ||).

- * - *

Generically, function objects are instances of a class with member function operator() defined. This member - * function allows the object to be used with the same syntax as a function call.

- * - * @param x First element. - * @param y Second element. - * - * @return Result of logical OR operation. - */ - function logical_or(x: T, y: T): boolean; + value: T; + /** + * @inheritdoc + */ + equal_to(obj: ListIterator): boolean; + /** + * @inheritdoc + */ + swap(obj: ListIterator): void; + } +} +declare namespace std { /** - *

Logical NOT function object class.

- * - *

Unary function object class whose call returns the result of the logical "not" operation on its argument - * (as returned by operator !).

+ *

A reverse-iterator of List.

* - *

Generically, function objects are instances of a class with member function operator() defined. This member - * function allows the object to be used with the same syntax as a function call.

+ *

+ * + *

* - * @param x Target element. + * @param Type of the elements. * - * @return Result of logical NOT operation. + * @author Jeongho Nam */ - function logical_not(x: T): boolean; + class ListReverseIterator extends ReverseIterator, ListReverseIterator> { + /** + * Construct from base iterator. + * + * @param base A reference of the base iterator, which iterates in the opposite direction. + */ + constructor(base: ListIterator); + /** + * @hidden + */ + protected create_neighbor(base: ListIterator): ListReverseIterator; + /** + * @inheritdoc + */ + /** + * Set value of the iterator is pointing to. + * + * @param val Value to set. + */ + value: T; + } +} +declare namespace std { /** - *

Bitwise AND function object class.

- * - *

Binary function object class whose call returns the result of applying the bitwise "and" operation between - * its two arguments (as returned by operator &).

- * - * @param x First element. - * @param y Second element. + *

Priority queue.

* - * @return Result of bitwise AND operation. - */ - function bit_and(x: number, y: number): number; - /** - *

Bitwise OR function object class.

+ *

{@link PriorityQueue Priority queues} are a type of container adaptors, specifically designed such that its + * first element is always the greatest of the elements it contains, according to some strict weak ordering + * criterion.

* - *

Binary function object class whose call returns the result of applying the bitwise "and" operation between - * its two arguments (as returned by operator &).

+ *

This context is similar to a heap, where elements can be inserted at any moment, and only the + * max heap element can be retrieved (the one at the top in the {@link PriorityQueue priority queue}).

* - * @param x First element. - * @param y Second element. + *

{@link PriorityQueue Priority queues} are implemented as container adaptors, which are classes that + * use an encapsulated object of a specific container class as its {@link container_ underlying container}, + * providing a specific set of member functions to access its elements. Elements are popped from the "back" + * of the specific container, which is known as the top of the {@link PriorityQueue Priority queue}.

* - * @return Result of bitwise OR operation. - */ - function bit_or(x: number, y: number): number; - /** - *

Bitwise XOR function object class.

+ *

The {@link container_ underlying container} may be any of the standard container class templates or some + * other specifically designed container class. The container shall be accessible through + * {@link IArrayIterator random access iterators} and support the following operations:

* - *

Binary function object class whose call returns the result of applying the bitwise "exclusive or" - * operation between its two arguments (as returned by operator ^).

+ *
    + *
  • empty()
  • + *
  • size()
  • + *
  • front()
  • + *
  • push_back()
  • + *
  • pop_back()
  • + *
* - * @param x First element. - * @param y Second element. + *

The standard container classes {@link Vector} and {@link Deque} fulfill these requirements. By default, if + * no container class is specified for a particular {@link PriorityQueue} class instantiation, the standard + * container {@link Vector} is used.

* - * @return Result of bitwise XOR operation. - */ - function bit_xor(x: number, y: number): number; - /** - *

Comparable instance.

+ *

Support of {@link IArrayIterator random access iterators} is required to keep a heap structure internally + * at all times. This is done automatically by the container adaptor by automatically calling the algorithm + * functions make_heap, push_heap and pop_heap when needed.

* - *

{@link IComparable} is a common interface for objects who can compare each other.

+ * @param Type of the elements. * - * @reference https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html - * @author Jeongho Nam + * @reference http://www.cplusplus.com/reference/queue/priority_queue/ + * @author Jeongho Nam */ - interface IComparable extends Object { + class PriorityQueue { /** - *

Indicates whether some other object is "equal to" this one.

+ *

The underlying container for implementing the priority queue.

* - *

The {@link equal_to} method implements an equivalence relation on non-null object references:

+ *

Following standard definition from the C++ committee, the underlying container should be one of + * {@link Vector} or {@link Deque}, however, I've adopted {@link TreeMultiSet} instead of them. Of course, + * there are proper reasons for adapting the {@link TreeMultiSet} even violating standard advice.

* - *
    - *
  • - * It is reflexive: for any non-null reference value x, x.equal_to(x) - * should return true. - *
  • - *
  • - * It is symmetric: for any non-null reference values x and y, - * x.equal_to(y) should return true if and only if y.equal_to(x) - * returns true.
  • - *
  • - * It is transitive: for any non-null reference values x, y, and - * z, if x.equal_to(y) returns true and y.equal_to(z) - * returns true, then x.equal_to(z) should return true. - *
  • - *
  • - * It is consistent: for any non-null reference values x and y, multiple - * invocations of x.equal_to(y) consistently return true or consistently return - * false, provided no information used in equal_to comparisons on the objects is modified. - *
  • - *
  • - * For any non-null reference value x, x.equal_to(null) should return - * false. - *
  • - *
+ *

Underlying container of {@link PriorityQueue} must keep a condition; the highest (or lowest) + * element must be placed on the terminal node for fast retrieval and deletion. To keep the condition with + * {@link Vector} or {@link Deque}, lots of times will only be spent for re-arranging elements. It calls + * rearrangement functions like make_heap, push_heap and pop_head for rearrangement.

* - *

The {@link equal_to} method for interface {@link IComparable} implements the most discriminating possible - * equivalence relation on objects; that is, for any non-null reference values x and - * y, this method returns true if and only if x and y - * refer to the same object (x == y has the value true).

+ *

However, the {@link TreeMultiSet} container always keeps arrangment automatically without additional + * operations and it even meets full criteria of {@link PriorityQueue}. Those are the reason why I've adopted + * {@link TreeMultiSet} as the underlying container of {@link PriorityQueue}.

+ */ + private container_; + /** + * Default Constructor. + */ + constructor(); + /** + * Construct from compare. * - *

Note that it is generally necessary to override the {@link hash_code} method whenever this method is - * overridden, so as to maintain the general contract for the {@link hash_code} method, which states that - * equal objects must have equal hash codes.

+ * @param compare A binary predicate determines order of elements. + */ + constructor(compare: (left: T, right: T) => boolean); + /** + * Contruct from elements. * - *
    - *
  • {@link IComparable.equal_to} is called by {@link std.equal_to}.
  • - *
+ * @param array Elements to be contained. + */ + constructor(array: Array); + /** + * Contruct from elements with compare. * - * @param obj the reference object with which to compare. + * @param array Elements to be contained. + * @param compare A binary predicate determines order of elements. + */ + constructor(array: Array, compare: (left: T, right: T) => boolean); + /** + * Copy Constructor. + */ + constructor(container: base.IContainer); + /** + * Copy Constructor with compare. * - * @return true if this object is the same as the obj argument; false otherwise. + * @param container A container to be copied. + * @param compare A binary predicate determines order of elements. */ - equal_to(obj: T): boolean; + constructor(container: base.IContainer, compare: (left: T, right: T) => boolean); /** - *

Less-than inequality comparison.

+ * Range Constructor. * - *

Binary method returns whether the the instance compares less than the obj.

+ * @param begin Input interator of the initial position in a sequence. + * @param end Input interator of the final position in a sequence. + */ + constructor(begin: Iterator, end: Iterator); + /** + * Range Constructor with compare. * - *
    - *
  • - * {@link IComparable.less} is called by {@link std.less}. Also, this method can be used on standard - * algorithms such as {@link sort sort()}, {@link merge merge()} or - * {@link TreeMap.lower_bound lower_bound()}. - *
  • - *
+ * @param begin Input interator of the initial position in a sequence. + * @param end Input interator of the final position in a sequence. + * @param compare A binary predicate determines order of elements. + */ + constructor(begin: Iterator, end: Iterator, compare: (left: T, right: T) => boolean); + /** + *

Return size.

* - * @param obj the reference object with which to compare. + *

Returns the number of elements in the {@link PriorityQueue}.

+ * + *

This member function effectively calls member {@link IArray.size size} of the + * {@link container_ underlying container} object.

+ * + * @return The number of elements in the underlying + */ + size(): number; + /** + *

Test whether container is empty.

+ * + *

Returns whether the {@link PriorityQueue} is empty: i.e. whether its {@link size} is zero.

+ * + *

This member function effectively calls member {@link IARray.empty empty} of the + * {@link container_ underlying container} object.

+ */ + empty(): boolean; + /** + *

Access top element.

+ * + *

Returns a constant reference to the top element in the {@link PriorityQueue}.

+ * + *

The top element is the element that compares higher in the {@link PriorityQueue}, and the next that is + * removed from the container when {@link PriorityQueue.pop} is called.

+ * + *

This member function effectively calls member {@link IArray.front front} of the + * {@link container_ underlying container} object.

+ * + * @return A reference to the top element in the {@link PriorityQueue}. + */ + top(): T; + /** + *

Insert element.

+ * + *

Inserts a new element in the {@link PriorityQueue}. The content of this new element is initialized to + * val. + * + *

This member function effectively calls the member function {@link IArray.push_back push_back} of the + * {@link container_ underlying container} object, and then reorders it to its location in the heap by calling + * the push_heap algorithm on the range that includes all the elements of the

* - * @return Whether the first parameter is less than the second. + * @param val Value to which the inserted element is initialized. */ - less(obj: T): boolean; + push(val: T): void; /** - *

Issue a hash code.

+ *

Remove top element.

* - *

Returns a hash code value for the object. This method is supported for the benefit of hash tables such - * as those provided by hash containers; {@link HashSet}, {@link HashMap}, {@link MultiHashSet} and - * {@link MultiHashMap}.

+ *

Removes the element on top of the {@link PriorityQueue}, effectively reducing its {@link size} by one. + * The element removed is the one with the highest (or lowest) value.

* - *

As much as is reasonably practical, the {@link hash_code} method defined by interface - * {@link IComparable} does return distinct integers for distinct objects. (This is typically implemented by - * converting the internal address of the object into an integer, but this implementation technique is not - * required by the JavaScript programming language.)

+ *

The value of this element can be retrieved before being popped by calling member + * {@link PriorityQueue.top}.

* - *
    - *
  • - * {@link IComparable.hash_code} is called by {@link std.hash_code}. If you want to keep basically - * provided hash function, then returns {@link std.Hash.code}; return std.Hash.code(this); - *
  • - *
+ *

This member function effectively calls the pop_heap algorithm to keep the heap property of + * {@link PriorityQueue PriorityQueues} and then calls the member function {@link IArray.pop_back pop_back} of + * the {@link container_ underlying container} object to remove the element.

+ */ + pop(): void; + /** + *

Swap contents.

* - * @return An hash code who represents the object. + *

Exchanges the contents of the container adaptor by those of obj, swapping both the + * {@link container_ underlying container} value and their comparison function using the corresponding + * {@link std.swap swap} non-member functions (unqualified).

+ * + *

This member function has a noexcept specifier that matches the combined noexcept of the + * {@link IArray.swap swap} operations on the {@link container_ underlying container} and the comparison + * functions.

+ * + * @param obj {@link PriorityQueue} container adaptor of the same type (i.e., instantiated with the same + * template parameters, T). Sizes may differ. */ - hash(): number; + swap(obj: PriorityQueue): void; } +} +declare namespace std { /** - *

Default hash function for number.

- * - *

Unary function that defines the default hash function used by the standard library.

+ *

FIFO queue.

* - *

The functional call returns a hash value of its argument: A hash value is a value that depends solely on - * its argument, returning always the same value for the same argument (for a given execution of a program). The - * value returned shall have a small likelihood of being the same as the one returned for a different argument. + *

{@link Queue}s are a type of container adaptor, specifically designed to operate in a FIFO context + * (first-in first-out), where elements are inserted into one end of the container and extracted from the other. *

* - * @param val Value to be hashed. - * - * @return Returns a hash value for its argument, as a value of type number. The number is an unsigned integer. - */ - function hash(val: number): number; - /** - *

Default hash function for string.

- * - *

Unary function that defines the default hash function used by the standard library.

- * - *

The functional call returns a hash value of its argument: A hash value is a value that depends solely on - * its argument, returning always the same value for the same argument (for a given execution of a program). The - * value returned shall have a small likelihood of being the same as the one returned for a different argument. - *

+ *

{@link Queue}s are implemented as containers adaptors, which are classes that use an encapsulated object of + * a specific container class as its underlying container, providing a specific set of member functions to access + * its elements. Elements are pushed into the {@link IDeque.back back()} of the specific container and popped from + * its {@link IDeque.front front()}.

* - * @param str A string to be hashed. + *

{@link container_ The underlying container} may be one of the standard container class template or some + * other specifically designed container class. This underlying container shall support at least the following + * operations:

* - * @return Returns a hash value for its argument, as a value of type number. The number is an unsigned integer. - */ - function hash(str: string): number; - /** - *

Default hash function for Object.

+ *
    + *
  • empty
  • + *
  • size
  • + *
  • front
  • + *
  • back
  • + *
  • push_back
  • + *
  • pop_front
  • + *
* - *

Unary function that defines the default hash function used by the standard library.

+ *

The standard container classes {@link Deque} and {@link List} fulfill these requirements. + * By default, if no container class is specified for a particular {@link Queue} class instantiation, the standard + * container {@link List} is used.

* - *

The functional call returns a hash value of its argument: A hash value is a value that depends solely on - * its argument, returning always the same value for the same argument (for a given execution of a program). The - * value returned shall have a small likelihood of being the same as the one returned for a different argument. + *

+ * *

* - *

The default {@link hash} function of Object returns a value returned from {@link hash hash(number)} with - * an unique id of each Object. If you want to specify {@link hash} function of a specific class, then - * define a member function public hash(): number in the class.

- * - * @param obj Object to be hashed. - * - * @return Returns a hash value for its argument, as a value of type number. The number is an unsigned integer. - */ - function hash(obj: Object): number; - /** - *

Exchange contents of {@link IContainers containers}.

- * - *

The contents of container left are exchanged with those of right. Both container objects must have - * same type of elements (same template parameters), although sizes may differ.

- * - *

After the call to this member function, the elements in left are those which were in right before - * the call, and the elements of right are those which were in left. All iterators, references and - * pointers remain valid for the swapped objects.

- * - *

This is an overload of the generic algorithm swap that improves its performance by mutually transferring - * ownership over their assets to the other container (i.e., the containers exchange references to their data, without - * actually performing any element copy or movement): It behaves as if left. - * {@link IContainer.swap swap}(right) was called.

- * - * @param left A {@link IContainer container} to swap its contents. - * @param right A {@link IContainer container} to swap its contents. - */ - function swap(left: base.IContainer, right: base.IContainer): void; - /** - *

Exchange contents of queues.

- * - *

Exchanges the contents of left and right.

- * - * @param left A {@link Queue} container of the same type. Size may differ. - * @param right A {@link Queue} container of the same type. Size may differ. - */ - function swap(left: Queue, right: Queue): void; - /** - *

Exchange contents of {@link PriorityQueue PriorityQueues}.

- * - *

Exchanges the contents of left and right.

- * - * @param left A {@link PriorityQueue} container of the same type. Size may differ. - * @param right A {@link PriorityQueue} container of the same type. Size may differ. - */ - function swap(left: PriorityQueue, right: PriorityQueue): void; - /** - *

Exchange contents of {@link Stack Stacks}.

- * - *

Exchanges the contents of left and right.

- * - * @param left A {@link Stack} container of the same type. Size may differ. - * @param right A {@link Stack} container of the same type. Size may differ. - */ - function swap(left: Stack, right: Stack): void; - /** - *

Exchanges the contents of two {@link UniqueMap unique maps}.

- * - *

The contents of container left are exchanged with those of right. Both container objects must - * be of the same type (same template parameters), although sizes may differ.

- * - *

After the call to this member function, the elements in left are those which were in right - * before the call, and the elements of right are those which were in left. All iterators, references - * and pointers remain valid for the swapped objects.

- * - *

This is an overload of the generic algorithm swap that improves its performance by mutually transferring - * ownership over their assets to the other container (i.e., the containers exchange references to their data, - * without actually performing any element copy or movement): It behaves as if - * left.{@link UniqueMap.swap swap}(right) was called.

- * - * @param left An {@link UniqueMap unique map} to swap its conents. - * @param right An {@link UniqueMap unique map} to swap its conents. - */ - function swap(left: base.UniqueMap, right: base.UniqueMap): void; - /** - *

Exchanges the contents of two {@link MultiMap multi maps}.

- * - *

The contents of container left are exchanged with those of right. Both container objects must - * be of the same type (same template parameters), although sizes may differ.

- * - *

After the call to this member function, the elements in left are those which were in right - * before the call, and the elements of right are those which were in left. All iterators, references - * and pointers remain valid for the swapped objects.

- * - *

This is an overload of the generic algorithm swap that improves its performance by mutually transferring - * ownership over their assets to the other container (i.e., the containers exchange references to their data, - * without actually performing any element copy or movement): It behaves as if - * left.{@link MultiMap.swap swap}(right) was called.

+ * @param Type of elements. * - * @param left A {@link MultiMap multi map} to swap its conents. - * @param right A {@link MultiMap multi map} to swap its conents. + * @reference http://www.cplusplus.com/reference/queue/queue + * @author Jeongho Nam */ - function swap(left: base.MultiMap, right: base.MultiMap): void; + class Queue { + /** + * The underlying object for implementing the FIFO + */ + private container_; + /** + * Default Constructor. + */ + constructor(); + /** + * Copy Constructor. + */ + constructor(container: Queue); + /** + *

Return size.

+ *

Returns the number of elements in the {@link Queue}.

+ * + *

This member function effectively calls member {@link IDeque.size size()} of the + * {@link container_ underlying container} object.

+ * + * @return The number of elements in the {@link container_ underlying container}. + */ + size(): number; + /** + *

Test whether container is empty.

+ *

returns whether the {@link Queue} is empty: i.e. whether its size is zero.

+ * + *

This member function efeectively calls member {@link IDeque.empty empty()} of the + * {@link container_ underlying container} object.

+ * + * @return true if the {@link container_ underlying container}'s size is 0, + * false otherwise.

+ */ + empty(): boolean; + /** + *

Access next element.

+ *

Returns a value of the next element in the {@link Queue}.

+ * + *

The next element is the "oldest" element in the {@link Queue} and the same element that is popped out + * from the queue when {@link pop Queue.pop()} is called.

+ * + *

This member function effectively calls member {@link IDeque.front front()} of the + * {@link container_ underlying container} object.

+ * + * @return A value of the next element in the {@link Queue}. + */ + front(): T; + /** + *

Access last element.

+ * + *

Returns a vaue of the last element in the queue. This is the "newest" element in the queue (i.e. the + * last element pushed into the queue).

+ * + *

This member function effectively calls the member function {@link IDeque.back back()} of the + * {@link container_ underlying container} object.

+ * + * @return A value of the last element in the {@link Queue}. + */ + back(): T; + /** + *

Insert element.

+ * + *

Inserts a new element at the end of the {@link Queue}, after its current last element. + * The content of this new element is initialized to val.

+ * + *

This member function effectively calls the member function {@link IDeque.push_back push_back()} of the + * {@link container_ underlying container} object.

+ * + * @param val Value to which the inserted element is initialized. + */ + push(val: T): void; + /** + *

Remove next element.

+ * + *

Removes the next element in the {@link Queue}, effectively reducing its size by one.

+ * + *

The element removed is the "oldest" element in the {@link Queue} whose value can be retrieved by calling + * member {@link front Queue.front()}

. + * + *

This member function effectively calls the member function {@link IDeque.pop_front pop_front()} of the + * {@link container_ underlying container} object.

+ */ + pop(): void; + /** + *

Swap contents.

+ * + *

Exchanges the contents of the container adaptor (this) by those of obj.

+ * + *

This member function calls the non-member function {@link IContainer.swap swap} (unqualified) to swap + * the {@link container_ underlying containers}.

+ * + * @param obj Another {@link Queue} container adaptor of the same type (i.e., instantiated with the same + * template parameter, T). Sizes may differ.

+ */ + swap(obj: Queue): void; + } } declare namespace std { /** - *

Bind function arguments.

- * - *

Returns a function object based on fn, but with its arguments bound to args.

- * - *

Each argument may either be bound to a value or be a {@link placeholders placeholder}:

- *
    - *
  • If bound to a value, calling the returned function object will always use that value as argument.
  • - *
  • - * If a {@link placeholders placeholder}, calling the returned function object forwards an argument passed to the - * call (the one whose order number is specified by the placeholder). - *
  • - *
- * - *

Calling the returned object returns the same type as fn.

+ *

LIFO stack.

* - * @param fn A function object, pointer to function or pointer to member. - * @param args List of arguments to bind: either values, or {@link placeholders}. + *

{@link Stack}s are a type of container adaptor, specifically designed to operate in a LIFO context + * (last-in first-out), where elements are inserted and extracted only from one end of the

* - * @return A function object that, when called, calls fn with its arguments bound to args. If fn is - * a pointer to member, the first argument expected by the returned function is an object of the class fn - * is a member. - */ - function bind(fn: (...args: any[]) => Ret, ...args: any[]): (...args: any[]) => Ret; - /** - *

Bind function arguments.

+ *

{@link Stack}s are implemented as containers adaptors, which are classes that use an encapsulated object of + * a specific container class as its underlying container, providing a specific set of member functions to + * access its elements. Elements are pushed/popped from the {@link ILinearContainer.back back()} of the + * {@link ILinearContainer specific container}, which is known as the top of the {@link Stack}.

* - *

Returns a function object based on fn, but with its arguments bound to args.

+ *

{@link container_ The underlying container} may be any of the standard container class templates or some + * other specifically designed container class. The container shall support the following operations:

* - *

Each argument may either be bound to a value or be a {@link placeholders placeholder}:

*
    - *
  • If bound to a value, calling the returned function object will always use that value as argument.
  • - *
  • - * If a {@link placeholders placeholder}, calling the returned function object forwards an argument passed to the - * call (the one whose order number is specified by the placeholder). - *
  • + *
  • empty
  • + *
  • size
  • + *
  • front
  • + *
  • back
  • + *
  • push_back
  • + *
  • pop_back
  • *
* - *

Calling the returned object returns the same type as fn.

- * - * @param fn A function object, pointer to function or pointer to member. - * @param thisArg This argument, owner object of the member method fn. - * @param args List of arguments to bind: either values, or {@link placeholders}. - * - * @return A function object that, when called, calls fn with its arguments bound to args. If fn is - * a pointer to member, the first argument expected by the returned function is an object of the class fn - * is a member. - */ - function bind(fn: (...args: any[]) => Ret, thisArg: T, ...args: any[]): (...args: any[]) => Ret; -} -/** - *

Bind argument placeholders.

- * - *
- * - *

When the function object returned by bind is called, an argument with placeholder {@link _1} is replaced by the - * first argument in the call, {@link _2} is replaced by the second argument in the call, and so on... For example:

- * - * - * let vec: Vector = new Vector(); - * - * let bind = std.bind(Vector.insert, _1, vec.end(), _2, _3); - * bind.apply(vec, 5, 1); // vec.insert(vec.end(), 5, 1); - * // [1, 1, 1, 1, 1] - * - * - *

When a call to {@link bind} is used as a subexpression in another call to bind, the {@link placeholders} - * are relative to the outermost {@link bind} expression.

- * - * @reference http://www.cplusplus.com/reference/functional/placeholders/ - * @author Jeongho Nam - */ -declare namespace std.placeholders { - /** - * @hidden - */ - class PlaceHolder { - private index_; - constructor(index: number); - readonly index: number; - } - /** - * Replaced by the first argument in the function call. - */ - const _1: PlaceHolder; - /** - * Replaced by the second argument in the function call. - */ - const _2: PlaceHolder; - /** - * Replaced by the third argument in the function call. - */ - const _3: PlaceHolder; - const _4: PlaceHolder; - const _5: PlaceHolder; - const _6: PlaceHolder; - const _7: PlaceHolder; - const _8: PlaceHolder; - const _9: PlaceHolder; - const _10: PlaceHolder; - const _11: PlaceHolder; - const _12: PlaceHolder; - const _13: PlaceHolder; - const _14: PlaceHolder; - const _15: PlaceHolder; - const _16: PlaceHolder; - const _17: PlaceHolder; - const _18: PlaceHolder; - const _19: PlaceHolder; - const _20: PlaceHolder; -} -declare namespace std.HashMap { - type iterator = std.MapIterator; - type reverse_iterator = std.MapReverseIterator; -} -declare namespace std { - /** - *

Hashed, unordered map.

+ *

The standard container classes {@link Vector}, {@link Deque} and {@link List} fulfill these requirements. + * By default, if no container class is specified for a particular {@link Stack} class instantiation, the standard + * container {@link List} is used.

* - *

{@link HashMap}s are associative containers that store elements formed by the combination of a key value - * and a mapped value, and which allows for fast retrieval of individual elements based on their keys. + *

+ * *

* - *

In an {@link HashMap}, the key value is generally used to uniquely identify the element, while the - * mapped value is an object with the content associated to this key. Types of key and - * mapped value may differ.

- * - *

Internally, the elements in the {@link HashMap} are not sorted in any particular order with respect to either - * their key or mapped values, but organized into buckets depending on their hash values to allow - * for fast access to individual elements directly by their key values (with a constant average time complexity - * on average).

- * - *

{@link HashMap} containers are faster than {@link TreeMap} containers to access individual elements by their - * key, although they are generally less efficient for range iteration through a subset of their elements.

- * - *

- * - *

+ * @param Type of elements. * - *

Container properties

- *
- *
Associative
- *
Elements in associative containers are referenced by their key and not by their absolute - * position in the container.
+ * @reference http://www.cplusplus.com/reference/stack/stack + * @author Jeongho Nam + */ + class Stack { + /** + * The underlying object for implementing the LIFO + */ + private container_; + /** + * Default Constructor. + */ + constructor(); + /** + * Copy Constructor. + */ + constructor(stack: Stack); + /** + *

Return size.

+ * + *

Returns the number of elements in the {@link Stack}.

+ * + *

This member function effectively calls member {@link ILinearContainer.size size()} of the + * {@link container_ underlying container} object.

+ * + * @return The number of elements in the {@link container_ underlying container}. + */ + size(): number; + /** + *

Test whether container is empty.

+ * + *

returns whether the {@link Stack} is empty: i.e. whether its size is zero.

+ * + *

This member function effectively calls member {@link ILinearContainer.empty empty()} of the + * {@link container_ underlying container} object.

+ * + * @return true if the underlying container's size is 0, + * false otherwise.

+ */ + empty(): boolean; + /** + *

Access next element.

+ * + *

Returns a value of the top element in the {@link Stack}

. + * + *

Since {@link Stack}s are last-in first-out containers, the top element is the last element inserted into + * the {@link Stack}.

+ * + *

This member function effectively calls member {@link ILinearContainer.back back()} of the + * {@link container_ underlying container} object.

+ * + * @return A value of the top element in the {@link Stack}. + */ + top(): T; + /** + *

Insert element.

+ * + *

Inserts a new element at the top of the {@link Stack}, above its current top element.

+ * + *

This member function effectively calls the member function + * {@link ILinearContainer.push_back push_back()} of the {@link container_ underlying container} object.

+ * + * @param val Value to which the inserted element is initialized. + */ + push(val: T): void; + /** + *

Remove top element.

+ * + *

Removes the element on top of the {@link Stack}, effectively reducing its size by one.

+ * + *

The element removed is the latest element inserted into the {@link Stack}, whose value can be retrieved + * by calling member {@link top Stack.top()}

. + * + *

This member function effectively calls the member function {@link ILinearContainer.pop_back pop_back()} + * of the {@link container_ underlying container} object.

+ */ + pop(): void; + /** + *

Swap contents.

+ * + *

Exchanges the contents of the container adaptor (this) by those of obj.

+ * + *

This member function calls the non-member function {@link IContainer.swap swap} (unqualified) to swap + * the {@link container_ underlying containers}.

+ * + * @param obj Another {@link Stack} container adaptor of the same type (i.e., instantiated with the same + * template parameter, T). Sizes may differ.

+ */ + swap(obj: Stack): void; + } +} +declare namespace std.base { + /** + *

An abstract error instance.

* - *
Hashed
- *
Hashed containers organize their elements using hash tables that allow for fast access to elements - * by their key.
+ *

{@link ErrorInstance} is an abstract class of {@link ErrorCode} and {@link ErrorCondition} + * holding an error instance's identifier {@link value}, associated with a {@link category}.

* - *
Map
- *
Each element associates a key to a mapped value: - * Keys are meant to identify the elements whose main content is the mapped value.
+ *

The operating system and other low-level applications and libraries generate numerical error codes to + * represent possible results. These numerical values may carry essential information for a specific platform, + * but be non-portable from one platform to another.

* - *
Unique keys
- *
No two elements in the container can have equivalent keys.
- *
+ *

Objects of this class associate such numerical codes to {@link ErrorCategory error categories}, + * so that they can be interpreted when needed as more abstract (and portable) + * {@link ErrorCondition error conditions}.

* - * @param Type of the key values. - * Each element in an {@link HashMap} is uniquely identified by its key value. - * @param Type of the mapped value. - * Each element in an {@link HashMap} is used to store some data as its mapped value. + *

+ *

* - * @reference http://www.cplusplus.com/reference/unordered_map/unordered_map * @author Jeongho Nam */ - class HashMap extends base.UniqueMap implements base.IHashMap { + abstract class ErrorInstance { /** * @hidden */ - private hash_buckets_; + protected category_: ErrorCategory; /** - * Default Constructor. + * @hidden */ - constructor(); + protected value_: number; /** - * Construct from elements. + * Default Constructor. */ - constructor(items: Pair[]); + constructor(); /** - * Contruct from tuples. + * Construct from a numeric value and error category. * - * @param array Tuples to be contained. - */ - constructor(array: [Key, T][]); - /** - * Copy Constructor. + * @param val A numerical value identifying an error instance. + * @param category A reference to an {@link ErrorCategory} object. */ - constructor(container: HashMap); + constructor(val: number, category: ErrorCategory); /** - * Construct from range iterators. + *

Assign error instance.

+ * + *

Assigns the {@link ErrorCode} object a value of val associated with the {@link ErrorCategory}.

+ * + * @param val A numerical value identifying an error instance. + * @param category A reference to an {@link ErrorCategory} object. */ - constructor(begin: Iterator>, end: Iterator>); + assign(val: number, category: ErrorCategory): void; /** - * @inheritdoc + *

Clear error instance.

+ * + *

Clears the value in the {@link ErrorCode} object so that it is set to a value of 0 of the + * {@link ErrorCategory.systemCategory ErrorCategory.systemCategory()} (indicating no error).

*/ clear(): void; /** - * @inheritdoc - */ - find(key: Key): MapIterator; - /** - * @inheritdoc - */ - begin(): MapIterator; - /** - * @inheritdoc - */ - begin(index: number): MapIterator; - /** - * @inheritdoc + *

Get category.

+ * + *

Returns a reference to the {@link ErrorCategory} associated with the {@link ErrorCode} object.

+ * + * @return A reference to a non-copyable object of a type derived from {@link ErrorCategory}. */ - end(): MapIterator; + category(): ErrorCategory; /** - * @inheritdoc + *

Error value.

+ * + *

Returns the error value associated with the {@link ErrorCode} object.

+ * + * @return The error value. */ - end(index: number): MapIterator; + value(): number; /** - * @inheritdoc + *

Get message.

+ * + *

Returns the message associated with the error instance.

+ * + *

Error messages are defined by the {@link category} the error instance belongs to.

+ * + *

This function returns the same as if the following member was called:

+ * + *

category().message(value())

+ * + * @return A string object with the message associated with the {@link ErrorCode}. */ - rbegin(): MapReverseIterator; + message(): string; /** - * @inheritdoc + *

Default error condition.

+ * + *

Returns the default {@link ErrorCondition}object associated with the {@link ErrorCode} object.

+ * + *

This function returns the same as if the following member was called:

+ * + *

category().default_error_condition(value())

+ * + *

{@link ErrorCategory.default_error_condition ErrorCategory.default_error_condition()} + * is a virtual member function, that can operate differently for each category.

+ * + * @return An {@link ErrorCondition}object that corresponds to the {@link ErrorCode} object. */ - rbegin(index: number): MapReverseIterator; + default_error_condition(): ErrorCondition; /** - * @inheritdoc + *

Convert to bool.

+ * + *

Returns whether the error instance has a numerical {@link value} other than 0.

+ * + *

If it is zero (which is generally used to represent no error), the function returns false, otherwise it returns true.

+ * + * @return true if the error's numerical value is not zero. + * false otherwise. */ - rend(): MapReverseIterator; + to_bool(): boolean; + } +} +declare namespace std { + /** + *

System error exception.

+ * + *

This class defines the type of objects thrown as exceptions to report conditions originating during + * runtime from the operating system or other low-level application program interfaces which have an + * associated {@link ErrorCode}.

+ * + *

The class inherits from {@link RuntimeError}, to which it adds an {@link ErrorCode} as + * member code (and defines a specialized what member).

+ * + *

+ *

+ * + * @reference http://www.cplusplus.com/reference/system_error/system_error + * @author Jeongho Nam + */ + class SystemError extends RuntimeError { /** - * @inheritdoc + * @hidden */ - rend(index: number): MapReverseIterator; + protected code_: ErrorCode; /** - * @inheritdoc + * Construct from an error code. + * + * @param code An {@link ErrorCode} object. */ - bucket_count(): number; + constructor(code: ErrorCode); /** - * @inheritdoc + * Construct from an error code and message. + * + * @param code An {@link ErrorCode} object. + * @param message A message incorporated in the string returned by member {@link what what()}. */ - bucket_size(index: number): number; + constructor(code: ErrorCode, message: string); /** - * @inheritdoc + * Construct from a numeric value and error category. + * + * @param val A numerical value identifying an error code. + * @param category A reference to an {@link ErrorCode} object. */ - max_load_factor(): number; + constructor(val: number, category: ErrorCategory); /** - * @inheritdoc + * Construct from a numeric value, error category and message. + * + * @param val A numerical value identifying an error code. + * @param category A reference to an {@link ErrorCode} object. + * @param message A message incorporated in the string returned by member {@link what what()}. */ - max_load_factor(z: number): void; + constructor(val: number, category: ErrorCategory, message: string); /** - * @inheritdoc + *

Get error code.

+ * + *

Returns the {@link ErrorCode} object associated with the exception.

+ * + *

This value is either the {@link ErrorCode} passed to the construction or its equivalent + * (if constructed with a value and a {@link category}.

+ * + * @return The {@link ErrorCode} associated with the object. */ - bucket(key: Key): number; + code(): ErrorCode; + } +} +declare namespace std { + /** + *

Error category.

+ * + *

This type serves as a base class for specific category types.

+ * + *

Category types are used to identify the source of an error. They also define the relation between + * {@link ErrorCode} and {@link ErrorCondition}objects of its category, as well as the message set for {@link ErrorCode} + * objects. + * + *

Objects of these types have no distinct values and are not-copyable and not-assignable, and thus can only be + * passed by reference. As such, only one object of each of these types shall exist, each uniquely identifying its own + * category: all error codes and conditions of a same category shall return a reference to same object.

+ * + *

+ *

+ * + * @reference http://www.cplusplus.com/reference/system_error/error_category + * @author Jeongho Nam + */ + abstract class ErrorCategory { /** - * @inheritdoc + * Default Constructor. */ - reserve(n: number): void; + constructor(); /** - * @inheritdoc + *

Return category name.

+ * + *

In derived classes, the function returns a string naming the category.

+ * + *

In {@link ErrorCategory}, it is a pure virtual member function.

+ * + *
    + *
  • In the {@link GenericCategory} object, it returns "generic".
  • + *
  • In the {@link SystemCategory} object, it returns "system".
  • + *
  • In the {@link IOStreamCategory} object, it returns "iostream".
  • + *
+ * + * @return The category name. */ - rehash(n: number): void; + abstract name(): string; /** - * @hidden + *

Error message.

+ * + *

In derived classes, the function returns a string object with a message describing the error condition + * denoted by val.

+ * + *

In {@link ErrorCategory}, it is a pure virtual member function.

+ * + *

This function is called both by {@link ErrorCode.message ErrorCode.message()} and + * {@link ErrorCondition.message ErrorCondition.message()} to obtain the corresponding message in the + * {@link category}. Therefore, numerical values used by custom error codes and + * {@link ErrorCondition error conditions} should only match for a category if they describe the same error.

+ * + * @param val A numerical value identifying an error condition. + * If the {@link ErrorCategory} object is the {@link GenericCategory}, this argument is equivalent to an + * {@link errno} value. + * + * @return A string object with the message. */ - protected _Insert_by_pair(pair: Pair): any; + abstract message(val: number): string; /** - * @hidden + *

Default error condition.

+ * + *

Returns the default {@link ErrorCondition}object of this category that is associated with the + * {@link ErrorCode} identified by a value of val.

+ * + *

Its definition in the base class {@link ErrorCategory} returns the same as constructing an + * {@link ErrorCondition} object with: + * + *

new ErrorCondition(val, *this);

+ * + *

As a virtual member function, this behavior can be overriden in derived classes.

+ * + *

This function is called by the default definition of member {@link equivalent equivalent()}, which is used to + * compare {@link ErrorCondition error conditions} with error codes.

+ * + * @param val A numerical value identifying an error condition. + * + * @return The default {@link ErrorCondition}object associated with condition value val for this category. */ - protected _Insert_by_hint(hint: MapIterator, pair: Pair): MapIterator; + default_error_condition(val: number): ErrorCondition; /** - * @hidden + *

Check error code equivalence.

+ * + *

Checks whether, for the category, an {@link ErrorCode error code} is equivalent to an + * {@link ErrorCondition error condition.

+ * + *

This function is called by the overloads of comparison operators when an {@link ErrorCondition} object is + * compared to an {@link ErrorCode} object to check for equality or inequality. If either one of those objects' + * {@link ErrorCategory categories} considers the other equivalent using this function, they are considered + * equivalent by the operator.

+ * + *

As a virtual member function, this behavior can be overridden in derived classes to define a different + * correspondence mechanism for each {@link ErrorCategory} type.

+ * + * @param val_code A numerical value identifying an error code. + * @param cond An object of an {@link ErrorCondition} type. + * + * @return true if the arguments are considered equivalent. false otherwise. */ - protected _Insert_by_range>>(first: InputIterator, last: InputIterator): void; + equivalent(val_code: number, cond: ErrorCondition): boolean; /** - * @inheritdoc + *

Check error code equivalence.

+ * + *

Checks whether, for the category, an {@link ErrorCode error code} is equivalent to an + * {@link ErrorCondition error condition.

+ * + *

This function is called by the overloads of comparison operators when an {@link ErrorCondition} object is + * compared to an {@link ErrorCode} object to check for equality or inequality. If either one of those objects' + * {@link ErrorCategory categories} considers the other equivalent using this function, they are considered + * equivalent by the operator.

+ * + *

As a virtual member function, this behavior can be overridden in derived classes to define a different + * correspondence mechanism for each {@link ErrorCategory} type.

+ * + * @param code An object of an {@link ErrorCode} type. + * @param val_cond A numerical value identifying an error code. + * + * @return true if the arguments are considered equivalent. false otherwise. */ - protected _Handle_insert(first: MapIterator, last: MapIterator): void; + equivalent(code: ErrorCode, val_cond: number): boolean; + } +} +declare namespace std { + /** + *

Error condition.

+ * + *

Objects of this type hold a condition {@link value} associated with a {@link category}.

+ * + *

Objects of this type describe errors in a generic way so that they may be portable across different + * systems. This is in contrast with {@link ErrorCode} objects, that may contain system-specific + * information.

+ * + *

Because {@link ErrorCondition}objects can be compared with error_code objects directly by using + * relational operators, {@link ErrorCondition}objects are generally used to check whether + * a particular {@link ErrorCode} obtained from the system matches a specific error condition no matter + * the system.

+ * + *

The {@link ErrorCategory categories} associated with the {@link ErrorCondition} and the + * {@link ErrorCode} define the equivalences between them.

+ * + *

+ *

+ * + * @reference http://www.cplusplus.com/reference/system_error/error_condition + * @author Jeongho Nam + */ + class ErrorCondition extends base.ErrorInstance { /** - * @inheritdoc + * Default Constructor. */ - protected _Handle_erase(first: MapIterator, last: MapIterator): void; + constructor(); /** - *

Swap content.

- * - *

Exchanges the content of the container by the content of obj, which is another - * {@link HashMap map} of the same type. Sizes abd container type may differ.

- * - *

After the call to this member function, the elements in this container are those which were - * in obj before the call, and the elements of obj are those which were in this. All - * iterators, references and pointers remain valid for the swapped objects.

- * - *

Notice that a non-member function exists with the same name, {@link std.swap swap}, overloading that - * algorithm with an optimization that behaves like this member function.

+ * Construct from a numeric value and error category. * - * @param obj Another {@link HashMap map container} of the same type of elements as this (i.e., - * with the same template parameters, Key and T) whose content is swapped - * with that of this {@link HashMap container}. + * @param val A numerical value identifying an error condition. + * @param category A reference to an {@link ErrorCategory} object. */ - swap(obj: HashMap): void; + constructor(val: number, category: ErrorCategory); + } +} +declare namespace std { + /** + *

Error code.

+ * + *

Objects of this type hold an error code {@link value} associated with a {@link category}.

+ * + *

The operating system and other low-level applications and libraries generate numerical error codes to + * represent possible results. These numerical values may carry essential information for a specific platform, + * but be non-portable from one platform to another.

+ * + *

Objects of this class associate such numerical codes to {@link ErrorCategory error categories}, so that they + * can be interpreted when needed as more abstract (and portable) {@link ErrorCondition error conditions}.

+ * + *

+ *

+ * + * @reference http://www.cplusplus.com/reference/system_error/error_code + * @author Jeongho Nam + */ + class ErrorCode extends base.ErrorInstance { /** - * @inheritdoc + * Default Constructor. */ - swap(obj: base.IContainer>): void; + constructor(); + /** + * Construct from a numeric value and error category. + * + * @param val A numerical value identifying an error code. + * @param category A reference to an {@link ErrorCategory} object. + */ + constructor(val: number, category: ErrorCategory); } } -declare namespace std.HashMultiMap { +declare namespace std.TreeMap { type iterator = std.MapIterator; type reverse_iterator = std.MapReverseIterator; } declare namespace std { /** - *

Hashed, unordered Multimap.

+ *

Tree-structured map, std::map of STL.

* - *

{@link HashMultiMap}s are associative containers that store elements formed by the combination of - * a key value and a mapped value, much like {@link HashMultiMap} containers, but allowing - * different elements to have equivalent keys.

+ *

{@link TreeMap TreeMaps} are associative containers that store elements formed by a combination of a + * key value (Key) and a mapped value (T), following order.

* - *

In an {@link HashMultiMap}, the key value is generally used to uniquely identify the - * element, while the mapped value is an object with the content associated to this key. - * Types of key and mapped value may differ.

+ *

In a {@link TreeMap}, the key values are generally used to sort and uniquely identify the elements, + * while the mapped values store the content associated to this key. The types of key and + * mapped value may differ, and are grouped together in member type value_type, which is a {@link Pair} + * type combining both:

* - *

Internally, the elements in the {@link HashMultiMap} are not sorted in any particular order with - * respect to either their key or mapped values, but organized into buckets depending on - * their hash values to allow for fast access to individual elements directly by their key values - * (with a constant average time complexity on average).

+ *

typedef Pair value_type;

* - *

Elements with equivalent keys are grouped together in the same bucket and in such a way that - * an iterator can iterate through all of them. Iterators in the container are doubly linked iterators.

+ *

Internally, the elements in a {@link TreeMap} are always sorted by its key following a + * strict weak ordering criterion indicated by its internal comparison method {@link less}. * - *

- * - *

+ *

{@link TreeMap} containers are generally slower than {@link HashMap HashMap} containers to access individual + * elements by their key, but they allow the direct iteration on subsets based on their order.

+ * + *

{@link TreeMap}s are typically implemented as binary search trees.

+ * + *

+ *

* *

Container properties

*
@@ -8749,125 +8285,121 @@ declare namespace std { *
Elements in associative containers are referenced by their key and not by their absolute * position in the container.
* - *
Hashed
- *
Hashed containers organize their elements using hash tables that allow for fast access to elements - * by their key.
+ *
Ordered
+ *
The elements in the container follow a strict order at all times. All inserted elements are + * given a position in this order.
* *
Map
*
Each element associates a key to a mapped value: * Keys are meant to identify the elements whose main content is the mapped value.
* - *
Multiple equivalent keys
- *
The container can hold multiple elements with equivalent keys.
+ *
Unique keys
+ *
No two elements in the container can have equivalent keys.
*
* - * @param Type of the key values. - * Each element in an {@link HashMultiMap} is identified by a key value. - * @param Type of the mapped value. - * Each element in an {@link HashMultiMap} is used to store some data as its mapped value. + * @param Type of the keys. Each element in a map is uniquely identified by its key value. + * @param Type of the mapped value. Each element in a map stores some data as its mapped value. * - * @reference http://www.cplusplus.com/reference/unordered_map/unordered_multimap + * @reference http://www.cplusplus.com/reference/map/map * @author Jeongho Nam */ - class HashMultiMap extends base.MultiMap { + class TreeMap extends base.UniqueMap implements base.ITreeMap { /** * @hidden */ - private hash_buckets_; + private tree_; /** * Default Constructor. */ constructor(); /** - * Construct from elements. - */ - constructor(items: Pair[]); - /** - * Contruct from tuples. + * Construct from compare. * - * @param array Tuples to be contained. - */ - constructor(array: [Key, T][]); - /** - * Copy Constructor. - */ - constructor(container: HashMultiMap); - /** - * Construct from range iterators. - */ - constructor(begin: Iterator>, end: Iterator>); - /** - * @inheritdoc - */ - clear(): void; - /** - * @inheritdoc - */ - find(key: Key): MapIterator; - /** - * @inheritdoc + * @param compare A binary predicate determines order of elements. */ - count(key: Key): number; + constructor(compare: (x: Key, y: Key) => boolean); /** - * @inheritdoc + * Contruct from elements. + * + * @param array Elements to be contained. */ - begin(): MapIterator; + constructor(array: Array>); /** - * @inheritdoc + * Contruct from elements. + * + * @param array Elements to be contained. + * @param compare A binary predicate determines order of elements. */ - begin(index: number): MapIterator; + constructor(array: Array>, compare: (x: Key, y: Key) => boolean); /** - * @inheritdoc + * Contruct from tuples. + * + * @param array Tuples to be contained. */ - end(): MapIterator; + constructor(array: Array<[Key, T]>); /** - * @inheritdoc + * Contruct from tuples. + * + * @param array Tuples to be contained. + * @param compare A binary predicate determines order of elements. */ - end(index: number): MapIterator; + constructor(array: Array<[Key, T]>, compare: (x: Key, y: Key) => boolean); /** - * @inheritdoc + * Copy Constructor. + * + * @param container Another map to copy. */ - rbegin(): MapReverseIterator; + constructor(container: TreeMap); /** - * @inheritdoc + * Copy Constructor. + * + * @param container Another map to copy. + * @param compare A binary predicate determines order of elements. */ - rbegin(index: number): MapReverseIterator; + constructor(container: TreeMap, compare: (x: Key, y: Key) => boolean); /** - * @inheritdoc + * Range Constructor. + * + * @param begin nput interator of the initial position in a sequence. + * @param end Input interator of the final position in a sequence. */ - rend(): MapReverseIterator; + constructor(begin: Iterator>, end: Iterator>); /** - * @inheritdoc + * Range Constructor. + * + * @param begin nput interator of the initial position in a sequence. + * @param end Input interator of the final position in a sequence. + * @param compare A binary predicate determines order of elements. */ - rend(index: number): MapReverseIterator; + constructor(begin: Iterator>, end: Iterator>, compare: (x: Key, y: Key) => boolean); /** * @inheritdoc */ - bucket_count(): number; + clear(): void; /** * @inheritdoc */ - bucket_size(n: number): number; + find(key: Key): MapIterator; /** * @inheritdoc */ - max_load_factor(): number; + key_comp(): (x: Key, y: Key) => boolean; /** * @inheritdoc */ - max_load_factor(z: number): void; + value_comp(): (x: Pair, y: Pair) => boolean; /** * @inheritdoc */ - bucket(key: Key): number; + lower_bound(key: Key): MapIterator; /** * @inheritdoc */ - reserve(n: number): void; + upper_bound(key: Key): MapIterator; /** * @inheritdoc */ - rehash(n: number): void; + equal_range(key: Key): Pair, MapIterator>; /** * @hidden */ @@ -8892,7 +8424,7 @@ declare namespace std { *

Swap content.

* *

Exchanges the content of the container by the content of obj, which is another - * {@link HashMultiMap map} of the same type. Sizes abd container type may differ.

+ * {@link TreeMap map} of the same type. Sizes abd container type may differ.

* *

After the call to this member function, the elements in this container are those which were * in obj before the call, and the elements of obj are those which were in this. All @@ -8901,184 +8433,204 @@ declare namespace std { *

Notice that a non-member function exists with the same name, {@link std.swap swap}, overloading that * algorithm with an optimization that behaves like this member function.

* - * @param obj Another {@link HashMultiMap map container} of the same type of elements as this (i.e., + * @param obj Another {@link TreeMap map container} of the same type of elements as this (i.e., * with the same template parameters, Key and T) whose content is swapped - * with that of this {@link HashMultiMap container}. + * with that of this {@link TreeMap container}. */ - swap(obj: HashMultiMap): void; + swap(obj: TreeMap): void; /** * @inheritdoc */ swap(obj: base.IContainer>): void; } } -declare namespace std.HashMultiSet { - type iterator = std.SetIterator; - type reverse_iterator = std.SetReverseIterator; +declare namespace std.TreeMultiMap { + type iterator = std.MapIterator; + type reverse_iterator = std.MapReverseIterator; } declare namespace std { /** - *

Hashed, unordered Multiset.

+ *

Tree-structured multiple-key map.

* - *

{@link HashMultiSet HashMultiSets} are containers that store elements in no particular order, allowing fast - * retrieval of individual elements based on their value, much like {@link HashMultiSet} containers, - * but allowing different elements to have equivalent values.

+ *

{@link TreeMultiMap TreeMultiMaps} are associative containers that store elements formed by a combination of + * a key value and a mapped value, following a specific order, and where multiple elements can + * have equivalent keys.

* - *

In an {@link HashMultiSet}, the value of an element is at the same time its key, used to - * identify it. Keys are immutable, therefore, the elements in an {@link HashMultiSet} cannot be - * modified once in the container - they can be inserted and removed, though.

+ *

In a {@link TreeMultiMap}, the key values are generally used to sort and uniquely identify + * the elements, while the mapped values store the content associated to this key. The types of + * key and mapped value may differ, and are grouped together in member type + * value_type, which is a {@link Pair} type combining both:

* - *

Internally, the elements in the {@link HashMultiSet} are not sorted in any particular, but - * organized into buckets depending on their hash values to allow for fast access to individual - * elements directly by their values (with a constant average time complexity on average).

+ *

typedef Pair value_type;

* - *

Elements with equivalent values are grouped together in the same bucket and in such a way that an - * iterator can iterate through all of them. Iterators in the container are doubly linked iterators.

+ *

Internally, the elements in a {@link TreeMultiMap}are always sorted by its key following a + * strict weak ordering criterion indicated by its internal comparison method (of {@link less}).

* - *

- *

+ *

{@link TreeMultiMap}containers are generally slower than {@link HashMap} containers + * to access individual elements by their key, but they allow the direct iteration on subsets based + * on their order.

+ * + *

{@link TreeMultiMap TreeMultiMaps} are typically implemented as binary search trees.

+ * + *

< + * img src="http://samchon.github.io/typescript-stl/images/design/class_diagram/map_containers.png" style="max-width: 100%" />

* *

Container properties

*
*
Associative
- *
Elements in associative containers are referenced by their key and not by their absolute - * position in the container.
+ *
+ * Elements in associative containers are referenced by their key and not by their absolute + * position in the container. + *
* - *
Hashed
- *
Hashed containers organize their elements using hash tables that allow for fast access to elements - * by their key.
+ *
Ordered
+ *
+ * The elements in the container follow a strict order at all times. All inserted elements are + * given a position in this order. + *
* - *
Set
- *
The value of an element is also the key used to identify it.
+ *
Map
+ *
+ * Each element associates a key to a mapped value: + * Keys are meant to identify the elements whose main content is the mapped value. + *
* *
Multiple equivalent keys
- *
The container can hold multiple elements with equivalent keys.
+ *
Multiple elements in the container can have equivalent keys.
*
* - * @param Type of the elements. - * Each element in an {@link UnorderedMultiSet} is also identified by this value.. + * @param Type of the keys. Each element in a map is uniquely identified by its key value. + * @param Type of the mapped value. Each element in a map stores some data as its mapped value. * - * @reference http://www.cplusplus.com/reference/unordered_set/unordered_multiset + * @reference http://www.cplusplus.com/reference/map/multimap * @author Jeongho Nam */ - class HashMultiSet extends base.MultiSet { + class TreeMultiMap extends base.MultiMap implements base.ITreeMap { /** * @hidden */ - private hash_buckets_; + private tree_; /** * Default Constructor. */ constructor(); /** - * Construct from elements. - */ - constructor(items: T[]); - /** - * Copy Constructor. - */ - constructor(container: HashMultiSet); - /** - * Construct from range iterators. - */ - constructor(begin: Iterator, end: Iterator); - /** - * @inheritdoc - */ - clear(): void; - /** - * @inheritdoc + * Construct from compare. + * + * @param compare A binary predicate determines order of elements. */ - find(key: T): SetIterator; + constructor(compare: (x: Key, y: Key) => boolean); /** - * @inheritdoc + * Contruct from elements. + * + * @param array Elements to be contained. */ - count(key: T): number; + constructor(array: Array>); /** - * @inheritdoc + * Contruct from elements. + * + * @param array Elements to be contained. + * @param compare A binary predicate determines order of elements. */ - begin(): SetIterator; + constructor(array: Array>, compare: (x: Key, y: Key) => boolean); /** - * @inheritdoc + * Contruct from tuples. + * + * @param array Tuples to be contained. */ - begin(index: number): SetIterator; + constructor(array: Array<[Key, T]>); /** - * @inheritdoc + * Contruct from tuples. + * + * @param array Tuples to be contained. + * @param compare A binary predicate determines order of elements. */ - end(): SetIterator; + constructor(array: Array<[Key, T]>, compare: (x: Key, y: Key) => boolean); /** - * @inheritdoc + * Copy Constructor. + * + * @param container Another map to copy. */ - end(index: number): SetIterator; + constructor(container: TreeMultiMap); /** - * @inheritdoc + * Copy Constructor. + * + * @param container Another map to copy. + * @param compare A binary predicate determines order of elements. */ - rbegin(): SetReverseIterator; + constructor(container: TreeMultiMap, compare: (x: Key, y: Key) => boolean); /** - * @inheritdoc + * Range Constructor. + * + * @param begin nput interator of the initial position in a sequence. + * @param end Input interator of the final position in a sequence. */ - rbegin(index: number): SetReverseIterator; + constructor(begin: Iterator>, end: Iterator>); /** - * @inheritdoc + * Range Constructor. + * + * @param begin nput interator of the initial position in a sequence. + * @param end Input interator of the final position in a sequence. + * @param compare A binary predicate determines order of elements. */ - rend(): SetReverseIterator; + constructor(begin: Iterator>, end: Iterator>, compare: (x: Key, y: Key) => boolean); /** * @inheritdoc */ - rend(index: number): SetReverseIterator; + clear(): void; /** * @inheritdoc */ - bucket_count(): number; + find(key: Key): MapIterator; /** * @inheritdoc */ - bucket_size(n: number): number; + count(key: Key): number; /** * @inheritdoc */ - max_load_factor(): number; + key_comp(): (x: Key, y: Key) => boolean; /** * @inheritdoc */ - max_load_factor(z: number): void; + value_comp(): (x: Pair, y: Pair) => boolean; /** * @inheritdoc */ - bucket(key: T): number; + lower_bound(key: Key): MapIterator; /** * @inheritdoc */ - reserve(n: number): void; + upper_bound(key: Key): MapIterator; /** * @inheritdoc */ - rehash(n: number): void; + equal_range(key: Key): Pair, MapIterator>; /** * @hidden */ - protected _Insert_by_val(val: T): any; + protected _Insert_by_pair(pair: Pair): any; /** * @hidden */ - protected _Insert_by_hint(hint: SetIterator, val: T): SetIterator; + protected _Insert_by_hint(hint: MapIterator, pair: Pair): MapIterator; /** * @hidden */ - protected _Insert_by_range>(first: InputIterator, last: InputIterator): void; + protected _Insert_by_range>>(first: InputIterator, last: InputIterator): void; /** * @inheritdoc */ - protected _Handle_insert(first: SetIterator, last: SetIterator): void; + protected _Handle_insert(first: MapIterator, last: MapIterator): void; /** * @inheritdoc */ - protected _Handle_erase(first: SetIterator, last: SetIterator): void; + protected _Handle_erase(first: MapIterator, last: MapIterator): void; /** *

Swap content.

* *

Exchanges the content of the container by the content of obj, which is another - * {@link HashMultiSet set} of the same type. Sizes abd container type may differ.

+ * {@link TreeMapMulti map} of the same type. Sizes abd container type may differ.

* *

After the call to this member function, the elements in this container are those which were * in obj before the call, and the elements of obj are those which were in this. All @@ -9087,155 +8639,158 @@ declare namespace std { *

Notice that a non-member function exists with the same name, {@link std.swap swap}, overloading that * algorithm with an optimization that behaves like this member function.

* - * @param obj Another {@link HashMultiSet set container} of the same type of elements as this (i.e., + * @param obj Another {@link TreeMapMulti map container} of the same type of elements as this (i.e., * with the same template parameters, Key and T) whose content is swapped - * with that of this {@link HashMultiSet container}. + * with that of this {@link TreeMapMulti container}. */ - swap(obj: HashMultiSet): void; + swap(obj: TreeMultiMap): void; /** * @inheritdoc */ - swap(obj: base.IContainer): void; + swap(obj: base.IContainer>): void; } } -declare namespace std.HashSet { +declare namespace std.TreeMultiSet { type iterator = std.SetIterator; type reverse_iterator = std.SetReverseIterator; } declare namespace std { /** - *

Hashed, unordered set.

+ *

Tree-structured multiple-key set.

* - *

{@link HashSet}s are containers that store unique elements in no particular order, and which - * allow for fast retrieval of individual elements based on their value.

+ *

{@link TreeMultiSet TreeMultiSets} are containers that store elements following a specific order, and + * where multiple elements can have equivalent values.

* - *

In an {@link HashSet}, the value of an element is at the same time its key, that - * identifies it uniquely. Keys are immutable, therefore, the elements in an {@link HashSet} cannot be - * modified once in the container - they can be inserted and removed, though.

+ *

In a {@link TreeMultiSet}, the value of an element also identifies it (the value is itself + * the key, of type T). The value of the elements in a {@link TreeMultiSet} cannot + * be modified once in the container (the elements are always const), but they can be inserted or removed + * from the

* - *

Internally, the elements in the {@link HashSet} are not sorted in any particular order, but - * organized into buckets depending on their hash values to allow for fast access to individual elements - * directly by their values (with a constant average time complexity on average).

+ *

Internally, the elements in a {@link TreeMultiSet TreeMultiSets} are always sorted following a strict + * weak ordering criterion indicated by its internal comparison method (of {@link IComparable.less less}).

* - *

{@link HashSet} containers are faster than {@link TreeSet} containers to access individual - * elements by their key, although they are generally less efficient for range iteration through a - * subset of their elements.

+ *

{@link TreeMultiSet} containers are generally slower than {@link HashMultiSet} containers + * to access individual elements by their key, but they allow the direct iteration on subsets based on + * their order.

+ * + *

{@link TreeMultiSet TreeMultiSets} are typically implemented as binary search trees.

* *

- *

+ *

* *

Container properties

*
*
Associative
- *
Elements in associative containers are referenced by their key and not by their absolute - * position in the container.
+ *
+ * Elements in associative containers are referenced by their key and not by their absolute + * position in the container. + *
* - *
Hashed
- *
Hashed containers organize their elements using hash tables that allow for fast access to elements - * by their key.
+ *
Ordered
+ *
+ * The elements in the container follow a strict order at all times. All inserted elements are + * given a position in this order. + *
* *
Set
*
The value of an element is also the key used to identify it.
* - *
Unique keys
- *
No two elements in the container can have equivalent keys.
+ *
Multiple equivalent keys
+ *
Multiple elements in the container can have equivalent keys.
*
* - * @param Type of the elements. - * Each element in an {@link HashSet} is also uniquely identified by this value. + * @param Type of the elements. Each element in a {@link TreeMultiSet} container is also identified + * by this value (each value is itself also the element's key). * - * @reference http://www.cplusplus.com/reference/unordered_set/unordered_set + * @reference http://www.cplusplus.com/reference/set/multiset * @author Jeongho Nam */ - class HashSet extends base.UniqueSet implements base.IHashSet { + class TreeMultiSet extends base.MultiSet implements base.ITreeSet { /** * @hidden */ - private hash_buckets_; + private tree_; /** * Default Constructor. */ constructor(); /** - * Construct from elements. - */ - constructor(items: T[]); - /** - * Copy Constructor. - */ - constructor(container: HashSet); - /** - * Construct from range iterators. - */ - constructor(begin: Iterator, end: Iterator); - /** - * @inheritdoc - */ - clear(): void; - /** - * @inheritdoc - */ - find(key: T): SetIterator; - /** - * @inheritdoc + * Construct from compare. + * + * @param compare A binary predicate determines order of elements. */ - begin(): SetIterator; + constructor(compare: (x: T, y: T) => boolean); /** - * @inheritdoc + * Contruct from elements. + * + * @param array Elements to be contained. */ - begin(index: number): SetIterator; + constructor(array: Array); /** - * @inheritdoc + * Contruct from elements with compare. + * + * @param array Elements to be contained. + * @param compare A binary predicate determines order of elements. */ - end(): SetIterator; + constructor(array: Array, compare: (x: T, y: T) => boolean); /** - * @inheritdoc + * Copy Constructor. */ - end(index: number): SetIterator; + constructor(container: TreeMultiSet); /** - * @inheritdoc + * Copy Constructor with compare. + * + * @param container A container to be copied. + * @param compare A binary predicate determines order of elements. */ - rbegin(): SetReverseIterator; + constructor(container: TreeMultiSet, compare: (x: T, y: T) => boolean); /** - * @inheritdoc + * Range Constructor. + * + * @param begin Input interator of the initial position in a sequence. + * @param end Input interator of the final position in a sequence. */ - rbegin(index: number): SetReverseIterator; + constructor(begin: Iterator, end: Iterator); /** - * @inheritdoc + * Construct from range and compare. + * + * @param begin Input interator of the initial position in a sequence. + * @param end Input interator of the final position in a sequence. + * @param compare A binary predicate determines order of elements. */ - rend(): SetReverseIterator; + constructor(begin: Iterator, end: Iterator, compare: (x: T, y: T) => boolean); /** * @inheritdoc */ - rend(index: number): SetReverseIterator; + clear(): void; /** * @inheritdoc */ - bucket_count(): number; + find(val: T): SetIterator; /** * @inheritdoc */ - bucket_size(n: number): number; + count(val: T): number; /** * @inheritdoc */ - max_load_factor(): number; + key_comp(): (x: T, y: T) => boolean; /** * @inheritdoc */ - max_load_factor(z: number): void; + value_comp(): (x: T, y: T) => boolean; /** * @inheritdoc */ - bucket(key: T): number; + lower_bound(val: T): SetIterator; /** * @inheritdoc */ - reserve(n: number): void; + upper_bound(val: T): SetIterator; /** * @inheritdoc */ - rehash(n: number): void; + equal_range(val: T): Pair, SetIterator>; /** * @hidden */ @@ -9260,7 +8815,7 @@ declare namespace std { *

Swap content.

* *

Exchanges the content of the container by the content of obj, which is another - * {@link HashSet set} of the same type. Sizes abd container type may differ.

+ * {@link TreeMultiSet set} of the same type. Sizes abd container type may differ.

* *

After the call to this member function, the elements in this container are those which were * in obj before the call, and the elements of obj are those which were in this. All @@ -9269,617 +8824,678 @@ declare namespace std { *

Notice that a non-member function exists with the same name, {@link std.swap swap}, overloading that * algorithm with an optimization that behaves like this member function.

* - * @param obj Another {@link HashSet set container} of the same type of elements as this (i.e., + * @param obj Another {@link TreeMultiSet set container} of the same type of elements as this (i.e., * with the same template parameters, Key and T) whose content is swapped - * with that of this {@link HashSet container}. + * with that of this {@link TreeMultiSet container}. */ - swap(obj: HashSet): void; + swap(obj: TreeMultiSet): void; /** * @inheritdoc */ swap(obj: base.IContainer): void; } } -declare namespace std.List { - type iterator = std.ListIterator; - type reverse_iterator = std.ListReverseIterator; +declare namespace std.TreeSet { + type iterator = std.SetIterator; + type reverse_iterator = std.SetReverseIterator; } declare namespace std { /** - *

Doubly linked list.

+ *

Tree-structured set, std::set of STL.

* - *

{@link List}s are sequence containers that allow constant time insert and erase operations anywhere within the - * sequence, and iteration in both directions.

+ *

{@link TreeSet}s are containers that store unique elements following a specific order.

* - *

List containers are implemented as doubly-linked lists; Doubly linked lists can store each of the elements they - * contain in different and unrelated storage locations. The ordering is kept internally by the association to each - * element of a link to the element preceding it and a link to the element following it.

+ *

In a {@link TreeSet}, the value of an element also identifies it (the value is itself the + * key, of type T), and each value must be unique. The value of the elements in a + * {@link TreeSet} cannot be modified once in the container (the elements are always const), but they + * can be inserted or removed from the

* - *

They are very similar to forward_list: The main difference being that forward_list objects are single-linked - * lists, and thus they can only be iterated forwards, in exchange for being somewhat smaller and more efficient.

+ *

Internally, the elements in a {@link TreeSet} are always sorted following a specific strict weak + * ordering criterion indicated by its internal comparison method (of {@link less}).

* - *

Compared to other base standard sequence containers (array, vector and deque), lists perform generally better - * in inserting, extracting and moving elements in any position within the container for which an iterator has already - * been obtained, and therefore also in algorithms that make intensive use of these, like sorting algorithms.

+ *

{@link TreeSet} containers are generally slower than {@link HashSet} containers to access + * individual elements by their key, but they allow the direct iteration on subsets based on their + * order.

* - *

The main drawback of lists and forward_lists compared to these other sequence containers is that they lack - * direct access to the elements by their position; For example, to access the sixth element in a list, one has to - * iterate from a known position (like the beginning or the end) to that position, which takes linear time in the - * distance between these. They also consume some extra memory to keep the linking information associated to each - * element (which may be an important factor for large lists of small-sized elements).

+ *

{@link TreeSet}s are typically implemented as binary search trees.

* - *

- * - *

+ *

+ *

* *

Container properties

*
- *
Sequence
- *
Elements in sequence containers are ordered in a strict linear sequence. Individual elements are accessed by - * their position in this sequence.
+ *
Associative
+ *
+ * Elements in associative containers are referenced by their key and not by their absolute + * position in the container. + *
* - *
Doubly-linked list
- *
Each element keeps information on how to locate the next and the previous elements, allowing constant time - * insert and erase operations before or after a specific element (even of entire ranges), but no direct random - * access.
+ *
Ordered
+ *
+ * The elements in the container follow a strict order at all times. All inserted elements are + * given a position in this order. + *
+ * + *
Set
+ *
The value of an element is also the key used to identify it.
+ * + *
Unique keys
+ *
No two elements in the container can have equivalent keys.
*
* * @param Type of the elements. + * Each element in an {@link TreeSet} is also uniquely identified by this value. * - * @reference http://www.cplusplus.com/reference/list/list/ + * @reference http://www.cplusplus.com/reference/set/set * @author Jeongho Nam */ - class List extends base.Container implements base.IDequeContainer { + class TreeSet extends base.UniqueSet implements base.ITreeSet { /** * @hidden */ - private begin_; + private tree_; /** - * @hidden + * Default Constructor. */ - private end_; + constructor(); /** - * @hidden + * Construct from compare. + * + * @param compare A binary predicate determines order of elements. */ - private size_; + constructor(compare: (x: T, y: T) => boolean); /** - *

Default Constructor.

+ * Contruct from elements. * - *

Constructs an empty container, with no elements.

+ * @param array Elements to be contained. */ - constructor(); + constructor(array: Array); /** - *

Initializer list Constructor.

- * - *

Constructs a container with a copy of each of the elements in array, in the same order.

+ * Contruct from elements with compare. * - * @param array An array containing elements to be copied and contained. + * @param array Elements to be contained. + * @param compare A binary predicate determines order of elements. */ - constructor(items: Array); + constructor(array: Array, compare: (x: T, y: T) => boolean); /** - *

Fill Constructor.

- * - *

Constructs a container with n elements. Each element is a copy of val (if provided).

- * - * @param n Initial container size (i.e., the number of elements in the container at construction). - * @param val Value to fill the container with. Each of the n elements in the container is - * initialized to a copy of this value. + * Copy Constructor. */ - constructor(size: number, val: T); + constructor(container: TreeMultiSet); /** - *

Copy Constructor.

- * - *

Constructs a container with a copy of each of the elements in container, in the same order.

+ * Copy Constructor with compare. * - * @param container Another container object of the same type (with the same class template - * arguments T), whose contents are either copied or acquired. + * @param container A container to be copied. + * @param compare A binary predicate determines order of elements. */ - constructor(container: List); + constructor(container: TreeMultiSet, compare: (x: T, y: T) => boolean); /** - *

Range Constructor.

- * - *

Constructs a container with as many elements as the range (begin, end), with each - * element emplace-constructed from its corresponding element in that range, in the same order.

+ * Range Constructor. * * @param begin Input interator of the initial position in a sequence. * @param end Input interator of the final position in a sequence. */ constructor(begin: Iterator, end: Iterator); /** - * @inheritdoc + * Construct from range and compare. + * + * @param begin Input interator of the initial position in a sequence. + * @param end Input interator of the final position in a sequence. + * @param compare A binary predicate determines order of elements. */ - assign(n: number, val: T): void; + constructor(begin: Iterator, end: Iterator, compare: (x: T, y: T) => boolean); /** * @inheritdoc */ - assign>(begin: InputIterator, end: InputIterator): void; + clear(): void; /** * @inheritdoc */ - clear(): void; + find(val: T): SetIterator; /** * @inheritdoc */ - begin(): ListIterator; + key_comp(): (x: T, y: T) => boolean; /** * @inheritdoc */ - end(): ListIterator; + value_comp(): (x: T, y: T) => boolean; /** * @inheritdoc */ - rbegin(): ListReverseIterator; + lower_bound(val: T): SetIterator; /** * @inheritdoc */ - rend(): ListReverseIterator; + upper_bound(val: T): SetIterator; /** * @inheritdoc */ - size(): number; + equal_range(val: T): Pair, SetIterator>; /** - * @inheritdoc + * @hidden */ - front(): T; + protected _Insert_by_val(val: T): any; + protected _Insert_by_hint(hint: SetIterator, val: T): SetIterator; /** - * @inheritdoc + * @hidden */ - back(): T; + protected _Insert_by_range>(first: InputIterator, last: InputIterator): void; /** * @inheritdoc */ - push(...items: U[]): number; + protected _Handle_insert(first: SetIterator, last: SetIterator): void; /** * @inheritdoc */ - push_front(val: T): void; + protected _Handle_erase(first: SetIterator, last: SetIterator): void; /** - * @inheritdoc + *

Swap content.

+ * + *

Exchanges the content of the container by the content of obj, which is another + * {@link TreeSet set} of the same type. Sizes abd container type may differ.

+ * + *

After the call to this member function, the elements in this container are those which were + * in obj before the call, and the elements of obj are those which were in this. All + * iterators, references and pointers remain valid for the swapped objects.

+ * + *

Notice that a non-member function exists with the same name, {@link std.swap swap}, overloading that + * algorithm with an optimization that behaves like this member function.

+ * + * @param obj Another {@link TreeSet set container} of the same type of elements as this (i.e., + * with the same template parameters, Key and T) whose content is swapped + * with that of this {@link TreeSet container}. */ - push_back(val: T): void; + swap(obj: TreeSet): void; /** * @inheritdoc */ - pop_front(): void; + swap(obj: base.IContainer): void; + } +} +declare namespace std { + /** + *

Running on Node.

+ * + *

Test whether the JavaScript is running on Node.

+ * + * @references http://stackoverflow.com/questions/17575790/environment-detection-node-js-or-browser + */ + function is_node(): boolean; + /** + *

Pair of values.

+ * + *

This class couples together a pair of values, which may be of different types (T1 and + * T2). The individual values can be accessed through its public members {@link first} and + * {@link second}.

+ * + * @param Type of member {@link first}. + * @param Type of member {@link second}. + * + * @reference http://www.cplusplus.com/reference/utility/pair + * @author Jeongho Nam + */ + class Pair { /** - * @inheritdoc + *

A first value in the Pair.

*/ - pop_back(): void; + first: T1; /** - *

Insert an element.

- * - *

The container is extended by inserting a new element before the element at the specified - * position. This effectively increases the {@link List.size List size} by the amount of elements - * inserted.

- * - *

Unlike other standard sequence containers, {@link List} is specifically designed to be efficient - * inserting and removing elements in any position, even in the middle of the sequence.

- * - * @param position Position in the container where the new element is inserted. - * {@link iterator}> is a member type, defined as a - * {@link ListIterator bidirectional iterator} type that points to elements. - * @param val Value to be inserted as an element. - * - * @return An iterator that points to the newly inserted element; val. + *

A second value in the Pair.

*/ - insert(position: ListIterator, val: T): ListIterator; + second: T2; /** - *

Insert elements by repeated filling.

- * - *

The container is extended by inserting a new element before the element at the specified - * position. This effectively increases the {@link List.size List size} by the amount of elements - * inserted.

- * - *

Unlike other standard sequence containers, {@link List} is specifically designed to be efficient - * inserting and removing elements in any position, even in the middle of the sequence.

- * - * @param position Position in the container where the new elements are inserted. The {@link iterator} is a - * member type, defined as a {@link ListIterator bidirectional iterator} type that points to - * elements. - * @param size Number of elements to insert. - * @param val Value to be inserted as an element. + *

Construct from pair values.

* - * @return An iterator that points to the first of the newly inserted elements. + * @param first The first value of the Pair + * @param second The second value of the Pair */ - insert(position: ListIterator, size: number, val: T): ListIterator; + constructor(first: T1, second: T2); /** - *

Insert elements by range iterators.

- * - *

The container is extended by inserting a new element before the element at the specified - * position. This effectively increases the {@link List.size List size} by the amount of elements - * inserted.

- * - *

Unlike other standard sequence containers, {@link List} is specifically designed to be efficient - * inserting and removing elements in any position, even in the middle of the sequence.

+ *

Whether a Pair is equal with the Pair.

+ *

Compare each first and second value of two Pair(s) and returns whether they are equal or not.

* - * @param position Position in the container where the new elements are inserted. The {@link iterator} is a - * member type, defined as a {@link ListIterator bidirectional iterator} type that points to - * elements. - * @param begin An iterator specifying range of the begining element. - * @param end An iterator specifying range of the ending element. + *

If stored key and value in a Pair are not number or string but an object like a class or struct, + * the comparison will be executed by a member method (SomeObject)::equal_to(). If the object does not have + * the member method equal_to(), only address of pointer will be compared.

* - * @return An iterator that points to the first of the newly inserted elements. + * @param obj A Map to compare + * @return Indicates whether equal or not. */ - insert>(position: ListIterator, begin: InputIterator, end: InputIterator): ListIterator; + equal_to(pair: Pair): boolean; + less(pair: Pair): boolean; + } + /** + *

Construct {@link Pair} object.

+ * + *

Constructs a {@link Pair} object with its {@link Pair.first first} element set to x and its + * {@link Pair.second second} element set to y.

+ * + *

The template types can be implicitly deduced from the arguments passed to {@link make_pair}.

+ * + *

{@link Pair} objects can be constructed from other {@link Pair} objects containing different types, if the + * respective types are implicitly convertible.

+ * + * @param x Value for member {@link Pair.first first}. + * @param y Value for member {@link Pair.second second}. + * + * @return A {@link Pair} object whose elements {@link Pair.first first} and {@link Pair.second second} are set to + * x and y respectivelly. + */ + function make_pair(x: T1, y: T2): Pair; +} +declare namespace std.Vector { + type iterator = std.VectorIterator; + type reverse_iterator = std.VectorReverseIterator; +} +declare namespace std { + /** + *

Vector, the dynamic array.

+ * + *

{@link Vector}s are sequence containers representing arrays that can change in size.

+ * + *

Just like arrays, {@link Vector}s use contiguous storage locations for their elements, which means that + * their elements can also be accessed using offsets on regular pointers to its elements, and just as efficiently + * as in arrays. But unlike arrays, their size can change dynamically, with their storage being handled + * automatically by the

+ * + *

Internally, {@link Vector}s use a dynamically allocated array to store their elements. This array may need + * to be reallocated in order to grow in size when new elements are inserted, which implies allocating a new + * array and moving all elements to it. This is a relatively expensive task in terms of processing time, and + * thus, {@link Vector}s do not reallocate each time an element is added to the

+ * + *

Instead, {@link Vector} containers may allocate some extra storage to accommodate for possible growth, and + * thus the container may have an actual {@link capacity} greater than the storage strictly needed to contain its + * elements (i.e., its {@link size}). Libraries can implement different strategies for growth to balance between + * memory usage and reallocations, but in any case, reallocations should only happen at logarithmically growing + * intervals of {@link size} so that the insertion of individual elements at the end of the {@link Vector} can be + * provided with amortized constant time complexity (see {@link push_back push_back()}).

+ * + *

Therefore, compared to arrays, {@link Vector}s consume more memory in exchange for the ability to manage + * storage and grow dynamically in an efficient way.

+ * + *

Compared to the other dynamic sequence containers ({@link Deque}s, {@link List}s), {@link Vector Vectors} + * are very efficient accessing its elements (just like arrays) and relatively efficient adding or removing + * elements from its end. For operations that involve inserting or removing elements at positions other than the + * end, they perform worse than the others, and have less consistent iterators and references than {@link List}s. + *

+ * + *

+ * + *

+ * + *

Container properties

+ *
+ *
Sequence
+ *
+ * Elements in sequence containers are ordered in a strict linear sequence. Individual elements are + * accessed by their position in this sequence. + *
+ * + *
Dynamic array
+ *
+ * Allows direct access to any element in the sequence, even through pointer arithmetics, and provides + * relatively fast addition/removal of elements at the end of the sequence. + *
+ *
+ * + * @param Type of the elements. + * + * @reference http://www.cplusplus.com/reference/vector/vector + * @author Jeongho Nam + */ + class Vector extends Array implements base.IContainer, base.IArrayContainer { /** - *

Insert an element.

- * - *

The container is extended by inserting a new element before the element at the specified - * position. This effectively increases the {@link List.size List size} by the amount of elements - * inserted.

- * - *

Unlike other standard sequence containers, {@link List} is specifically designed to be efficient - * inserting and removing elements in any position, even in the middle of the sequence.

- * - * @param position Position in the container where the new element is inserted. - * {@link iterator}> is a member type, defined as a - * {@link ListReverseIterator bidirectional iterator} type that points to elements. - * @param val Value to be inserted as an element. + *

Default Constructor.

* - * @return An iterator that points to the newly inserted element; val. + *

Constructs an empty container, with no elements.

+ */ + constructor(); + /** + * @inheritdoc */ - insert(position: ListReverseIterator, val: T): ListReverseIterator; + constructor(array: Array); /** - *

Insert elements by repeated filling.

+ *

Initializer list Constructor.

* - *

The container is extended by inserting a new element before the element at the specified - * position. This effectively increases the {@link List.size List size} by the amount of elements - * inserted.

+ *

Constructs a container with a copy of each of the elements in array, in the same order.

* - *

Unlike other standard sequence containers, {@link List} is specifically designed to be efficient - * inserting and removing elements in any position, even in the middle of the sequence.

+ * @param array An array containing elements to be copied and contained. + */ + constructor(n: number); + /** + *

Fill Constructor.

* - * @param position Position in the container where the new elements are inserted. The {@link iterator} is a - * member type, defined as a {@link ListReverseIterator bidirectional iterator} type that points to - * elements. - * @param size Number of elements to insert. - * @param val Value to be inserted as an element. + *

Constructs a container with n elements. Each element is a copy of val (if provided).

* - * @return An iterator that points to the first of the newly inserted elements. + * @param n Initial container size (i.e., the number of elements in the container at construction). + * @param val Value to fill the container with. Each of the n elements in the container is + * initialized to a copy of this value. */ - insert(position: ListReverseIterator, size: number, val: T): ListReverseIterator; + constructor(n: number, val: T); /** - *

Insert elements by range iterators.

+ *

Copy Constructor.

* - *

The container is extended by inserting a new element before the element at the specified - * position. This effectively increases the {@link List.size List size} by the amount of elements - * inserted.

+ *

Constructs a container with a copy of each of the elements in container, in the same order.

* - *

Unlike other standard sequence containers, {@link List} is specifically designed to be efficient - * inserting and removing elements in any position, even in the middle of the sequence.

+ * @param container Another container object of the same type (with the same class template + * arguments T), whose contents are either copied or acquired. + */ + constructor(container: Vector); + /** + *

Range Constructor.

* - * @param position Position in the container where the new elements are inserted. The {@link iterator} is a - * member type, defined as a {@link ListReverseIterator bidirectional iterator} type that points to - * elements. - * @param begin An iterator specifying range of the begining element. - * @param end An iterator specifying range of the ending element. + *

Constructs a container with as many elements as the range (begin, end), with each + * element emplace-constructed from its corresponding element in that range, in the same order.

* - * @return An iterator that points to the first of the newly inserted elements. + * @param begin Input interator of the initial position in a sequence. + * @param end Input interator of the final position in a sequence. */ - insert>(position: ListReverseIterator, begin: InputIterator, end: InputIterator): ListReverseIterator; + constructor(begin: Iterator, end: Iterator); /** - * @hidden + * @inheritdoc */ - private insert_by_val(position, val); + assign>(begin: InputIterator, end: InputIterator): void; /** - * @hidden + * @inheritdoc */ - protected _Insert_by_repeating_val(position: ListIterator, size: number, val: T): ListIterator; + assign(n: number, val: T): void; /** - * @hidden + * @inheritdoc */ - protected _Insert_by_range>(position: ListIterator, begin: InputIterator, end: InputIterator): ListIterator; + reserve(size: number): void; /** - *

Erase an element.

- * - *

Removes from the {@link List} either a single element; position.

- * - *

This effectively reduces the container size by the number of element removed.

- * - *

Unlike other standard sequence containers, {@link List} objects are specifically designed to be - * efficient inserting and removing elements in any position, even in the middle of the sequence.

- * - * @param position Iterator pointing to a single element to be removed from the {@link List}. - * - * @return An iterator pointing to the element that followed the last element erased by the function call. - * This is the {@link end end()} if the operation erased the last element in the sequence. + * @inheritdoc */ - erase(position: ListIterator): ListIterator; + clear(): void; /** - *

Erase elements.

- * - *

Removes from the {@link List} container a range of elements.

- * - *

This effectively reduces the container {@link size} by the number of elements removed.

- * - *

Unlike other standard sequence containers, {@link List} objects are specifically designed to be - * efficient inserting and removing elements in any position, even in the middle of the sequence.

- * - * @param begin An iterator specifying a range of beginning to erase. - * @param end An iterator specifying a range of end to erase. - * - * @return An iterator pointing to the element that followed the last element erased by the function call. - * This is the {@link end end()} if the operation erased the last element in the sequence. + * @inheritdoc */ - erase(begin: ListIterator, end: ListIterator): ListIterator; + begin(): VectorIterator; /** - *

Erase an element.

- * - *

Removes from the {@link List} either a single element; position.

- * - *

This effectively reduces the container size by the number of element removed.

- * - *

Unlike other standard sequence containers, {@link List} objects are specifically designed to be - * efficient inserting and removing elements in any position, even in the middle of the sequence.

- * - * @param position Iterator pointing to a single element to be removed from the {@link List}. - * - * @return An iterator pointing to the element that followed the last element erased by the function call. - * This is the {@link rend rend()} if the operation erased the last element in the sequence. + * @inheritdoc */ - erase(position: ListReverseIterator): ListReverseIterator; + end(): VectorIterator; /** - *

Erase elements.

- * - *

Removes from the {@link List} container a range of elements.

- * - *

This effectively reduces the container {@link size} by the number of elements removed.

- * - *

Unlike other standard sequence containers, {@link List} objects are specifically designed to be - * efficient inserting and removing elements in any position, even in the middle of the sequence.

- * - * @param begin An iterator specifying a range of beginning to erase. - * @param end An iterator specifying a range of end to erase. - * - * @return An iterator pointing to the element that followed the last element erased by the function call. - * This is the {@link rend rend()} if the operation erased the last element in the sequence. + * @inheritdoc */ - erase(begin: ListReverseIterator, end: ListReverseIterator): ListReverseIterator; + rbegin(): VectorReverseIterator; /** - * @hidden + * @inheritdoc */ - protected _Erase_by_range(first: ListIterator, last: ListIterator): ListIterator; + rend(): VectorReverseIterator; /** - *

Remove duplicate values.

- * - *

Removes all but the first element from every consecutive group of equal elements in the

- * - *

Notice that an element is only removed from the {@link List} container if it compares equal to the - * element immediately preceding it. Thus, this function is especially useful for sorted lists.

+ * @inheritdoc */ - unique(): void; + size(): number; /** - *

Remove duplicate values.

+ * @inheritdoc + */ + capacity(): number; + /** + * @inheritdoc + */ + empty(): boolean; + /** + * @inheritdoc + */ + at(index: number): T; + /** + * @inheritdoc + */ + set(index: number, val: T): T; + /** + * @inheritdoc + */ + front(): T; + /** + * @inheritdoc + */ + back(): T; + /** + * @inheritdoc + */ + push_back(val: T): void; + /** + *

Insert an element.

* - *

Removes all but the first element from every consecutive group of equal elements in the

+ *

The {@link Vector} is extended by inserting new element before the element at the specified + * position, effectively increasing the container size by one.

* - *

The argument binary_pred is a specific comparison function that determine the uniqueness - * of an element. In fact, any behavior can be implemented (and not only an equality comparison), but notice - * that the function will call binary_pred(it.value, it.prev().value) for all pairs of elements - * (where it is an iterator to an element, starting from the second) and remove it - * from the {@link List} if the predicate returns true. + *

This causes an automatic reallocation of the allocated storage space if -and only if- the new + * {@link size} surpasses the current {@link capacity}.

* - *

Notice that an element is only removed from the {@link List} container if it compares equal to the - * element immediately preceding it. Thus, this function is especially useful for sorted lists.

+ *

Because {@link Vector}s use an Array as their underlying storage, inserting element in + * positions other than the {@link end end()} causes the container to relocate all the elements that were + * after position to its new position. This is generally an inefficient operation compared to the one + * performed for the same operation by other kinds of sequence containers (such as {@link List}).

* - * @param binary_pred Binary predicate that, taking two values of the same type than those contained in the - * {@link List}, returns true to remove the element passed as first argument - * from the container, and false otherwise. This shall be a function pointer - * or a function object. + * @param position Position in the {@link Vector} where the new element is inserted. + * {@link iterator} is a member type, defined as a + * {@link VectorIterator random access iterator} type that points to elements. + * @param val Value to be copied to the inserted element. + * + * @return An iterator that points to the newly inserted element. */ - unique(binary_pred: (left: T, right: T) => boolean): void; + insert(position: VectorIterator, val: T): VectorIterator; /** - *

Remove elements with specific value.

+ *

Insert elements by repeated filling.

* - *

Removes from the container all the elements that compare equal to val. This calls the - * destructor of these objects and reduces the container {@link size} by the number of elements removed.

+ *

The {@link Vector} is extended by inserting new elements before the element at the specified + * position, effectively increasing the container size by the number of elements inserted.

* - *

Unlike member function {@link List.erase}, which erases elements by their position (using an - * iterator), this function ({@link List.remove}) removes elements by their value.

+ *

This causes an automatic reallocation of the allocated storage space if -and only if- the new + * {@link size} surpasses the current {@link capacity}.

* - *

A similar function, {@link List.remove_if}, exists, which allows for a condition other than an - * equality comparison to determine whether an element is removed.

+ *

Because {@link Vector}s use an Array as their underlying storage, inserting elements in + * positions other than the {@link end end()} causes the container to relocate all the elements that were + * after position to their new positions. This is generally an inefficient operation compared to the + * one performed for the same operation by other kinds of sequence containers (such as {@link List}). * - * @param val Value of the elements to be removed. + * @param position Position in the {@link Vector} where the new elements are inserted. + * {@link iterator} is a member type, defined as a + * {@link VectorIterator random access iterator} type that points to elements. + * @param n Number of elements to insert. Each element is initialized to a copy of val. + * @param val Value to be copied (or moved) to the inserted elements. + * + * @return An iterator that points to the first of the newly inserted elements. */ - remove(val: T): void; + insert(position: VectorIterator, n: number, val: T): VectorIterator; /** - *

Remove elements fulfilling condition.

+ *

Insert elements by range iterators.

* - *

Removes from the container all the elements for which pred returns true. This - * calls the destructor of these objects and reduces the container {@link size} by the number of elements - * removed.

+ *

The {@link Vector} is extended by inserting new elements before the element at the specified + * position, effectively increasing the container size by the number of elements inserted by range + * iterators.

* - *

The function calls pred(it.value) for each element (where it is an iterator - * to that element). Any of the elements in the list for which this returns true, are removed - * from the

+ *

This causes an automatic reallocation of the allocated storage space if -and only if- the new + * {@link size} surpasses the current {@link capacity}.

* - * @param pred Unary predicate that, taking a value of the same type as those contained in the forward_list - * object, returns true for those values to be removed from the container, and - * false for those remaining. This can either be a function pointer or a function - * object. + *

Because {@link Vector}s use an Array as their underlying storage, inserting elements in + * positions other than the {@link end end()} causes the container to relocate all the elements that were + * after position to their new positions. This is generally an inefficient operation compared to the + * one performed for the same operation by other kinds of sequence containers (such as {@link List}). + * + * @param position Position in the {@link Vector} where the new elements are inserted. + * {@link iterator} is a member type, defined as a + * {@link VectorIterator random access iterator} type that points to elements. + * @param begin Input interator of the initial position in a sequence. + * @param end Input interator of the final position in a sequence. + * + * @return An iterator that points to the first of the newly inserted elements. */ - remove_if(pred: (val: T) => boolean): void; + insert>(position: VectorIterator, begin: InputIterator, end: InputIterator): VectorIterator; /** - *

Merge sorted {@link List Lists}.

- * - *

Merges obj into the {@link List} by transferring all of its elements at their respective - * ordered positions into the container (both containers shall already be ordered). - *

+ *

Insert an element.

* - *

This effectively removes all the elements in obj (which becomes {@link empty}), and inserts - * them into their ordered position within container (which expands in {@link size} by the number of elements - * transferred). The operation is performed without constructing nor destroying any element: they are - * transferred, no matter whether obj is an lvalue or an rvalue, or whether the value_type supports - * move-construction or not.

+ *

The {@link Vector} is extended by inserting new element before the element at the specified + * position, effectively increasing the container size by one.

* - *

This function requires that the {@link List} containers have their elements already ordered by value - * ({@link less}) before the call. For an alternative on unordered {@link List Lists}, see - * {@link List.splice}.

+ *

This causes an automatic reallocation of the allocated storage space if -and only if- the new + * {@link size} surpasses the current {@link capacity}.

* - *

Assuming such ordering, each element of obj is inserted at the position that corresponds to its - * value according to the strict weak ordering defined by {@link less}. The resulting order of equivalent - * elements is stable (i.e., equivalent elements preserve the relative order they had before the call, and - * existing elements precede those equivalent inserted from obj).

+ *

Because {@link Vector}s use an Array as their underlying storage, inserting element in + * positions other than the {@link end end()} causes the container to relocate all the elements that were + * after position to its new position. This is generally an inefficient operation compared to the one + * performed for the same operation by other kinds of sequence containers (such as {@link List}).

* - * The function does nothing if this == obj. + * @param position Position in the {@link Vector} where the new element is inserted. + * {@link iterator} is a member type, defined as a + * {@link VectorIterator random access iterator} type that points to elements. + * @param val Value to be copied to the inserted element. * - * @param obj A {@link List} object of the same type (i.e., with the same template parameters, T). - * Note that this function modifies obj no matter whether an lvalue or rvalue reference is - * passed. + * @return An iterator that points to the newly inserted element. */ - merge(obj: List): void; + insert(position: VectorReverseIterator, val: T): VectorReverseIterator; /** - *

Merge sorted {@link List Lists}.

- * - *

Merges obj into the {@link List} by transferring all of its elements at their respective - * ordered positions into the container (both containers shall already be ordered). - *

- * - *

This effectively removes all the elements in obj (which becomes {@link empty}), and inserts - * them into their ordered position within container (which expands in {@link size} by the number of elements - * transferred). The operation is performed without constructing nor destroying any element: they are - * transferred, no matter whether obj is an lvalue or an rvalue, or whether the value_type supports - * move-construction or not.

+ *

Insert elements by repeated filling.

* - *

The argument compare is a specific predicate to perform the comparison operation between - * elements. This comparison shall produce a strict weak ordering of the elements (i.e., a consistent - * transitive comparison, without considering its reflexiveness). + *

The {@link Vector} is extended by inserting new elements before the element at the specified + * position, effectively increasing the container size by the number of elements inserted.

* - *

This function requires that the {@link List} containers have their elements already ordered by - * compare before the call. For an alternative on unordered {@link List Lists}, see - * {@link List.splice}.

+ *

This causes an automatic reallocation of the allocated storage space if -and only if- the new + * {@link size} surpasses the current {@link capacity}.

* - *

Assuming such ordering, each element of obj is inserted at the position that corresponds to its - * value according to the strict weak ordering defined by compare. The resulting order of equivalent - * elements is stable (i.e., equivalent elements preserve the relative order they had before the call, and - * existing elements precede those equivalent inserted from obj).

+ *

Because {@link Vector}s use an Array as their underlying storage, inserting elements in + * positions other than the {@link end end()} causes the container to relocate all the elements that were + * after position to their new positions. This is generally an inefficient operation compared to the + * one performed for the same operation by other kinds of sequence containers (such as {@link List}). * - * The function does nothing if this == obj. + * @param position Position in the {@link Vector} where the new elements are inserted. + * {@link iterator} is a member type, defined as a + * {@link VectorIterator random access iterator} type that points to elements. + * @param n Number of elements to insert. Each element is initialized to a copy of val. + * @param val Value to be copied (or moved) to the inserted elements. * - * @param obj A {@link List} object of the same type (i.e., with the same template parameters, T). - * Note that this function modifies obj no matter whether an lvalue or rvalue reference is - * passed. - * @param compare Binary predicate that, taking two values of the same type than those contained in the - * {@link list}, returns true if the first argument is considered to go before - * the second in the strict weak ordering it defines, and false otherwise. - * This shall be a function pointer or a function object. + * @return An iterator that points to the first of the newly inserted elements. */ - merge(obj: List, compare: (left: T, right: T) => boolean): void; + insert(position: VectorReverseIterator, n: number, val: T): VectorReverseIterator; /** - *

Transfer elements from {@link List} to {@link List}.

+ *

Insert elements by range iterators.

* - *

Transfers elements from obj into the container, inserting them at position.

+ *

The {@link Vector} is extended by inserting new elements before the element at the specified + * position, effectively increasing the container size by the number of elements inserted by range + * iterators.

* - *

This effectively inserts all elements into the container and removes them from obj, altering - * the sizes of both containers. The operation does not involve the construction or destruction of any - * element. They are transferred, no matter whether obj is an lvalue or an rvalue, or whether the - * value_type supports move-construction or not.

+ *

This causes an automatic reallocation of the allocated storage space if -and only if- the new + * {@link size} surpasses the current {@link capacity}.

* - *

This first version (1) transfers all the elements of obj into the

+ *

Because {@link Vector}s use an Array as their underlying storage, inserting elements in + * positions other than the {@link end end()} causes the container to relocate all the elements that were + * after position to their new positions. This is generally an inefficient operation compared to the + * one performed for the same operation by other kinds of sequence containers (such as {@link List}). * - * @param position Position within the container where the elements of obj are inserted. - * @param obj A {@link List} object of the same type (i.e., with the same template parameters, T). + * @param position Position in the {@link Vector} where the new elements are inserted. + * {@link iterator} is a member type, defined as a + * {@link VectorIterator random access iterator} type that points to elements. + * @param begin Input interator of the initial position in a sequence. + * @param end Input interator of the final position in a sequence. + * + * @return An iterator that points to the first of the newly inserted elements. */ - splice(position: ListIterator, obj: List): void; + insert>(position: VectorReverseIterator, begin: InputIterator, end: InputIterator): VectorReverseIterator; /** - *

Transfer an element from {@link List} to {@link List}.

+ * @hidden + */ + private insert_by_val(position, val); + /** + * @hidden + */ + protected _Insert_by_repeating_val(position: VectorIterator, n: number, val: T): VectorIterator; + /** + * @hidden + */ + protected _Insert_by_range>(position: VectorIterator, first: InputIterator, last: InputIterator): VectorIterator; + /** + * @inheritdoc + */ + pop_back(): void; + /** + *

Erase element.

* - *

Transfers an element from obj, which is pointed by an {@link ListIterator iterator} it, - * into the container, inserting the element at specified position.

+ *

Removes from the {@link Vector} either a single element; position.

* - *

This effectively inserts an element into the container and removes it from obj, altering the - * sizes of both containers. The operation does not involve the construction or destruction of any element. - * They are transferred, no matter whether obj is an lvalue or an rvalue, or whether the value_type - * supports move-construction or not.

+ *

This effectively reduces the container size by the number of element removed.

* - *

This second version (2) transfers only the element pointed by it from obj into the - *

+ *

Because {@link Vector}s use an Array as their underlying storage, erasing an element in + * position other than the {@link end end()} causes the container to relocate all the elements after the + * segment erased to their new positions. This is generally an inefficient operation compared to the one + * performed for the same operation by other kinds of sequence containers (such as {@link List}).

* - * @param position Position within the container where the element of obj is inserted. - * @param obj A {@link List} object of the same type (i.e., with the same template parameters, T). - * This parameter may be this if position points to an element not actually - * being spliced. - * @param it {@link ListIterator Iterator} to an element in obj. Only this single element is - * transferred. + * @param position Iterator pointing to a single element to be removed from the {@link Vector}. + * + * @return An iterator pointing to the new location of the element that followed the last element erased by + * the function call. This is the {@link end end()} if the operation erased the last element in the + * sequence. */ - splice(position: ListIterator, obj: List, it: ListIterator): void; + erase(position: VectorIterator): VectorIterator; /** - *

Transfer elements from {@link List} to {@link List}.

+ *

Erase element.

* - *

Transfers elements from obj into the container, inserting them at position.

+ *

Removes from the Vector either a single element; position.

* - *

This effectively inserts those elements into the container and removes them from obj, altering - * the sizes of both containers. The operation does not involve the construction or destruction of any - * element. They are transferred, no matter whether obj is an lvalue or an rvalue, or whether the - * value_type supports move-construction or not.

+ *

This effectively reduces the container size by the number of elements removed.

* - *

This third version (3) transfers the range [begin, end) from obj into the - *

+ *

Because {@link Vector}s use an Array as their underlying storage, erasing elements in + * position other than the {@link end end()} causes the container to relocate all the elements after the + * segment erased to their new positions. This is generally an inefficient operation compared to the one + * performed for the same operation by other kinds of sequence containers (such as {@link List}).

* - * @param position Position within the container where the elements of obj are inserted. - * @param obj A {@link List} object of the same type (i.e., with the same template parameters, T). - * This parameter may be this if position points to an element not actually - * being spliced. - * @param begin {@link ListIterator An Iterator} specifying initial position of a range of elements in - * obj. Transfers the elements in the range [begin, end) to - * position. - * @param end {@link ListIterator An Iterator} specifying final position of a range of elements in - * obj. Transfers the elements in the range [begin, end) to - * position. Notice that the range includes all the elements between begin and - * end, including the element pointed by begin but not the one pointed by end. + * @param begin An iterator specifying a range of beginning to erase. + * @param end An iterator specifying a range of end to erase. + * + * @return An iterator pointing to the new location of the element that followed the last element erased by + * the function call. This is the {@link rend rend()} if the operation erased the last element in the + * sequence. */ - splice(position: ListIterator, obj: List, begin: ListIterator, end: ListIterator): void; + erase(first: VectorIterator, last: VectorIterator): VectorIterator; /** - *

Sort elements in

+ *

Erase element.

* - *

Sorts the elements in the {@link List}, altering their position within the

+ *

Removes from the {@link Vector} either a single element; position.

* - *

The sorting is performed by applying an algorithm that uses {@link less}. This comparison shall - * produce a strict weak ordering of the elements (i.e., a consistent transitive comparison, without - * considering its reflexiveness).

+ *

This effectively reduces the container size by the number of element removed.

* - *

The resulting order of equivalent elements is stable: i.e., equivalent elements preserve the relative - * order they had before the call.

+ *

Because {@link Vector}s use an Array as their underlying storage, erasing an element in + * position other than the {@link end end()} causes the container to relocate all the elements after the + * segment erased to their new positions. This is generally an inefficient operation compared to the one + * performed for the same operation by other kinds of sequence containers (such as {@link List}).

* - *

The entire operation does not involve the construction, destruction or copy of any element object. - * Elements are moved within the

+ * @param position Iterator pointing to a single element to be removed from the {@link Vector}. + * + * @return An iterator pointing to the new location of the element that followed the last element erased by + * the function call. This is the {@link rend rend()} if the operation erased the last element in the + * sequence. */ - sort(): void; + erase(position: VectorReverseIterator): VectorReverseIterator; /** - *

Sort elements in

+ *

Erase element.

* - *

Sorts the elements in the {@link List}, altering their position within the

+ *

Removes from the Vector either a single element; position.

* - *

The sorting is performed by applying an algorithm that uses compare. This comparison shall - * produce a strict weak ordering of the elements (i.e., a consistent transitive comparison, without - * considering its reflexiveness).

+ *

This effectively reduces the container size by the number of elements removed.

* - *

The resulting order of equivalent elements is stable: i.e., equivalent elements preserve the relative - * order they had before the call.

+ *

Because {@link Vector}s use an Array as their underlying storage, erasing elements in + * position other than the {@link end end()} causes the container to relocate all the elements after the + * segment erased to their new positions. This is generally an inefficient operation compared to the one + * performed for the same operation by other kinds of sequence containers (such as {@link List}).

* - *

The entire operation does not involve the construction, destruction or copy of any element object. - * Elements are moved within the

+ * @param begin An iterator specifying a range of beginning to erase. + * @param end An iterator specifying a range of end to erase. * - * @param compare Binary predicate that, taking two values of the same type of those contained in the - * {@link List}, returns true if the first argument goes before the second - * argument in the strict weak ordering it defines, and false otherwise. This - * shall be a function pointer or a function object. - */ - sort(compare: (left: T, right: T) => boolean): void; - /** - * @hidden + * @return An iterator pointing to the new location of the element that followed the last element erased by + * the function call. This is the {@link end end()} if the operation erased the last element in the + * sequence. */ - private qsort(first, last, compare); + erase(first: VectorReverseIterator, last: VectorReverseIterator): VectorReverseIterator; /** * @hidden */ - private partition(first, last, compare); + protected _Erase_by_range(first: VectorIterator, last: VectorIterator): VectorIterator; /** *

Swap content.

* *

Exchanges the content of the container by the content of obj, which is another - * {@link List container} object with same type of elements. Sizes and container type may differ.

+ * {@link Vector container} object with same type of elements. Sizes and container type may differ.

* *

After the call to this member function, the elements in this container are those which were in obj * before the call, and the elements of obj are those which were in this. All iterators, references and @@ -9888,11 +9504,11 @@ declare namespace std { *

Notice that a non-member function exists with the same name, {@link std.swap swap}, overloading that * algorithm with an optimization that behaves like this member function.

* - * @param obj Another {@link List container} of the same type of elements (i.e., instantiated + * @param obj Another {@link Vector container} of the same type of elements (i.e., instantiated * with the same template parameter, T) whose content is swapped with that of this - * {@link container List}. + * {@link container Vector}. */ - swap(obj: List): void; + obj(obj: Vector): void; /** * @inheritdoc */ @@ -9901,95 +9517,106 @@ declare namespace std { } declare namespace std { /** - *

An iterator, node of a List.

+ *

An iterator of Vector.

* *

- * + * *

* + * @param Type of the elements. + * * @author Jeongho Nam */ - class ListIterator extends Iterator { + class VectorIterator extends Iterator implements base.IArrayIterator { /** - * @hidden + * Sequence number of iterator in the source {@link Vector}. */ - private prev_; + private index_; /** - * @hidden + *

Construct from the source {@link Vector container}.

+ * + *

Note

+ *

Do not create the iterator directly, by yourself.

+ *

Use {@link Vector.begin begin()}, {@link Vector.end end()} in {@link Vector container} instead.

+ * + * @param source The source {@link Vector container} to reference. + * @param index Sequence number of the element in the source {@link Vector}. */ - private next_; + constructor(source: Vector, index: number); /** * @hidden */ - private value_; + private vector; /** - *

Construct from the source {@link List container}.

- * - *

Note

- *

Do not create the iterator directly, by yourself.

- *

Use {@link List.begin begin()}, {@link List.end end()} in {@link List container} instead.

+ * @inheritdoc + */ + /** + * Set value of the iterator is pointing to. * - * @param source The source {@link List container} to reference. - * @param prev A refenrece of previous node ({@link ListIterator iterator}). - * @param next A refenrece of next node ({@link ListIterator iterator}). - * @param value Value to be stored in the node (iterator). + * @param val Value to set. */ - constructor(source: List, prev: ListIterator, next: ListIterator, value: T); - private list(); + value: T; /** - * @inheritdoc + * Get index. */ - prev(): ListIterator; + index: number; /** * @inheritdoc */ - next(): ListIterator; + prev(): VectorIterator; /** * @inheritdoc */ - advance(step: number): ListIterator; + next(): VectorIterator; /** * @inheritdoc */ + advance(n: number): VectorIterator; /** - * Set value of the iterator is pointing to. + *

Whether an iterator is equal with the iterator.

* - * @param val Value to set. - */ - value: T; - /** - * @inheritdoc + *

Compare two iterators and returns whether they are equal or not.

+ * + *

Note

+ *

Iterator's equal_to() only compare souce container and index number.

+ * + *

Although elements in a pair, key and value are equal_to, if the source map or + * index number is different, then the {@link equal_to equal_to()} will return false. If you want to + * compare the elements of a pair, compare them directly by yourself.

+ * + * @param obj An iterator to compare + * @return Indicates whether equal or not. */ - equal_to(obj: ListIterator): boolean; + equal_to(obj: VectorIterator): boolean; /** * @inheritdoc */ - swap(obj: ListIterator): void; + swap(obj: VectorIterator): void; } } declare namespace std { /** - *

A reverse-iterator of List.

+ *

A reverse-iterator of Vector.

* *

- * + * *

* * @param Type of the elements. * * @author Jeongho Nam */ - class ListReverseIterator extends ReverseIterator, ListReverseIterator> { + class VectorReverseIterator extends ReverseIterator, VectorReverseIterator> implements base.IArrayIterator { /** * Construct from base iterator. * * @param base A reference of the base iterator, which iterates in the opposite direction. */ - constructor(base: ListIterator); + constructor(base: VectorIterator); /** * @hidden */ - protected create_neighbor(base: ListIterator): ListReverseIterator; + protected create_neighbor(base: VectorIterator): VectorReverseIterator; /** * @inheritdoc */ @@ -9999,2091 +9626,2464 @@ declare namespace std { * @param val Value to set. */ value: T; + /** + * Get index. + */ + index: number; } } -declare namespace std.Vector { - type iterator = std.VectorIterator; - type reverse_iterator = std.VectorReverseIterator; +declare namespace std.base { + /** + *

Static class holding enumeration codes of color of Red-black tree.

+ * + *

Color codes imposed to nodes of RB-Tree are following those rules:

+ * + *
    + *
  1. A node is either red or black.
  2. + *
  3. The root is black. This rule is sometimes omitted. Since the root can + * always be changed from red to black, but not + * necessarily vice versa, this rule has little effect on analysis.
  4. + *
  5. All leaves (NIL; null) are black.
  6. + *
  7. If a node is red, then both its children are + * black.
  8. + *
  9. Every path from a given node to any of its descendant NIL nodes contains the same number of + * black nodes. Some definitions: the number of + * black nodes from the root to a node is the node's + * black depth; the uniform number of black + * nodes in all paths from root to the leaves is called the black-height of + * the red-black tree.
  10. + *
+ * + * @author Migrated by Jeongho Nam + */ + enum Color { + /** + *

Code of color black.

+ * + *
    + *
  • Those are clearly black: root, leaf nodes or children nodes of red.
  • + *
  • Every path from a given nodes containes the same number of black nodes exclude NIL(s).
  • + *
+ */ + BLACK = 0, + /** + *

Code of color red.

+ */ + RED = 1, + } } -declare namespace std { +declare namespace std.base { + enum Hash { + MIN_SIZE = 10, + RATIO = 1, + MAX_RATIO = 2, + } /** - *

Vector, the dynamic array.

+ *

Hask buckets.

* - *

{@link Vector}s are sequence containers representing arrays that can change in size.

+ * @author Jeongho Nam + */ + class HashBuckets { + /** + * @hidden + */ + private buckets_; + /** + * @hidden + */ + private item_size_; + /** + * Default Constructor. + */ + constructor(); + /** + *

Reconstruction of hash table.

+ * + *

All the elements in the hash buckets are rearranged according to their hash value into the new set of + * buckets. This may alter the order of iteration of elements within the container.

+ * + *

Notice that {@link rehash rehashes} are automatically performed whenever its number of elements is going + * to greater than its own {@link capacity}.

+ * + * @param size Number of bucket size to rehash. + */ + rehash(size: number): void; + clear(): void; + size(): number; + item_size(): number; + capacity(): number; + at(index: number): Vector; + hash_index(val: T): number; + insert(val: T): void; + erase(val: T): void; + } +} +declare namespace std.base { + /** + *

Common interface for hash map.

* - *

Just like arrays, {@link Vector}s use contiguous storage locations for their elements, which means that - * their elements can also be accessed using offsets on regular pointers to its elements, and just as efficiently - * as in arrays. But unlike arrays, their size can change dynamically, with their storage being handled - * automatically by the

+ *

{@link IHashMap}s are associative containers that store elements formed by the combination of + * a key value and a mapped value.

* - *

Internally, {@link Vector}s use a dynamically allocated array to store their elements. This array may need - * to be reallocated in order to grow in size when new elements are inserted, which implies allocating a new - * array and moving all elements to it. This is a relatively expensive task in terms of processing time, and - * thus, {@link Vector}s do not reallocate each time an element is added to the

+ *

In an {@link IHashMap}, the key value is generally used to uniquely identify the + * element, while the mapped value is an object with the content associated to this key. + * Types of key and mapped value may differ.

* - *

Instead, {@link Vector} containers may allocate some extra storage to accommodate for possible growth, and - * thus the container may have an actual {@link capacity} greater than the storage strictly needed to contain its - * elements (i.e., its {@link size}). Libraries can implement different strategies for growth to balance between - * memory usage and reallocations, but in any case, reallocations should only happen at logarithmically growing - * intervals of {@link size} so that the insertion of individual elements at the end of the {@link Vector} can be - * provided with amortized constant time complexity (see {@link push_back push_back()}).

+ *

Internally, the elements in the {@link IHashMap} are not sorted in any particular order with + * respect to either their key or mapped values, but organized into buckets depending on + * their hash values to allow for fast access to individual elements directly by their key values + * (with a constant average time complexity on average).

* - *

Therefore, compared to arrays, {@link Vector}s consume more memory in exchange for the ability to manage - * storage and grow dynamically in an efficient way.

+ *

Elements with equivalent keys are grouped together in the same bucket and in such a way that + * an iterator can iterate through all of them. Iterators in the container are doubly linked iterators.

* - *

Compared to the other dynamic sequence containers ({@link Deque}s, {@link List}s), {@link Vector Vectors} - * are very efficient accessing its elements (just like arrays) and relatively efficient adding or removing - * elements from its end. For operations that involve inserting or removing elements at positions other than the - * end, they perform worse than the others, and have less consistent iterators and references than {@link List}s. + *

+ * *

* - *

- * - *

- * *

Container properties

*
- *
Sequence
- *
- * Elements in sequence containers are ordered in a strict linear sequence. Individual elements are - * accessed by their position in this sequence. - *
+ *
Associative
+ *
Elements in associative containers are referenced by their key and not by their absolute + * position in the container.
* - *
Dynamic array
- *
- * Allows direct access to any element in the sequence, even through pointer arithmetics, and provides - * relatively fast addition/removal of elements at the end of the sequence. - *
+ *
Hashed
+ *
Hashed containers organize their elements using hash tables that allow for fast access to elements + * by their key.
+ * + *
Map
+ *
Each element associates a key to a mapped value: + * Keys are meant to identify the elements whose main content is the mapped value.
*
* - * @param Type of the elements. + * @param Type of the key values. + * Each element in an {@link IHashMap} is identified by a key value. + * @param Type of the mapped value. + * Each element in an {@link IHashMap} is used to store some data as its mapped value. * - * @reference http://www.cplusplus.com/reference/vector/vector + * @reference http://www.cplusplus.com/reference/unordered_map * @author Jeongho Nam */ - class Vector extends Array implements base.IContainer, base.IArrayContainer { - /** - *

Default Constructor.

- * - *

Constructs an empty container, with no elements.

- */ - constructor(); - /** - * @inheritdoc - */ - constructor(array: Array); + interface IHashMap { /** - *

Initializer list Constructor.

+ *

Return iterator to beginning.

* - *

Constructs a container with a copy of each of the elements in array, in the same order.

+ *

Returns an iterator pointing to the first element in the {@link IHashMap}.

* - * @param array An array containing elements to be copied and contained. + *

Notice that an {@link IHashMap} object makes no guarantees on which specific element is considered its + * first element. But, in any case, the range that goes from its begin to its end covers all the elements in the + * container, until invalidated.

+ * + * @return An iterator to the first element in the container. */ - constructor(n: number); + begin(): MapIterator; /** - *

Fill Constructor.

+ *

Return iterator to beginning.

* - *

Constructs a container with n elements. Each element is a copy of val (if provided).

+ *

Returns an iterator pointing to the first element in one of buckets in the {@link IHashMap}.

* - * @param n Initial container size (i.e., the number of elements in the container at construction). - * @param val Value to fill the container with. Each of the n elements in the container is - * initialized to a copy of this value. - */ - constructor(n: number, val: T); - /** - *

Copy Constructor.

+ *

Notice that an {@link IHashMap} object makes no guarantees on which specific element is considered its + * first element. But, in any case, the range that goes from its begin to its end covers all the elements in the + * bucket, until invalidated.

* - *

Constructs a container with a copy of each of the elements in container, in the same order.

+ * @param index Bucket number. This shall be lower than {@link bucket_count}. * - * @param container Another container object of the same type (with the same class template - * arguments T), whose contents are either copied or acquired. + * @return An iterator to the first element in the bucket. */ - constructor(container: Vector); + begin(index: number): MapIterator; /** - *

Range Constructor.

+ *

Return iterator to end.

* - *

Constructs a container with as many elements as the range (begin, end), with each - * element emplace-constructed from its corresponding element in that range, in the same order.

+ *

Returns an iterator pointing to the past-the-end element in the {@link HaspMap} container.

* - * @param begin Input interator of the initial position in a sequence. - * @param end Input interator of the final position in a sequence. - */ - constructor(begin: Iterator, end: Iterator); - /** - * @inheritdoc - */ - assign>(begin: InputIterator, end: InputIterator): void; - /** - * @inheritdoc - */ - assign(n: number, val: T): void; - /** - * @inheritdoc - */ - reserve(size: number): void; - /** - * @inheritdoc - */ - clear(): void; - /** - * @inheritdoc - */ - begin(): VectorIterator; - /** - * @inheritdoc + *

The iterator returned by end does not point to any element, but to the position that follows the last + * element in the {@link HaspMap} container (its past-the-end position). Thus, the value returned shall + * not be dereferenced - it is generally used to describe the open-end of a range, such as + * [begin, end).

+ * + *

Notice that an {@link IHashMap} object makes no guarantees on which order its elements follow. But, in any + * case, the range that goes from its begin to its end covers all the elements in the container (or the bucket), + * until invalidated.

+ * + * @return An iterator to the element past the end of the container. */ - end(): VectorIterator; + end(): MapIterator; /** - * @inheritdoc + *

Return iterator to end.

+ * + *

Returns an iterator pointing to the past-the-end element in the {@link HaspMap} container.

+ * + *

The iterator returned by end does not point to any element, but to the position that follows the last + * element in the {@link HaspMap} container (its past-the-end position). Thus, the value returned shall + * not be dereferenced - it is generally used to describe the open-end of a range, such as + * [begin, end).

+ * + *

Notice that an {@link IHashMap} object makes no guarantees on which order its elements follow. But, in any + * case, the range that goes from its begin to its end covers all the elements in the container (or the bucket), + * until invalidated.

+ * + * @param index Bucket number. This shall be lower than {@link bucket_count}. + * + * @return An iterator to the element past the end of the bucket. */ - rbegin(): VectorReverseIterator; + end(index: number): MapIterator; /** - * @inheritdoc + *

Return {@link MapReverseIterator reverse iterator} to reverse beginning.

+ * + *

Returns a {@link MapReverseIterator reverse iterator} pointing to the last element in the {@link IHashMap} + * (i.e., its reverse beginning).

+ * + * {@link MapReverseIterator Reverse iterators} iterate backwards: increasing them moves them towards the + * beginning of the container.

+ * + *

{@link rbegin} points to the element preceding the one that would be pointed to by member {@link end}.

+ * + *

Notice that an {@link IHashMap} object makes no guarantees on which specific element is considered its + * first element. But, in any case, the range that goes from its begin to its end covers all the elements in the + * bucket, until invalidated.

+ * + * @return A {@link MapReverseIterator reverse iterator} to the reverse beginning of the sequence */ - rend(): VectorReverseIterator; + rbegin(): MapReverseIterator; /** - * @inheritdoc + *

Return {@link MapReverseIterator reverse iterator} to reverse beginning.

+ * + *

Returns a {@link MapReverseIterator reverse iterator} pointing to the last element in one of buckets in the + * {@link IHashMap} (i.e., its reverse beginning).

+ * + * {@link MapReverseIterator Reverse iterators} iterate backwards: increasing them moves them towards the + * beginning of the container.

+ * + *

{@link rbegin} points to the element preceding the one that would be pointed to by member {@link end}.

+ * + *

Notice that an {@link IHashMap} object makes no guarantees on which specific element is considered its + * first element. But, in any case, the range that goes from its begin to its end covers all the elements in the + * bucket, until invalidated.

+ * + * @param index Bucket number. This shall be lower than {@link bucket_count}. + * + * @return A {@link MapReverseIterator reverse iterator} to the reverse beginning of the sequence */ - size(): number; + rbegin(index: number): MapReverseIterator; /** - * @inheritdoc + *

Return {@link MapReverseIterator reverse iterator} to reverse end.

+ * + *

Returns a {@link MapReverseIterator reverse iterator} pointing to the theoretical element right before + * the first element in the {@link IHashMap hash map container} (which is considered its reverse end).

+ * + *

The range between {@link IHashMap}.{@link rbegin} and {@link IHashMap}.{@link rend} contains all the + * elements of the container (in reverse order).

+ * + *

Notice that an {@link IHashMap} object makes no guarantees on which order its elements follow. But, in any + * case, the range that goes from its begin to its end covers all the elements in the container (or the bucket), + * until invalidated.

+ * + * @return A {@link MapReverseIterator reverse iterator} to the reverse end of the sequence. */ - capacity(): number; + rend(): MapReverseIterator; /** - * @inheritdoc + *

Return {@link MapReverseIterator reverse iterator} to reverse end.

+ * + *

Returns a {@link MapReverseIterator reverse iterator} pointing to the theoretical element right before + * the first element in one of buckets in the {@link IHashMap hash map container} (which is considered its + * reverse end).

+ * + *

The range between {@link IHashMap}.{@link rbegin} and {@link IHashMap}.{@link rend} contains all the + * elements of the container (in reverse order).

+ * + *

Notice that an {@link IHashMap} object makes no guarantees on which order its elements follow. But, in any + * case, the range that goes from its begin to its end covers all the elements in the container (or the bucket), + * until invalidated.

+ * + * @param index Bucket number. This shall be lower than {@link bucket_count}. + * + * @return A {@link MapReverseIterator reverse iterator} to the reverse end of the sequence. */ - empty(): boolean; + rend(index: number): MapReverseIterator; /** - * @inheritdoc + *

Return number of buckets.

+ * + *

Returns the number of buckets in the {@link IHashMap} container.

+ * + *

A bucket is a slot in the container's internal hash table to which elements are assigned based on the + * hash value of their key.

+ * + *

The number of buckets influences directly the {@link load_factor load factor} of the container's hash + * table (and thus the probability of collision). The container automatically increases the number of buckets to + * keep the load factor below a specific threshold (its {@link max_load_factor}), causing a {@link rehash} each + * time the number of buckets needs to be increased.

+ * + * @return The current amount of buckets. */ - at(index: number): T; + bucket_count(): number; /** - * @inheritdoc + *

Return bucket size.

+ * + *

Returns the number of elements in bucket n.

+ * + *

A bucket is a slot in the container's internal hash table to which elements are assigned based on the hash + * value of their key.

+ * + *

The number of elements in a bucket influences the time it takes to access a particular element in the + * bucket. The container automatically increases the number of buckets to keep the {@link load_cator load factor} + * (which is the average bucket size) below its {@link max_load_factor}.

+ * + * @param n Bucket number. This shall be lower than {@link bucket_count}. + * + * @return The number of elements in bucket n. */ - set(index: number, val: T): T; + bucket_size(n: number): number; /** - * @inheritdoc + *

Get maximum load factor.

+ * + *

Returns the current maximum load factor for the {@link HashMultiMap} container.

+ * + *

The load factor is the ratio between the number of elements in the container (its {@link size}) and the + * number of buckets ({@link bucket_count}).

+ * + *

By default, {@link HashMultiMap} containers have a {@link max_load_factor} of 1.0.

+ * + *

The load factor influences the probability of collision in the hash table (i.e., the probability of two + * elements being located in the same bucket). The container uses the value of max_load_factor as the threshold + * that forces an increase in the number of buckets (and thus causing a {@link rehash}).

+ * + *

Note though, that implementations may impose an upper limit on the number of buckets (see + * {@link max_bucket_count}), which may force the container to ignore the {@link max_load_factor}.

+ * + * @return The current load factor. */ - front(): T; + max_load_factor(): number; /** - * @inheritdoc + *

Set maximum load factor.

+ * + *

Sets z as the cnew maximum load factor for the {@link HashMultiMap} container.

+ * + *

The load factor is the ratio between the number of elements in the container (its {@link size}) and the + * number of buckets ({@link bucket_count}).

+ * + *

By default, {@link HashMultiMap} containers have a {@link max_load_factor} of 1.0.

+ * + *

The load factor influences the probability of collision in the hash table (i.e., the probability of two + * elements being located in the same bucket). The container uses the value of max_load_factor as the threshold + * that forces an increase in the number of buckets (and thus causing a {@link rehash}).

+ * + *

Note though, that implementations may impose an upper limit on the number of buckets (see + * {@link max_bucket_count}), which may force the container to ignore the {@link max_load_factor}.

+ * + * @param z The new maximum load factor. */ - back(): T; + max_load_factor(z: number): void; /** - * @inheritdoc + *

Locate element's bucket.

+ * + *

Returns the bucket number where the element with key is located.

+ * + *

A bucket is a slot in the container's internal hash table to which elements are assigned based on the + * hash value of their key. Buckets are numbered from 0 to ({@link bucket_count} - 1).

+ * + *

Individual elements in a bucket can be accessed by means of the range iterators returned by + * {@link begin} and {@link end}.

+ * + * @param key Key whose bucket is to be located. */ - push_back(val: T): void; + bucket(key: Key): number; /** - *

Insert an element.

- * - *

The {@link Vector} is extended by inserting new element before the element at the specified - * position, effectively increasing the container size by one.

+ *

Request a capacity change.

* - *

This causes an automatic reallocation of the allocated storage space if -and only if- the new - * {@link size} surpasses the current {@link capacity}.

+ *

Sets the number of buckets in the container ({@link bucket_count}) to the most appropriate to contain at + * least n elements.

* - *

Because {@link Vector}s use an Array as their underlying storage, inserting element in - * positions other than the {@link end end()} causes the container to relocate all the elements that were - * after position to its new position. This is generally an inefficient operation compared to the one - * performed for the same operation by other kinds of sequence containers (such as {@link List}).

+ *

If n is greater than the current {@link bucket_count} multiplied by the {@link max_load_factor}, + * the container's {@link bucket_count} is increased and a {@link rehash} is forced.

* - * @param position Position in the {@link Vector} where the new element is inserted. - * {@link iterator} is a member type, defined as a - * {@link VectorIterator random access iterator} type that points to elements. - * @param val Value to be copied to the inserted element. + *

If n is lower than that, the function may have no effect.

* - * @return An iterator that points to the newly inserted element. + * @param n The number of elements requested as minimum capacity. */ - insert(position: VectorIterator, val: T): VectorIterator; + reserve(n: number): void; /** - *

Insert elements by repeated filling.

+ *

Set number of buckets.

* - *

The {@link Vector} is extended by inserting new elements before the element at the specified - * position, effectively increasing the container size by the number of elements inserted.

+ *

Sets the number of buckets in the container to n or more.

* - *

This causes an automatic reallocation of the allocated storage space if -and only if- the new - * {@link size} surpasses the current {@link capacity}.

+ *

If n is greater than the current number of buckets in the container ({@link bucket_count}), a + * {@link HashBuckets.rehash rehash} is forced. The new {@link bucket_count bucket count} can either be equal or + * greater than n.

* - *

Because {@link Vector}s use an Array as their underlying storage, inserting elements in - * positions other than the {@link end end()} causes the container to relocate all the elements that were - * after position to their new positions. This is generally an inefficient operation compared to the - * one performed for the same operation by other kinds of sequence containers (such as {@link List}). + *

If n is lower than the current number of buckets in the container ({@link bucket_count}), the + * function may have no effect on the {@link bucket_count bucket count} and may not force a + * {@link HashBuckets.rehash rehash}.

* - * @param position Position in the {@link Vector} where the new elements are inserted. - * {@link iterator} is a member type, defined as a - * {@link VectorIterator random access iterator} type that points to elements. - * @param n Number of elements to insert. Each element is initialized to a copy of val. - * @param val Value to be copied (or moved) to the inserted elements. + *

A {@link HashBuckets.rehash rehash} is the reconstruction of the hash table: All the elements in the + * container are rearranged according to their hash value into the new set of buckets. This may alter the order + * of iteration of elements within the container.

* - * @return An iterator that points to the first of the newly inserted elements. - */ - insert(position: VectorIterator, n: number, val: T): VectorIterator; - /** - *

Insert elements by range iterators.

+ *

{@link HashBuckets.rehash Rehashes} are automatically performed by the container whenever its + * {@link load_factor load factor} is going to surpass its {@link max_load_factor} in an operation.

* - *

The {@link Vector} is extended by inserting new elements before the element at the specified - * position, effectively increasing the container size by the number of elements inserted by range - * iterators.

+ *

Notice that this function expects the number of buckets as argument. A similar function exists, + * {@link reserve}, that expects the number of elements in the container as argument.

* - *

This causes an automatic reallocation of the allocated storage space if -and only if- the new - * {@link size} surpasses the current {@link capacity}.

+ * @param n The minimum number of buckets for the container hash table. + */ + rehash(n: number): void; + } +} +declare namespace std.base { + /** + *

Hash buckets storing {@link MapIterator MapIterators}.

+ * + *

+ * + *

+ * + * @author Jeongho Nam + */ + class MapHashBuckets extends HashBuckets> { + private map; + constructor(map: MapContainer); + find(key: K): MapIterator; + } +} +declare namespace std.base { + /** + *

A common interface for hash set.

+ * + *

{@link IHashSet}s are containers that store unique elements in no particular order, and which + * allow for fast retrieval of individual elements based on their value.

+ * + *

In an {@link IHashSet}, the value of an element is at the same time its key, that + * identifies it uniquely. Keys are immutable, therefore, the elements in an {@link IHashSet} cannot be + * modified once in the container - they can be inserted and removed, though.

+ * + *

Internally, the elements in the {@link IHashSet} are not sorted in any particular order, but + * organized into buckets depending on their hash values to allow for fast access to individual elements + * directly by their values (with a constant average time complexity on average).

+ * + *

{@link IHashSet} containers are faster than {@link TreeSet} containers to access individual + * elements by their key, although they are generally less efficient for range iteration through a + * subset of their elements.

+ * + *

+ * + *

+ * + *

Container properties

+ *
+ *
Associative
+ *
Elements in associative containers are referenced by their key and not by their absolute + * position in the container.
+ * + *
Hashed
+ *
Hashed containers organize their elements using hash tables that allow for fast access to elements + * by their key.
+ * + *
Set
+ *
The value of an element is also the key used to identify it.
+ *
+ * + * @param Type of the elements. + * Each element in an {@link IHashSet} is also uniquely identified by this value. + * + * @reference http://www.cplusplus.com/reference/unordered_set/unordered_set + * @author Jeongho Nam + */ + interface IHashSet { + /** + *

Return iterator to beginning.

* - *

Because {@link Vector}s use an Array as their underlying storage, inserting elements in - * positions other than the {@link end end()} causes the container to relocate all the elements that were - * after position to their new positions. This is generally an inefficient operation compared to the - * one performed for the same operation by other kinds of sequence containers (such as {@link List}). + *

Returns an iterator pointing to the first element in the {@link IHashSet}.

* - * @param position Position in the {@link Vector} where the new elements are inserted. - * {@link iterator} is a member type, defined as a - * {@link VectorIterator random access iterator} type that points to elements. - * @param begin Input interator of the initial position in a sequence. - * @param end Input interator of the final position in a sequence. + *

Notice that an {@link IHashSet} object makes no guarantees on which specific element is considered its + * first element. But, in any case, the range that goes from its begin to its end covers all the elements in the + * container, until invalidated.

* - * @return An iterator that points to the first of the newly inserted elements. + * @return An iterator to the first element in the container. */ - insert>(position: VectorIterator, begin: InputIterator, end: InputIterator): VectorIterator; + begin(): SetIterator; /** - *

Insert an element.

- * - *

The {@link Vector} is extended by inserting new element before the element at the specified - * position, effectively increasing the container size by one.

+ *

Return iterator to beginning.

* - *

This causes an automatic reallocation of the allocated storage space if -and only if- the new - * {@link size} surpasses the current {@link capacity}.

+ *

Returns an iterator pointing to the first element in one of buckets in the {@link IHashSet}.

* - *

Because {@link Vector}s use an Array as their underlying storage, inserting element in - * positions other than the {@link end end()} causes the container to relocate all the elements that were - * after position to its new position. This is generally an inefficient operation compared to the one - * performed for the same operation by other kinds of sequence containers (such as {@link List}).

+ *

Notice that an {@link IHashSet} object makes no guarantees on which specific element is considered its + * first element. But, in any case, the range that goes from its begin to its end covers all the elements in the + * bucket, until invalidated.

* - * @param position Position in the {@link Vector} where the new element is inserted. - * {@link iterator} is a member type, defined as a - * {@link VectorIterator random access iterator} type that points to elements. - * @param val Value to be copied to the inserted element. + * @param index Bucket number. This shall be lower than {@link bucket_count}. * - * @return An iterator that points to the newly inserted element. + * @return An iterator to the first element in the bucket. */ - insert(position: VectorReverseIterator, val: T): VectorReverseIterator; + begin(index: number): SetIterator; /** - *

Insert elements by repeated filling.

- * - *

The {@link Vector} is extended by inserting new elements before the element at the specified - * position, effectively increasing the container size by the number of elements inserted.

+ *

Return iterator to end.

* - *

This causes an automatic reallocation of the allocated storage space if -and only if- the new - * {@link size} surpasses the current {@link capacity}.

+ *

Returns an iterator pointing to the past-the-end element in the {@link HaspMap} container.

* - *

Because {@link Vector}s use an Array as their underlying storage, inserting elements in - * positions other than the {@link end end()} causes the container to relocate all the elements that were - * after position to their new positions. This is generally an inefficient operation compared to the - * one performed for the same operation by other kinds of sequence containers (such as {@link List}). + *

The iterator returned by end does not point to any element, but to the position that follows the last + * element in the {@link HaspMap} container (its past-the-end position). Thus, the value returned shall + * not be dereferenced - it is generally used to describe the open-end of a range, such as + * [begin, end).

* - * @param position Position in the {@link Vector} where the new elements are inserted. - * {@link iterator} is a member type, defined as a - * {@link VectorIterator random access iterator} type that points to elements. - * @param n Number of elements to insert. Each element is initialized to a copy of val. - * @param val Value to be copied (or moved) to the inserted elements. + *

Notice that an {@link IHashSet} object makes no guarantees on which order its elements follow. But, in any + * case, the range that goes from its begin to its end covers all the elements in the container (or the bucket), + * until invalidated.

* - * @return An iterator that points to the first of the newly inserted elements. + * @return An iterator to the element past the end of the container. */ - insert(position: VectorReverseIterator, n: number, val: T): VectorReverseIterator; + end(): SetIterator; /** - *

Insert elements by range iterators.

+ *

Return iterator to end.

* - *

The {@link Vector} is extended by inserting new elements before the element at the specified - * position, effectively increasing the container size by the number of elements inserted by range - * iterators.

+ *

Returns an iterator pointing to the past-the-end element in the {@link HaspMap} container.

* - *

This causes an automatic reallocation of the allocated storage space if -and only if- the new - * {@link size} surpasses the current {@link capacity}.

+ *

The iterator returned by end does not point to any element, but to the position that follows the last + * element in the {@link HaspMap} container (its past-the-end position). Thus, the value returned shall + * not be dereferenced - it is generally used to describe the open-end of a range, such as + * [begin, end).

* - *

Because {@link Vector}s use an Array as their underlying storage, inserting elements in - * positions other than the {@link end end()} causes the container to relocate all the elements that were - * after position to their new positions. This is generally an inefficient operation compared to the - * one performed for the same operation by other kinds of sequence containers (such as {@link List}). + *

Notice that an {@link IHashSet} object makes no guarantees on which order its elements follow. But, in any + * case, the range that goes from its begin to its end covers all the elements in the container (or the bucket), + * until invalidated.

* - * @param position Position in the {@link Vector} where the new elements are inserted. - * {@link iterator} is a member type, defined as a - * {@link VectorIterator random access iterator} type that points to elements. - * @param begin Input interator of the initial position in a sequence. - * @param end Input interator of the final position in a sequence. + * @param index Bucket number. This shall be lower than {@link bucket_count}. * - * @return An iterator that points to the first of the newly inserted elements. - */ - insert>(position: VectorReverseIterator, begin: InputIterator, end: InputIterator): VectorReverseIterator; - /** - * @hidden - */ - private insert_by_val(position, val); - /** - * @hidden - */ - protected _Insert_by_repeating_val(position: VectorIterator, n: number, val: T): VectorIterator; - /** - * @hidden + * @return An iterator to the element past the end of the bucket. */ - protected _Insert_by_range>(position: VectorIterator, first: InputIterator, last: InputIterator): VectorIterator; + end(index: number): SetIterator; + rbegin(): SetReverseIterator; + rbegin(index: number): SetReverseIterator; + rend(): SetReverseIterator; + rend(index: number): SetReverseIterator; /** - * @inheritdoc + *

Return number of buckets.

+ * + *

Returns the number of buckets in the {@link IHashSet} container.

+ * + *

A bucket is a slot in the container's internal hash table to which elements are assigned based on the + * hash value of their key.

+ * + *

The number of buckets influences directly the {@link load_factor load factor} of the container's hash + * table (and thus the probability of collision). The container automatically increases the number of buckets to + * keep the load factor below a specific threshold (its {@link max_load_factor}), causing a {@link rehash} each + * time the number of buckets needs to be increased.

+ * + * @return The current amount of buckets. */ - pop_back(): void; + bucket_count(): number; /** - *

Erase element.

+ *

Return bucket size.

* - *

Removes from the {@link Vector} either a single element; position.

+ *

Returns the number of elements in bucket n.

* - *

This effectively reduces the container size by the number of element removed.

+ *

A bucket is a slot in the container's internal hash table to which elements are assigned based on the hash + * value of their key.

* - *

Because {@link Vector}s use an Array as their underlying storage, erasing an element in - * position other than the {@link end end()} causes the container to relocate all the elements after the - * segment erased to their new positions. This is generally an inefficient operation compared to the one - * performed for the same operation by other kinds of sequence containers (such as {@link List}).

+ *

The number of elements in a bucket influences the time it takes to access a particular element in the + * bucket. The container automatically increases the number of buckets to keep the {@link load_cator load factor} + * (which is the average bucket size) below its {@link max_load_factor}.

* - * @param position Iterator pointing to a single element to be removed from the {@link Vector}. + * @param n Bucket number. This shall be lower than {@link bucket_count}. * - * @return An iterator pointing to the new location of the element that followed the last element erased by - * the function call. This is the {@link end end()} if the operation erased the last element in the - * sequence. + * @return The number of elements in bucket n. */ - erase(position: VectorIterator): VectorIterator; + bucket_size(n: number): number; /** - *

Erase element.

+ *

Get maximum load factor.

* - *

Removes from the Vector either a single element; position.

+ *

Returns the current maximum load factor for the {@link HashMultiMap} container.

* - *

This effectively reduces the container size by the number of elements removed.

+ *

The load factor is the ratio between the number of elements in the container (its {@link size}) and the + * number of buckets ({@link bucket_count}).

* - *

Because {@link Vector}s use an Array as their underlying storage, erasing elements in - * position other than the {@link end end()} causes the container to relocate all the elements after the - * segment erased to their new positions. This is generally an inefficient operation compared to the one - * performed for the same operation by other kinds of sequence containers (such as {@link List}).

+ *

By default, {@link HashMultiMap} containers have a {@link max_load_factor} of 1.0.

* - * @param begin An iterator specifying a range of beginning to erase. - * @param end An iterator specifying a range of end to erase. + *

The load factor influences the probability of collision in the hash table (i.e., the probability of two + * elements being located in the same bucket). The container uses the value of max_load_factor as the threshold + * that forces an increase in the number of buckets (and thus causing a {@link rehash}).

* - * @return An iterator pointing to the new location of the element that followed the last element erased by - * the function call. This is the {@link rend rend()} if the operation erased the last element in the - * sequence. + *

Note though, that implementations may impose an upper limit on the number of buckets (see + * {@link max_bucket_count}), which may force the container to ignore the {@link max_load_factor}.

+ * + * @return The current load factor. */ - erase(first: VectorIterator, last: VectorIterator): VectorIterator; + max_load_factor(): number; /** - *

Erase element.

+ *

Set maximum load factor.

* - *

Removes from the {@link Vector} either a single element; position.

+ *

Sets z as the cnew maximum load factor for the {@link HashMultiMap} container.

* - *

This effectively reduces the container size by the number of element removed.

+ *

The load factor is the ratio between the number of elements in the container (its {@link size}) and the + * number of buckets ({@link bucket_count}).

* - *

Because {@link Vector}s use an Array as their underlying storage, erasing an element in - * position other than the {@link end end()} causes the container to relocate all the elements after the - * segment erased to their new positions. This is generally an inefficient operation compared to the one - * performed for the same operation by other kinds of sequence containers (such as {@link List}).

+ *

By default, {@link HashMultiMap} containers have a {@link max_load_factor} of 1.0.

* - * @param position Iterator pointing to a single element to be removed from the {@link Vector}. + *

The load factor influences the probability of collision in the hash table (i.e., the probability of two + * elements being located in the same bucket). The container uses the value of max_load_factor as the threshold + * that forces an increase in the number of buckets (and thus causing a {@link rehash}).

* - * @return An iterator pointing to the new location of the element that followed the last element erased by - * the function call. This is the {@link rend rend()} if the operation erased the last element in the - * sequence. + *

Note though, that implementations may impose an upper limit on the number of buckets (see + * {@link max_bucket_count}), which may force the container to ignore the {@link max_load_factor}.

+ * + * @param z The new maximum load factor. */ - erase(position: VectorReverseIterator): VectorReverseIterator; + max_load_factor(z: number): void; /** - *

Erase element.

- * - *

Removes from the Vector either a single element; position.

+ *

Locate element's bucket.

* - *

This effectively reduces the container size by the number of elements removed.

+ *

Returns the bucket number where the element with key is located.

* - *

Because {@link Vector}s use an Array as their underlying storage, erasing elements in - * position other than the {@link end end()} causes the container to relocate all the elements after the - * segment erased to their new positions. This is generally an inefficient operation compared to the one - * performed for the same operation by other kinds of sequence containers (such as {@link List}).

+ *

A bucket is a slot in the container's internal hash table to which elements are assigned based on the + * hash value of their key. Buckets are numbered from 0 to ({@link bucket_count} - 1).

* - * @param begin An iterator specifying a range of beginning to erase. - * @param end An iterator specifying a range of end to erase. + *

Individual elements in a bucket can be accessed by means of the range iterators returned by + * {@link begin} and {@link end}.

* - * @return An iterator pointing to the new location of the element that followed the last element erased by - * the function call. This is the {@link end end()} if the operation erased the last element in the - * sequence. - */ - erase(first: VectorReverseIterator, last: VectorReverseIterator): VectorReverseIterator; - /** - * @hidden + * @param key Key whose bucket is to be located. */ - protected _Erase_by_range(first: VectorIterator, last: VectorIterator): VectorIterator; + bucket(key: T): number; /** - *

Swap content.

+ *

Request a capacity change.

* - *

Exchanges the content of the container by the content of obj, which is another - * {@link Vector container} object with same type of elements. Sizes and container type may differ.

+ *

Sets the number of buckets in the container ({@link bucket_count}) to the most appropriate to contain at + * least n elements.

* - *

After the call to this member function, the elements in this container are those which were in obj - * before the call, and the elements of obj are those which were in this. All iterators, references and - * pointers remain valid for the swapped objects.

+ *

If n is greater than the current {@link bucket_count} multiplied by the {@link max_load_factor}, + * the container's {@link bucket_count} is increased and a {@link rehash} is forced.

* - *

Notice that a non-member function exists with the same name, {@link std.swap swap}, overloading that - * algorithm with an optimization that behaves like this member function.

+ *

If n is lower than that, the function may have no effect.

* - * @param obj Another {@link Vector container} of the same type of elements (i.e., instantiated - * with the same template parameter, T) whose content is swapped with that of this - * {@link container Vector}. - */ - obj(obj: Vector): void; - /** - * @inheritdoc - */ - swap(obj: base.IContainer): void; - } -} -declare namespace std { - /** - *

An iterator of Vector.

- * - *

- * - *

- * - * @param Type of the elements. - * - * @author Jeongho Nam - */ - class VectorIterator extends Iterator implements base.IArrayIterator { - /** - * Sequence number of iterator in the source {@link Vector}. + * @param n The number of elements requested as minimum capacity. */ - private index_; + reserve(n: number): void; /** - *

Construct from the source {@link Vector container}.

+ *

Set number of buckets.

* - *

Note

- *

Do not create the iterator directly, by yourself.

- *

Use {@link Vector.begin begin()}, {@link Vector.end end()} in {@link Vector container} instead.

+ *

Sets the number of buckets in the container to n or more.

* - * @param source The source {@link Vector container} to reference. - * @param index Sequence number of the element in the source {@link Vector}. - */ - constructor(source: Vector, index: number); - /** - * @hidden - */ - private readonly vector; - /** - * @inheritdoc - */ - /** - * Set value of the iterator is pointing to. + *

If n is greater than the current number of buckets in the container ({@link bucket_count}), a + * {@link HashBuckets.rehash rehash} is forced. The new {@link bucket_count bucket count} can either be equal or + * greater than n.

* - * @param val Value to set. - */ - value: T; - /** - * Get index. - */ - readonly index: number; - /** - * @inheritdoc - */ - prev(): VectorIterator; - /** - * @inheritdoc - */ - next(): VectorIterator; - /** - * @inheritdoc - */ - advance(n: number): VectorIterator; - /** - *

Whether an iterator is equal with the iterator.

+ *

If n is lower than the current number of buckets in the container ({@link bucket_count}), the + * function may have no effect on the {@link bucket_count bucket count} and may not force a + * {@link HashBuckets.rehash rehash}.

* - *

Compare two iterators and returns whether they are equal or not.

+ *

A {@link HashBuckets.rehash rehash} is the reconstruction of the hash table: All the elements in the + * container are rearranged according to their hash value into the new set of buckets. This may alter the order + * of iteration of elements within the container.

* - *

Note

- *

Iterator's equal_to() only compare souce container and index number.

+ *

{@link HashBuckets.rehash Rehashes} are automatically performed by the container whenever its + * {@link load_factor load factor} is going to surpass its {@link max_load_factor} in an operation.

* - *

Although elements in a pair, key and value are equal_to, if the source map or - * index number is different, then the {@link equal_to equal_to()} will return false. If you want to - * compare the elements of a pair, compare them directly by yourself.

+ *

Notice that this function expects the number of buckets as argument. A similar function exists, + * {@link reserve}, that expects the number of elements in the container as argument.

* - * @param obj An iterator to compare - * @return Indicates whether equal or not. - */ - equal_to(obj: VectorIterator): boolean; - /** - * @inheritdoc + * @param n The minimum number of buckets for the container hash table. */ - swap(obj: VectorIterator): void; + rehash(n: number): void; } } -declare namespace std { +declare namespace std.base { /** - *

A reverse-iterator of Vector.

+ *

Hash buckets storing {@link SetIterator SetIterators}.

* - *

- * + *

+ * *

* - * @param Type of the elements. - * * @author Jeongho Nam */ - class VectorReverseIterator extends ReverseIterator, VectorReverseIterator> implements base.IArrayIterator { - /** - * Construct from base iterator. - * - * @param base A reference of the base iterator, which iterates in the opposite direction. - */ - constructor(base: VectorIterator); - /** - * @hidden - */ - protected create_neighbor(base: VectorIterator): VectorReverseIterator; - /** - * @inheritdoc - */ - /** - * Set value of the iterator is pointing to. - * - * @param val Value to set. - */ - value: T; - /** - * Get index. - */ - readonly index: number; + class SetHashBuckets extends HashBuckets> { + private set; + constructor(set: SetContainer); + find(val: T): SetIterator; } } -declare namespace std { +declare namespace std.base { /** - *

FIFO queue.

+ *

Array

+ * + *

{@link IArray} is an interface for sequence containers representing arrays that can change in + * {@link size}. However, compared to arrays, {@link IArray} objectss consume more memory in exchange for + * the ability to manage storage and grow dynamically in an efficient way.

* - *

{@link Queue}s are a type of container adaptor, specifically designed to operate in a FIFO context - * (first-in first-out), where elements are inserted into one end of the container and extracted from the other. - *

+ *

Both {@link Vector Vectors} and {@link Deque Deques} who implemented {@link IArray} provide a very + * similar interface and can be used for similar purposes, but internally both work in quite different ways: + * While {@link Vector Vectors} use a single array that needs to be occasionally reallocated for growth, the + * elements of a {@link Deque} can be scattered in different chunks of storage, with the container keeping the + * necessary information internally to provide direct access to any of its elements in constant time and with a + * uniform sequential interface (through iterators). Therefore, {@link Deque Deques} are a little more complex + * internally than {@link Vector Vectors}, but this allows them to grow more efficiently under certain + * circumstances, especially with very long sequences, where reallocations become more expensive.

* - *

{@link Queue}s are implemented as containers adaptors, which are classes that use an encapsulated object of - * a specific container class as its underlying container, providing a specific set of member functions to access - * its elements. Elements are pushed into the {@link IDeque.back back()} of the specific container and popped from - * its {@link IDeque.front front()}.

+ *

Both {@link Vector Vectors} and {@link Deque Deques} provide a very similar interface and can be used for + * similar purposes, but internally both work in quite different ways: While {@link Vector Vectors} use a single + * array that needs to be occasionally reallocated for growth, the elements of a {@link Deque} can be scattered + * in different chunks of storage, with the container keeping the necessary information internally to provide + * direct access to any of its elements in constant time and with a uniform sequential interface (through + * iterators). Therefore, {@link Deque Deques} are a little more complex internally than {@link Vector Vectors}, + * but this allows them to grow more efficiently under certain circumstances, especially with very long + * sequences, where reallocations become more expensive.

* - *

{@link container_ The underlying container} may be one of the standard container class template or some - * other specifically designed container class. This underlying container shall support at least the following - * operations:

+ *

For operations that involve frequent insertion or removals of elements at positions other than the + * beginning or the end, {@link IArray} objects perform worse and have less consistent iterators and references + * than {@link List Lists}

. * - *
    - *
  • empty
  • - *
  • size
  • - *
  • front
  • - *
  • back
  • - *
  • push_back
  • - *
  • pop_front
  • - *
+ *

+ * + *

* - *

The standard container classes {@link Deque} and {@link List} fulfill these requirements. - * By default, if no container class is specified for a particular {@link Queue} class instantiation, the standard - * container {@link List} is used.

+ *

Container properties

+ *
+ *
Sequence
+ *
+ * Elements in sequence containers are ordered in a strict linear sequence. Individual elements are + * accessed by their position in this sequence. + *
* - *

- * - *

+ *
Dynamic array
+ *
+ * Allows direct access to any element in the sequence, even through pointer arithmetics, and provides + * relatively fast addition/removal of elements at the end of the sequence. + *
+ *
* - * @param Type of elements. + * @param Type of the elements. * - * @reference http://www.cplusplus.com/reference/queue/queue * @author Jeongho Nam */ - class Queue { - /** - * The underlying object for implementing the FIFO - */ - private container_; - /** - * Default Constructor. - */ - constructor(); - /** - * Copy Constructor. - */ - constructor(container: Queue); - /** - *

Return size.

- *

Returns the number of elements in the {@link Queue}.

- * - *

This member function effectively calls member {@link IDeque.size size()} of the - * {@link container_ underlying container} object.

- * - * @return The number of elements in the {@link container_ underlying container}. - */ - size(): number; + interface IArrayContainer extends ILinearContainer { /** - *

Test whether container is empty.

- *

returns whether the {@link Queue} is empty: i.e. whether its size is zero.

+ *

Request a change in capacity.

* - *

This member function efeectively calls member {@link IDeque.empty empty()} of the - * {@link container_ underlying container} object.

+ *

Requests that the {@link IArray container} {@link capacity} be at least enough to contain + * n elements.

* - * @return true if the {@link container_ underlying container}'s size is 0, - * false otherwise.

- */ - empty(): boolean; - /** - *

Access next element.

- *

Returns a value of the next element in the {@link Queue}.

+ *

If n is greater than the current {@link IArray container} {@link capacity}, the + * function causes the {@link IArray container} to reallocate its storage increasing its + * {@link capacity} to n (or greater).

* - *

The next element is the "oldest" element in the {@link Queue} and the same element that is popped out - * from the queue when {@link pop Queue.pop()} is called.

+ *

In all other cases, the function call does not cause a reallocation and the + * {@link IArray container} {@link capacity} is not affected.

* - *

This member function effectively calls member {@link IDeque.front front()} of the - * {@link container_ underlying container} object.

+ *

This function has no effect on the {@link IArray container} {@link size} and cannot alter + * its elements.

* - * @return A value of the next element in the {@link Queue}. + * @param n Minimum {@link capacity} for the {@link IArray container}. + * Note that the resulting {@link capacity} may be equal or greater than n. */ - front(): T; + reserve(n: number): void; /** - *

Access last element.

- * - *

Returns a vaue of the last element in the queue. This is the "newest" element in the queue (i.e. the - * last element pushed into the queue).

+ *

Return size of allocated storage capacity.

* - *

This member function effectively calls the member function {@link IDeque.back back()} of the - * {@link container_ underlying container} object.

+ *

Returns the size of the storage space currently allocated for the {@link IArray container}, + * expressed in terms of elements.

* - * @return A value of the last element in the {@link Queue}. - */ - back(): T; - /** - *

Insert element.

+ *

This {@link capacity} is not necessarily equal to the {@link IArray container} {@link size}. + * It can be equal or greater, with the extra space allowing to accommodate for growth without the + * need to reallocate on each insertion.

* - *

Inserts a new element at the end of the {@link Queue}, after its current last element. - * The content of this new element is initialized to val.

+ *

Notice that this {@link capacity} does not suppose a limit on the {@link size} of the + * {@link IArray container}. When this {@link capacity} is exhausted and more is needed, it is + * automatically expanded by the {@link IArray container} (reallocating it storage space). + * The theoretical limit on the {@link size} of a {@link IArray container} is given by member + * {@link max_size}.

* - *

This member function effectively calls the member function {@link IDeque.push_back push_back()} of the - * {@link container_ underlying container} object.

+ *

The {@link capacity} of a {@link IArray container} can be explicitly altered by calling member + * {@link IArray.reserve}.

* - * @param val Value to which the inserted element is initialized. + * @return The size of the currently allocated storage capacity in the {@link IArray container}, + * measured in terms of the number elements it can hold. */ - push(val: T): void; + capacity(): number; /** - *

Remove next element.

+ *

Access element.

+ *

Returns a value to the element at position index in the {@link IArray container}.

* - *

Removes the next element in the {@link Queue}, effectively reducing its size by one.

+ *

The function automatically checks whether index is within the bounds of valid elements + * in the {@link IArray container}, throwing an {@link OutOfRange} exception if it is not (i.e., + * if index is greater or equal than its {@link size}).

* - *

The element removed is the "oldest" element in the {@link Queue} whose value can be retrieved by calling - * member {@link front Queue.front()}

. + * @param index Position of an element in the + * If this is greater than or equal to the {@link IArray container} {@link size}, an + * exception of type {@link OutOfRange} is thrown. Notice that the first + * element has a position of 0 (not 1). * - *

This member function effectively calls the member function {@link IDeque.pop_front pop_front()} of the - * {@link container_ underlying container} object.

+ * @return The element at the specified position in the */ - pop(): void; + at(index: number): T; /** - *

Swap contents.

+ *

Modify element.

+ *

Replaces an element at the specified position (index) in this {@link IArray container} + * with the specified element (val).

* - *

Exchanges the contents of the container adaptor (this) by those of obj.

+ *

The function automatically checks whether index is within the bounds of valid elements + * in the {@link IArray container}, throwing an {@link OutOfRange} exception if it is not (i.e., if + * index is greater or equal than its {@link size}).

* - *

This member function calls the non-member function {@link IContainer.swap swap} (unqualified) to swap - * the {@link container_ underlying containers}.

+ * @.param index A specified position of the value to replace. + * @param val A value to be stored at the specified position. * - * @param obj Another {@link Queue} container adaptor of the same type (i.e., instantiated with the same - * template parameter, T). Sizes may differ.

+ * @return The previous element had stored at the specified position. */ - swap(obj: Queue): void; + set(index: number, val: T): void; } } -declare namespace std { +declare namespace std.base { /** - *

LIFO stack.

+ *

Random-access iterator.

* - *

{@link Stack}s are a type of container adaptor, specifically designed to operate in a LIFO context - * (last-in first-out), where elements are inserted and extracted only from one end of the

+ *

{@link IArrayIterator Random-access iterators} are iterators that can be used to access elements at an + * arbitrary offset position relative to the element they point to, offering the same functionality as pointers. + *

* - *

{@link Stack}s are implemented as containers adaptors, which are classes that use an encapsulated object of - * a specific container class as its underlying container, providing a specific set of member functions to - * access its elements. Elements are pushed/popped from the {@link ILinearContainer.back back()} of the - * {@link ILinearContainer specific container}, which is known as the top of the {@link Stack}.

+ *

{@link IArrayIterator Random-access iterators} are the most complete iterators in terms of functionality. + * All pointer types are also valid {@link IArrayIterator random-access iterators}.

* - *

{@link container_ The underlying container} may be any of the standard container class templates or some - * other specifically designed container class. The container shall support the following operations:

+ *

There is not a single type of {@link IArrayIterator random-access iterator}: Each container may define its + * own specific iterator type able to iterate through it and access its elements.

* - *
    - *
  • empty
  • - *
  • size
  • - *
  • front
  • - *
  • back
  • - *
  • push_back
  • - *
  • pop_back
  • - *
+ *

+ * + *

* - *

The standard container classes {@link Vector}, {@link Deque} and {@link List} fulfill these requirements. - * By default, if no container class is specified for a particular {@link Stack} class instantiation, the standard - * container {@link List} is used.

+ * @reference http://www.cplusplus.com/reference/iterator/RandomAccessIterator + * @author Jeongho Nam + */ + interface IArrayIterator extends Iterator { + /** + * Get index, sequence number of the iterator in the source {@link IArray array}. + * + * @return Sequence number of the iterator in the source {@link IArray array}. + */ + index: number; + /** + * @inheritdoc + */ + prev(): IArrayIterator; + /** + * @inheritdoc + */ + next(): IArrayIterator; + } +} +declare namespace std.base { + /** + *

An interface of containers.

* - *

- * - *

+ *

{@link IContainer} is an interface designed for sequence containers. Sequence containers of STL + * (Standard Template Library) are based on the {@link IContainer}.

+ * + *

+ * + *

+ * + *

Container properties

+ *
+ *
Sequence
+ *
Elements in sequence containers are ordered in a strict linear sequence. Individual elements are + * accessed by their position in this sequence.
+ * + *
Doubly-linked list
+ *
Each element keeps information on how to locate the next and the previous elements, allowing + * constant time insert and erase operations before or after a specific element (even of entire ranges), + * but no direct random access.
+ *
* * @param Type of elements. * - * @reference http://www.cplusplus.com/reference/stack/stack * @author Jeongho Nam */ - class Stack { - /** - * The underlying object for implementing the LIFO - */ - private container_; + interface IContainer { /** - * Default Constructor. + *

Assign new content to content.

+ * + *

Assigns new contents to the container, replacing its current contents, and modifying its + * {@link size} accordingly.

+ * + * @param begin Input interator of the initial position in a sequence. + * @param end Input interator of the final position in a sequence. */ - constructor(); + assign>(begin: InputIterator, end: InputIterator): void; /** - * Copy Constructor. + *

Clear content.

+ * + *

Removes all elements from the Container, leaving the container with a size of 0.

*/ - constructor(stack: Stack); + clear(): void; /** - *

Return size.

+ *

Return iterator to beginning.

* - *

Returns the number of elements in the {@link Stack}.

+ *

Returns an iterator referring the first element in the

* - *

This member function effectively calls member {@link ILinearContainer.size size()} of the - * {@link container_ underlying container} object.

+ *

Note

+ *

If the container is {@link empty}, the returned iterator is same with {@link end end()}.

* - * @return The number of elements in the {@link container_ underlying container}. + * @return An iterator to the first element in the The iterator containes the first element's value. */ - size(): number; + begin(): Iterator; /** - *

Test whether container is empty.

+ *

Return iterator to end.

+ *

Returns an iterator referring to the past-the-end element in the

* - *

returns whether the {@link Stack} is empty: i.e. whether its size is zero.

+ *

The past-the-end element is the theoretical element that would follow the last element in the + * It does not point to any element, and thus shall not be dereferenced.

* - *

This member function effectively calls member {@link ILinearContainer.empty empty()} of the - * {@link container_ underlying container} object.

+ *

Because the ranges used by functions of the Container do not include the element reference by their + * closing iterator, this function is often used in combination with {@link IContainer}.{@link begin} to + * specify a range including all the elements in the container.

* - * @return true if the underlying container's size is 0, - * false otherwise.

+ *

Note

+ *

Returned iterator from {@link IContainer}.{@link end} does not refer any element. Trying to accessing + * element by the iterator will cause throwing exception ({@link OutOfRange}).

+ * + *

If the container is {@link empty}, this function returns the same as {@link Container}.{@link begin}. + *

+ * + * @return An iterator to the end element in the */ - empty(): boolean; + end(): Iterator; /** - *

Access next element.

+ *

Return {@link ReverseIterator reverse iterator} to reverse beginning.

* - *

Returns a value of the top element in the {@link Stack}

. + *

Returns a {@link ReverseIterator reverse iterator} pointing to the last element in the container (i.e., + * its reverse beginning).

* - *

Since {@link Stack}s are last-in first-out containers, the top element is the last element inserted into - * the {@link Stack}.

+ *

{@link ReverseIterator reverse iterators} iterate backwards: increasing them moves them towards the + * beginning of the

* - *

This member function effectively calls member {@link ILinearContainer.back back()} of the - * {@link container_ underlying container} object.

+ *

{@link rbegin} points to the element right before the one that would be pointed to by member {@link end}. + *

* - * @return A value of the top element in the {@link Stack}. + * @return A {@link ReverseIterator reverse iterator} to the reverse beginning of the sequence */ - top(): T; + rbegin(): base.IReverseIterator; /** - *

Insert element.

+ *

Return {@link ReverseIterator reverse iterator} to reverse end.

* - *

Inserts a new element at the top of the {@link Stack}, above its current top element.

+ *

Returns a {@link ReverseIterator reverse iterator} pointing to the theoretical element preceding the + * first element in the container (which is considered its reverse end).

* - *

This member function effectively calls the member function - * {@link ILinearContainer.push_back push_back()} of the {@link container_ underlying container} object.

+ *

The range between {@link IContainer}.{@link rbegin} and {@link IContainer}.{@link rend} contains all + * the elements of the container (in reverse order). * - * @param val Value to which the inserted element is initialized. + * @return A {@link ReverseIterator reverse iterator} to the reverse end of the sequence */ - push(val: T): void; + rend(): base.IReverseIterator; /** - *

Remove top element.

+ * Return the number of elements in the Container. * - *

Removes the element on top of the {@link Stack}, effectively reducing its size by one.

+ * @return The number of elements in the + */ + size(): number; + /** + *

Test whether the container is empty.

+ *

Returns whether the container is empty (i.e. whether its size is 0).

* - *

The element removed is the latest element inserted into the {@link Stack}, whose value can be retrieved - * by calling member {@link top Stack.top()}

. + *

This function does not modify the container in any way. To clear the content of the container, + * see {@link clear clear()}.

* - *

This member function effectively calls the member function {@link ILinearContainer.pop_back pop_back()} - * of the {@link container_ underlying container} object.

+ * @return true if the container size is 0, false otherwise. */ - pop(): void; + empty(): boolean; /** - *

Swap contents.

+ *

Insert elements.

* - *

Exchanges the contents of the container adaptor (this) by those of obj.

+ *

Appends new elements to the container, and returns the new size of the

* - *

This member function calls the non-member function {@link IContainer.swap swap} (unqualified) to swap - * the {@link container_ underlying containers}.

+ * @param items New elements to insert. * - * @param obj Another {@link Stack} container adaptor of the same type (i.e., instantiated with the same - * template parameter, T). Sizes may differ.

- */ - swap(obj: Stack): void; - } -} -declare namespace std.TreeSet { - type iterator = std.SetIterator; - type reverse_iterator = std.SetReverseIterator; -} -declare namespace std { - /** - *

Tree-structured set, std::set of STL.

- * - *

{@link TreeSet}s are containers that store unique elements following a specific order.

- * - *

In a {@link TreeSet}, the value of an element also identifies it (the value is itself the - * key, of type T), and each value must be unique. The value of the elements in a - * {@link TreeSet} cannot be modified once in the container (the elements are always const), but they - * can be inserted or removed from the

- * - *

Internally, the elements in a {@link TreeSet} are always sorted following a specific strict weak - * ordering criterion indicated by its internal comparison method (of {@link less}).

- * - *

{@link TreeSet} containers are generally slower than {@link HashSet} containers to access - * individual elements by their key, but they allow the direct iteration on subsets based on their - * order.

- * - *

{@link TreeSet}s are typically implemented as binary search trees.

- * - *

- *

- * - *

Container properties

- *
- *
Associative
- *
- * Elements in associative containers are referenced by their key and not by their absolute - * position in the container. - *
- * - *
Ordered
- *
- * The elements in the container follow a strict order at all times. All inserted elements are - * given a position in this order. - *
- * - *
Set
- *
The value of an element is also the key used to identify it.
- * - *
Unique keys
- *
No two elements in the container can have equivalent keys.
- *
- * - * @param Type of the elements. - * Each element in an {@link TreeSet} is also uniquely identified by this value. - * - * @reference http://www.cplusplus.com/reference/set/set - * @author Jeongho Nam - */ - class TreeSet extends base.UniqueSet implements base.ITreeSet { - /** - * @hidden - */ - private tree_; - /** - * Default Constructor. + * @return New size of the Container. */ - constructor(); + push(...items: U[]): number; /** - * Construct from compare. + *

Insert an element.

* - * @param compare A binary predicate determines order of elements. - */ - constructor(compare: (x: T, y: T) => boolean); - /** - * Contruct from elements. + *

The container is extended by inserting a new element before the element at the specified + * position. This effectively increases the {@link IContainer.size container size} by the amount of + * elements inserted.

* - * @param array Elements to be contained. - */ - constructor(array: Array); - /** - * Contruct from elements with compare. + * @param position Position in the {@link IContainer} where the new element is inserted. + * {@link iterator} is a member type, defined as a {@link Iterator random access iterator} + * type that points to elements. + * @param val Value to be copied to the inserted element. * - * @param array Elements to be contained. - * @param compare A binary predicate determines order of elements. - */ - constructor(array: Array, compare: (x: T, y: T) => boolean); - /** - * Copy Constructor. + * @return An iterator that points to the newly inserted element. */ - constructor(container: TreeMultiSet); + insert(position: Iterator, val: T): Iterator; /** - * Copy Constructor with compare. + *

Erase an element.

* - * @param container A container to be copied. - * @param compare A binary predicate determines order of elements. - */ - constructor(container: TreeMultiSet, compare: (x: T, y: T) => boolean); - /** - * Range Constructor. + *

Removes from the container a single element.

* - * @param begin Input interator of the initial position in a sequence. - * @param end Input interator of the final position in a sequence. - */ - constructor(begin: Iterator, end: Iterator); - /** - * Construct from range and compare. + *

This effectively reduces the container size by the number of element removed.

* - * @param begin Input interator of the initial position in a sequence. - * @param end Input interator of the final position in a sequence. - * @param compare A binary predicate determines order of elements. + * @param position Iterator pointing to a single element to be removed from the Container. + * + * @return An iterator pointing to the element that followed the last element erased by the function + * call. This is the {@link end Container.end} if the operation erased the last element in the + * sequence. */ - constructor(begin: Iterator, end: Iterator, compare: (x: T, y: T) => boolean); + erase(position: Iterator): Iterator; /** - * @inheritdoc + *

Erase elements.

+ * + *

Removes from the container a range of elements.

+ * + *

This effectively reduces the container size by the number of elements removed.

+ * + * @param begin An iterator specifying a range of beginning to erase. + * @param end An iterator specifying a range of end to erase. + * + * @return An iterator pointing to the element that followed the last element erased by the function + * call. This is the {@link end Container.end} if the operation erased the last element in + * the sequence. */ - clear(): void; + erase(begin: Iterator, end: Iterator): Iterator; /** - * @inheritdoc + *

Swap content.

+ * + *

Exchanges the content of the container by the content of obj, which is another + * {@link IContainer container} object with same type of elements. Sizes and container type may differ.

+ * + *

After the call to this member function, the elements in this container are those which were in obj + * before the call, and the elements of obj are those which were in this. All iterators, references and + * pointers remain valid for the swapped objects.

+ * + *

Notice that a non-member function exists with the same name, {@link std.swap swap}, overloading that + * algorithm with an optimization that behaves like this member function.

+ * + * @param obj Another {@link IContainer container} of the same type of elements (i.e., instantiated + * with the same template parameter, T) whose content is swapped with that of this + * {@link container IContainer}. */ - find(val: T): SetIterator; + swap(obj: IContainer): void; + } + interface IReverseIterator extends ReverseIterator, IReverseIterator> { + } +} +declare namespace std.base { + /** + *

An interface for deque

+ * + *

+ * + *

+ * + * @author Jeongho Nam + */ + interface IDequeContainer extends ILinearContainer { /** - * @inheritdoc + *

Insert element at beginning.

+ * + *

Inserts a new element at the beginning of the {@link IDeque container}, right before its + * current first element. This effectively increases the {@link IDeque container} {@link size} by + * one.

+ * + * @param val Value to be inserted as an element. */ - key_comp(): (x: T, y: T) => boolean; + push_front(val: T): void; /** - * @inheritdoc + *

Delete first element.

+ * + *

Removes the first element in the {@link IDeque container}, effectively reducing its + * {@link size} by one.

*/ - value_comp(): (x: T, y: T) => boolean; + pop_front(): void; + } +} +declare namespace std.base { + /** + *

An interface for linear containers.

+ * + *

+ * + *

+ * + * @author Jeonngho Nam + */ + interface ILinearContainer extends IContainer { /** * @inheritdoc */ - lower_bound(val: T): SetIterator; + assign>(begin: InputIterator, end: InputIterator): void; /** - * @inheritdoc + *

Assign container content.

+ * + *

Assigns new contents to the {@link IList container}, replacing its current contents, + * and modifying its {@link size} accordingly.

+ * + * @param n New size for the + * @param val Value to fill the container with. Each of the n elements in the container will + * be initialized to a copy of this value. */ - upper_bound(val: T): SetIterator; + assign(n: number, val: T): void; /** - * @inheritdoc + *

Access first element.

+ *

Returns a value of the first element in the {@link IList container}.

+ * + *

Unlike member {@link end end()}, which returns an iterator just past this element, + * this function returns a direct value.

+ * + *

Calling this function on an {@link empty} {@link IList container} causes undefined behavior.

+ * + * @return A value of the first element of the {@link IList container}. */ - equal_range(val: T): Pair, SetIterator>; + front(): T; /** - * @hidden + *

Access last element.

+ *

Returns a value of the last element in the {@link IList container}.

+ * + *

Unlike member {@link end end()}, which returns an iterator just past this element, + * this function returns a direct value.

+ * + *

Calling this function on an {@link empty} {@link IList container} causes undefined behavior.

+ * + * @return A value of the last element of the {@link IList container}. */ - protected _Insert_by_val(val: T): any; - protected _Insert_by_hint(hint: SetIterator, val: T): SetIterator; + back(): T; /** - * @hidden + *

Add element at the end.

+ * + *

Adds a new element at the end of the {@link IList container}, after its current last element. + * This effectively increases the {@link IList container} {@link size} by one.

+ * + * @param val Value to be copied to the new element. */ - protected _Insert_by_range>(first: InputIterator, last: InputIterator): void; + push_back(val: T): void; /** - * @inheritdoc + *

Delete last element.

+ * + *

Removes the last element in the {@link IList container}, effectively reducing the + * {@link IList container} {@link size} by one.

*/ - protected _Handle_insert(first: SetIterator, last: SetIterator): void; + pop_back(): void; /** - * @inheritdoc + *

Insert an element.

+ * + *

The {@link IList conatiner} is extended by inserting new element before the element at the + * specified position, effectively increasing the {@link IList container} {@link size} by + * one.

+ * + * @param position Position in the {@link IList container} where the new elements are inserted. + * {@link iterator} is a member type, defined as a {@link iterator random access iterator} + * type that points to elements. + * @param val Value to be copied to the inserted element. + * + * @return An iterator that points to the newly inserted element. */ - protected _Handle_erase(first: SetIterator, last: SetIterator): void; + insert(position: Iterator, val: T): Iterator; /** - *

Swap content.

- * - *

Exchanges the content of the container by the content of obj, which is another - * {@link TreeSet set} of the same type. Sizes abd container type may differ.

+ *

Insert elements by range iterators.

* - *

After the call to this member function, the elements in this container are those which were - * in obj before the call, and the elements of obj are those which were in this. All - * iterators, references and pointers remain valid for the swapped objects.

+ *

The {@link IList container} is extended by inserting new elements before the element at the + * specified position, effectively increasing the {@link IList container} {@link size} by + * the number of repeating elements n.

* - *

Notice that a non-member function exists with the same name, {@link std.swap swap}, overloading that - * algorithm with an optimization that behaves like this member function.

+ * @param position Position in the {@link IList container} where the new elements are inserted. + * {@link iterator} is a member type, defined as a {@link iterator random access iterator} + * type that points to elements. + * @param n Number of elements to insert. Each element is initialized to a copy of val. + * @param val Value to be copied (or moved) to the inserted elements. * - * @param obj Another {@link TreeSet set container} of the same type of elements as this (i.e., - * with the same template parameters, Key and T) whose content is swapped - * with that of this {@link TreeSet container}. + * @return An iterator that points to the first of the newly inserted elements. */ - swap(obj: TreeSet): void; + insert(position: Iterator, n: number, val: T): Iterator; /** - * @inheritdoc + *

Insert elements by range iterators.

+ * + *

The {@link IList container} is extended by inserting new elements before the element at the + * specified position, effectively increasing the {@link IList container} {@link size} by + * the number of elements inserted by range iterators.

+ * + * @param position Position in the {@link IList container} where the new elements are inserted. + * {@link iterator} is a member type, defined as a {@link iterator random access iterator} + * type that points to elements. + * @param begin Input interator of the initial position in a sequence. + * @param end Input interator of the final position in a sequence. + * + * @return An iterator that points to the first of the newly inserted elements. */ - swap(obj: base.IContainer): void; + insert>(position: Iterator, begin: InputIterator, end: InputIterator): Iterator; } } -declare namespace std.TreeMap { - type iterator = std.MapIterator; - type reverse_iterator = std.MapReverseIterator; -} -declare namespace std { +declare namespace std.base { /** - *

Tree-structured map, std::map of STL.

- * - *

{@link TreeMap TreeMaps} are associative containers that store elements formed by a combination of a - * key value (Key) and a mapped value (T), following order.

- * - *

In a {@link TreeMap}, the key values are generally used to sort and uniquely identify the elements, - * while the mapped values store the content associated to this key. The types of key and - * mapped value may differ, and are grouped together in member type value_type, which is a {@link Pair} - * type combining both:

+ *

Red-black Tree.

* - *

typedef Pair value_type;

+ *

A red-black tree is a kind of self-balancing + * binary search tree. Each node of the binary tree has an extra bit, and that bit is often interpreted as the + * color (red or black) of the node. These color bits + * are used to ensure the tree remains approximately balanced during insertions and deletions.

* - *

Internally, the elements in a {@link TreeMap} are always sorted by its key following a - * strict weak ordering criterion indicated by its internal comparison method {@link less}. + *

Balance is preserved by painting each node of the tree with one of two colors (typically called + * 'red' and 'black') in a way that satisfies certain + * properties, which collectively constrain how unbalanced the tree can become in the worst case. When the tree + * is modified, the new tree is subsequently rearranged and repainted to restore the coloring properties. The + * properties are designed in such a way that this rearranging and recoloring can be performed efficiently.

* - *

{@link TreeMap} containers are generally slower than {@link HashMap HashMap} containers to access individual - * elements by their key, but they allow the direct iteration on subsets based on their order.

+ *

The balancing of the tree is not perfect but it is good enough to allow it to guarantee searching in + * O(log n) time, where n is the total number of elements in the tree. The insertion and deletion operations, + * along with the tree rearrangement and recoloring, are also performed in O(log n) time.

* - *

{@link TreeMap}s are typically implemented as binary search trees.

+ *

Tracking the color of each node requires only 1 bit of information per node because there are only two + * colors. The tree does not contain any other data specific to its being a + * red-black tree so its memory footprint is almost + * identical to a classic (uncolored) binary search tree. In many cases the additional bit of information can + * be stored at no additional memory cost.

* - *

- *

+ *

Properties

+ *

In addition to the requirements imposed on a binary search tree the following must be satisfied by a + * red-black tree:

* - *

Container properties

- *
- *
Associative
- *
Elements in associative containers are referenced by their key and not by their absolute - * position in the container.
+ *
    + *
  1. A node is either red or black.
  2. + *
  3. + * The root is black. This rule is sometimes omitted. Since the root can + * always be changed from red to black, but not + * necessarily vice versa, this rule has little effect on analysis. + *
  4. + *
  5. All leaves (NIL; null) are black.
  6. + *
  7. + * If a node is red, then both its children are + * black. + *
  8. + *
  9. + * Every path from a given node to any of its descendant NIL nodes contains the same number of + * black nodes. Some definitions: the number of + * black nodes from the root to a node is the node's + * black depth; the uniform number of black + * nodes in all paths from root to the leaves is called the black-height of + * the red-black tree. + *
  10. + *
* - *
Ordered
- *
The elements in the container follow a strict order at all times. All inserted elements are - * given a position in this order.
+ *

* - *
Map
- *
Each element associates a key to a mapped value: - * Keys are meant to identify the elements whose main content is the mapped value.
+ *

These constraints enforce a critical property of red-black trees: the path from the root to the farthest + * leaf is no more than twice as long as the path from the root to the nearest leaf. The result is that the tree + * is roughly height-balanced. Since operations such as inserting, deleting, and finding values require + * worst-case time proportional to the height of the tree, this theoretical upper bound on the height allows + * red-black trees to be efficient in the worst case, unlike ordinary binary search trees.

* - *
Unique keys
- *
No two elements in the container can have equivalent keys.
- *
+ *

To see why this is guaranteed, it suffices to consider the effect of properties 4 and 5 together. For a + * red-black tree T, let B be the number of black nodes in property 5. Let the + * shortest possible path from the root of T to any leaf consist of B black nodes. + * Longer possible paths may be constructed by inserting red nodes. However, property 4 + * makes it impossible to insert more than one consecutive red node. Therefore, + * ignoring any black NIL leaves, the longest possible path consists of 2*B nodes, + * alternating black and red (this is the worst case). + * Counting the black NIL leaves, the longest possible path consists of 2*B-1 + * nodes.

* - * @param Type of the keys. Each element in a map is uniquely identified by its key value. - * @param Type of the mapped value. Each element in a map stores some data as its mapped value. + *

The shortest possible path has all black nodes, and the longest possible + * path alternates between red and black nodes. Since all + * maximal paths have the same number of black nodes, by property 5, this shows + * that no path is more than twice as long as any other path.

* - * @reference http://www.cplusplus.com/reference/map/map - * @author Jeongho Nam + * @param Type of elements. + * + * @reference https://en.wikipedia.org/w/index.php?title=Red%E2%80%93black_tree + * @inventor Rudolf Bayer + * @author Migrated by Jeongho Nam */ - class TreeMap extends base.UniqueMap implements base.ITreeMap { + abstract class XTree { /** - * @hidden + * Root node. */ - private tree_; + protected root_: XTreeNode; /** * Default Constructor. */ constructor(); + clear(): void; /** - * Construct from compare. + * Find a node from its contained value. * - * @param compare A binary predicate determines order of elements. + * @param val Value to find. */ - constructor(compare: (x: Key, y: Key) => boolean); + find(val: T): XTreeNode; /** - * Contruct from elements. + * Fetch maximum (the rightes?) node from one. * - * @param array Elements to be contained. + * @param node A node to fetch its maximum node. + * @return The maximum node. */ - constructor(array: Array>); + protected fetch_maximum(node: XTreeNode): XTreeNode; + abstract is_less(left: T, right: T): boolean; + abstract is_equal_to(left: T, right: T): boolean; /** - * Contruct from elements. + *

Insert an element with a new node.

* - * @param array Elements to be contained. - * @param compare A binary predicate determines order of elements. + *

Insertion begins by adding the node as any binary search tree insertion does and by coloring it + * red. Whereas in the binary search tree, we always add a leaf, in the red-black + * tree, leaves contain no information, so instead we add a red interior node, with + * two black leaves, in place of an existing + * black leaf.

+ * + *

What happens next depends on the color of other nearby nodes. The term uncle node will be used to + * refer to the sibling of a node's parent, as in human family trees. Note that:

+ * + *
    + *
  • property 3 (all leaves are black) always holds.
  • + *
  • + * property 4 (both children of every red node are + * black) is threatened only by adding a red + * node, repainting a black node red, or a + * rotation. + *
  • + *
  • + * property 5 (all paths from any given node to its leaf nodes contain the same number of + * black nodes) is threatened only by adding a + * black node, repainting a red node + * black (or vice versa), or a rotation. + *
  • + *
+ * + *

Notes

+ *
    + *
  1. + * The label N will be used to denote the current node (colored + * red). In the diagrams N carries a blue contour. At the + * beginning, this is the new node being inserted, but the entire procedure may also be applied + * recursively to other nodes (see case 3). {@link XTreeNode.parent P} will denote + * N's parent node, {@link XTreeNode.grand_parent G} will denote N's + * grandparent, and {@link XTreeNode.uncle U} will denote N's uncle. In between + * some cases, the roles and labels of the nodes are exchanged, but in each case, every label continues + * to represent the same node it represented at the beginning of the case. + *
  2. + *
  3. + * If a node in the right (target) half of a diagram carries a blue contour it will become the current + * node in the next iteration and there the other nodes will be newly assigned relative to it. Any + * color shown in the diagram is either assumed in its case or implied by those assumptions. + *
  4. + *
  5. + * A numbered triangle represents a subtree of unspecified depth. A black + * circle atop a triangle means that black-height of subtree is greater + * by one compared to subtree without this circle.
  6. + *
+ * + *

There are several cases of red-black tree insertion to handle:

+ * + *
    + *
  • N is the root node, i.e., first node of red-black tree.
  • + *
  • + * N's parent ({@link XTreeNode.parent P}) is black. + *
  • + *
  • + * N's parent ({@link XTreeNode.parent P}) and uncle + * ({@link XTreeNode.uncle U}) are red. + *
  • + *
  • + * N is added to right of left child of grandparent, or N is added to left + * of right child of grandparent ({@link XTreeNode.parent P} is red and + * {@link XTreeNode.uncle U} is black). + *
  • + *
  • + * N is added to left of left child of grandparent, or N is added to right + * of right child of grandparent ({@link XTreeNode.parent P} is red and + * {@link XTreeNode.uncle U} is black). + *
  • + *
+ * + *

Note

+ *

Note that inserting is actually in-place, since all the calls above use tail recursion.

+ * + *

In the algorithm above, all cases are chained in order, except in insert case 3 where it can recurse + * to case 1 back to the grandparent node: this is the only case where an iterative implementation will + * effectively loop. Because the problem of repair is escalated to the next higher level but one, it takes + * maximally h⁄2 iterations to repair the tree (where h is the height of the tree). Because the probability + * for escalation decreases exponentially with each iteration the average insertion cost is constant.

+ * + * @param val An element to insert. */ - constructor(array: Array>, compare: (x: Key, y: Key) => boolean); + insert(val: T): void; /** - * Contruct from tuples. + *

N is the root node, i.e., first node of red-black tree.

* - * @param array Tuples to be contained. + *

The current node N is at the {@link root_ root} of the tree.

+ * + *

In this case, it is repainted black to satisfy property 2 (the root is + * black). Since this adds one black node to + * every path at once, property 5 (all paths from any given node to its leaf nodes contain the same number + * of black nodes) is not violated.

+ * + * @param N A node to be inserted or swapped. */ - constructor(array: Array<[Key, T]>); + private insert_case1(N); /** - * Contruct from tuples. + *

N's parent ({@link XTreeNode.parent P}) is black.

+ * + *

The current node's parent {@link XTreeNode.parent P} is black, + * so property 4 (both children of every red node are + * black) is not invalidated.

+ * + *

In this case, the tree is still valid. Property 5 (all paths from any given node to its leaf nodes + * contain the same number of black nodes) is not threatened, because the + * current node N has two black leaf children, but because + * N is red, the paths through each of its children have the same + * number of black nodes as the path through the leaf it replaced, which was + * black, and so this property remains satisfied.

+ * + * @param N A node to be inserted or swapped. + */ + private insert_case2(N); + /** + *

N's parent ({@link XTreeNode.parent P}) and uncle + * ({@link XTreeNode.uncle U}) are red.

+ * + *

If both the parent {@link XTreeNode.parent P} and the uncle {@link XTreeNode.uncle U} + * are red, then both of them can be repainted black + * and the grandparent {@link XTreeNode.grand_parent G} becomes red (to + * maintain property 5 (all paths from any given node to its leaf nodes contain the same number of + * black nodes)).

+ * + *

Now, the current red node N has a + * black parent. Since any path through the parent or uncle must pass through + * the grandparent, the number of black nodes on these paths has not changed. + * + *

However, the grandparent {@link XTreeNode.grand_parent G} may now violate properties 2 (The + * root is black) or 4 (Both children of every red + * node are black) (property 4 possibly being violated since + * {@link XTreeNode.grand_parent G} may have a red parent).

+ * + *

To fix this, the entire procedure is recursively performed on {@link XTreeNode.grand_parent G} + * from case 1. Note that this is a tail-recursive call, so it could be rewritten as a loop; since this is + * the only loop, and any rotations occur after this loop, this proves that a constant number of rotations + * occur.

+ * + *

+ * + * @param N A node to be inserted or swapped. + */ + private insert_case3(N); + /** + *

N is added to right of left child of grandparent, or N is added to left + * of right child of grandparent ({@link XTreeNode.parent P} is red and + * {@link XTreeNode.uncle U} is black).

+ * + *

The parent {@link XTreeNode.parent P} is red but the uncle + * {@link XTreeNode.uncle U} is black; also, the current node + * N is the right child of {@link XTreeNode.parent P}, and + * {@link XTreeNode.parent P} in turn is the left child of its parent + * {@link XTreeNode.grand_parent G}.

+ * + *

In this case, a left rotation on {@link XTreeNode.parent P} that switches the roles of the + * current node N and its parent {@link XTreeNode.parent P} can be performed; then, + * the former parent node {@link XTreeNode.parent P} is dealt with using case 5 + * (relabeling N and {@link XTreeNode.parent P}) because property 4 (both children of + * every red node are black) is still violated.

+ * + *

The rotation causes some paths (those in the sub-tree labelled "1") to pass through the node + * N where they did not before. It also causes some paths (those in the sub-tree labelled "3") + * not to pass through the node {@link XTreeNode.parent P} where they did before. However, both of + * these nodes are red, so property 5 (all paths from any given node to its leaf + * nodes contain the same number of black nodes) is not violated by the + * rotation.

+ * + *

After this case has been completed, property 4 (both children of every red + * node are black) is still violated, but now we can resolve this by + * continuing to case 5.

+ * + *

+ * + * @param N A node to be inserted or swapped. + */ + private insert_case4(node); + /** + *

N is added to left of left child of grandparent, or N is added to right + * of right child of grandparent ({@link XTreeNode.parent P} is red and + * {@link XTreeNode.uncle U} is black).

+ * + *

The parent {@link XTreeNode.parent P} is red but the uncle + * {@link XTreeNode.uncle U} is black, the current node N + * is the left child of {@link XTreeNode.parent P}, and {@link XTreeNode.parent P} is the left + * child of its parent {@link XTreeNode.grand_parent G}.

+ * + *

In this case, a right rotation on {@link XTreeNode.grand_parent G} is performed; the result is a + * tree where the former parent {@link XTreeNode.parent P} is now the parent of both the current node + * N and the former grandparent {@link XTreeNode.grand_parent G}.

+ * + *

{@link XTreeNode.grand_parent G} is known to be black, since its + * former child {@link XTreeNode.parent P} could not have been red otherwise + * (without violating property 4). Then, the colors of {@link XTreeNode.parent P} and + * {@link XTreeNode.grand_parent G} are switched, and the resulting tree satisfies property 4 (both + * children of every red node are black). Property 5 + * (all paths from any given node to its leaf nodes contain the same number of + * black nodes) also remains satisfied, since all paths that went through any + * of these three nodes went through {@link XTreeNode.grand_parent G} before, and now they all go + * through {@link XTreeNode.parent P}. In each case, this is the only + * black node of the three.

+ * + *

* - * @param array Tuples to be contained. - * @param compare A binary predicate determines order of elements. + * @param N A node to be inserted or swapped. */ - constructor(array: Array<[Key, T]>, compare: (x: Key, y: Key) => boolean); + private insert_case5(node); /** - * Copy Constructor. + *

Erase an element with its node.

* - * @param container Another map to copy. - */ - constructor(container: TreeMap); - /** - * Copy Constructor. + *

In a regular binary search tree when deleting a node with two non-leaf children, we find either the + * maximum element in its left subtree (which is the in-order predecessor) or the minimum element in its + * right subtree (which is the in-order successor) and move its value into the node being deleted (as shown + * here). We then delete the node we copied the value from, which must have fewer than two non-leaf children. + * (Non-leaf children, rather than all children, are specified here because unlike normal binary search + * trees, red-black trees can have leaf nodes anywhere, so that all nodes are either internal nodes with + * two children or leaf nodes with, by definition, zero children. In effect, internal nodes having two leaf + * children in a red-black tree are like the leaf nodes in a regular binary search tree.) Because merely + * copying a value does not violate any red-black properties, this reduces to the problem of deleting a node + * with at most one non-leaf child. Once we have solved that problem, the solution applies equally to the + * case where the node we originally want to delete has at most one non-leaf child as to the case just + * considered where it has two non-leaf children.

* - * @param container Another map to copy. - * @param compare A binary predicate determines order of elements. - */ - constructor(container: TreeMap, compare: (x: Key, y: Key) => boolean); - /** - * Range Constructor. + *

Therefore, for the remainder of this discussion we address the deletion of a node with at most one + * non-leaf child. We use the label M to denote the node to be deleted; C will denote a + * selected child of M, which we will also call "its child". If M does have a non-leaf child, + * call that its child, C; otherwise, choose either leaf as its child, C.

* - * @param begin nput interator of the initial position in a sequence. - * @param end Input interator of the final position in a sequence. - */ - constructor(begin: Iterator>, end: Iterator>); - /** - * Range Constructor. + *

If M is a red node, we simply replace it with its child C, + * which must be black by property 4. (This can only occur when M has + * two leaf children, because if the red node M had a + * black non-leaf child on one side but just a leaf child on the other side, + * then the count of black nodes on both sides would be different, thus the + * tree would violate property 5.) All paths through the deleted node will simply pass through one fewer + * red node, and both the deleted node's parent and child must be + * black, so property 3 (all leaves are black) + * and property 4 (both children of every red node are + * black) still hold.

* - * @param begin nput interator of the initial position in a sequence. - * @param end Input interator of the final position in a sequence. - * @param compare A binary predicate determines order of elements. - */ - constructor(begin: Iterator>, end: Iterator>, compare: (x: Key, y: Key) => boolean); - /** - * @inheritdoc - */ - clear(): void; - /** - * @inheritdoc - */ - find(key: Key): MapIterator; - /** - * @inheritdoc - */ - key_comp(): (x: Key, y: Key) => boolean; - /** - * @inheritdoc - */ - value_comp(): (x: Pair, y: Pair) => boolean; - /** - * @inheritdoc - */ - lower_bound(key: Key): MapIterator; - /** - * @inheritdoc - */ - upper_bound(key: Key): MapIterator; - /** - * @inheritdoc - */ - equal_range(key: Key): Pair, MapIterator>; - /** - * @hidden - */ - protected _Insert_by_pair(pair: Pair): any; - /** - * @hidden - */ - protected _Insert_by_hint(hint: MapIterator, pair: Pair): MapIterator; - /** - * @hidden - */ - protected _Insert_by_range>>(first: InputIterator, last: InputIterator): void; - /** - * @inheritdoc - */ - protected _Handle_insert(first: MapIterator, last: MapIterator): void; - /** - * @inheritdoc - */ - protected _Handle_erase(first: MapIterator, last: MapIterator): void; - /** - *

Swap content.

+ *

Another simple case is when M is black and C is + * red. Simply removing a black node could break + * Properties 4 (“Both children of every red node are + * black”) and 5 (“All paths from any given node to its leaf nodes contain the + * same number of black nodes”), but if we repaint C + * black, both of these properties are preserved.

* - *

Exchanges the content of the container by the content of obj, which is another - * {@link TreeMap map} of the same type. Sizes abd container type may differ.

+ *

The complex case is when both M and C are black. (This + * can only occur when deleting a black node which has two leaf children, + * because if the black node M had a black + * non-leaf child on one side but just a leaf child on the other side, then the count of + * black nodes on both sides would be different, thus the tree would have been + * an invalid red-black tree by violation of property 5.) We begin by replacing M with its child + * C. We will relabel this child C (in its new position) N, and its sibling (its + * new parent's other child) {@link XTreeNode.sibling S}. ({@link XTreeNode.sibling S} was + * previously the sibling of M.)

* - *

After the call to this member function, the elements in this container are those which were - * in obj before the call, and the elements of obj are those which were in this. All - * iterators, references and pointers remain valid for the swapped objects.

+ *

In the diagrams below, we will also use {@link XTreeNode.parent P} for N's new + * parent (M's old parent), SL for {@link XTreeNode.sibling S}'s left child, and + * SR for {@link XTreeNode.sibling S}'s right child ({@link XTreeNode.sibling S} cannot + * be a leaf because if M and C were black, then + * {@link XTreeNode.parent P}'s one subtree which included M counted two + * black-height and thus {@link XTreeNode.parent P}'s other subtree + * which includes {@link XTreeNode.sibling S} must also count two + * black-height, which cannot be the case if {@link XTreeNode.sibling S} + * is a leaf node).

* - *

Notice that a non-member function exists with the same name, {@link std.swap swap}, overloading that - * algorithm with an optimization that behaves like this member function.

+ *

Notes

+ *
    + *
  1. + * The label N will be used to denote the current node (colored + * black). In the diagrams N carries a blue contour. At the + * beginning, this is the replacement node and a leaf, but the entire procedure may also be applied + * recursively to other nodes (see case 3). In between some cases, the roles and labels of the nodes + * are exchanged, but in each case, every label continues to represent the same node it represented at + * the beginning of the case. + *
  2. + *
  3. + * If a node in the right (target) half of a diagram carries a blue contour it will become the current + * node in the next iteration and there the other nodes will be newly assigned relative to it. Any + * color shown in the diagram is either assumed in its case or implied by those assumptions. + * White represents an arbitrary color (either red or + * black), but the same in both halves of the diagram. + *
  4. + *
  5. + * A numbered triangle represents a subtree of unspecified depth. A black + * circle atop a triangle means that black-height of subtree is greater + * by one compared to subtree without this circle. + *
  6. + *
* - * @param obj Another {@link TreeMap map container} of the same type of elements as this (i.e., - * with the same template parameters, Key and T) whose content is swapped - * with that of this {@link TreeMap container}. - */ - swap(obj: TreeMap): void; - /** - * @inheritdoc - */ - swap(obj: base.IContainer>): void; - } -} -declare namespace std.TreeMultiSet { - type iterator = std.SetIterator; - type reverse_iterator = std.SetReverseIterator; -} -declare namespace std { - /** - *

Tree-structured multiple-key set.

- * - *

{@link TreeMultiSet TreeMultiSets} are containers that store elements following a specific order, and - * where multiple elements can have equivalent values.

- * - *

In a {@link TreeMultiSet}, the value of an element also identifies it (the value is itself - * the key, of type T). The value of the elements in a {@link TreeMultiSet} cannot - * be modified once in the container (the elements are always const), but they can be inserted or removed - * from the

- * - *

Internally, the elements in a {@link TreeMultiSet TreeMultiSets} are always sorted following a strict - * weak ordering criterion indicated by its internal comparison method (of {@link IComparable.less less}).

- * - *

{@link TreeMultiSet} containers are generally slower than {@link HashMultiSet} containers - * to access individual elements by their key, but they allow the direct iteration on subsets based on - * their order.

- * - *

{@link TreeMultiSet TreeMultiSets} are typically implemented as binary search trees.

- * - *

- *

- * - *

Container properties

- *
- *
Associative
- *
- * Elements in associative containers are referenced by their key and not by their absolute - * position in the container. - *
- * - *
Ordered
- *
- * The elements in the container follow a strict order at all times. All inserted elements are - * given a position in this order. - *
- * - *
Set
- *
The value of an element is also the key used to identify it.
- * - *
Multiple equivalent keys
- *
Multiple elements in the container can have equivalent keys.
- *
- * - * @param Type of the elements. Each element in a {@link TreeMultiSet} container is also identified - * by this value (each value is itself also the element's key). - * - * @reference http://www.cplusplus.com/reference/set/multiset - * @author Jeongho Nam - */ - class TreeMultiSet extends base.MultiSet implements base.ITreeSet { - /** - * @hidden - */ - private tree_; - /** - * Default Constructor. - */ - constructor(); - /** - * Construct from compare. + *

If both N and its original parent are black, then + * deleting this original parent causes paths which proceed through N to have one fewer + * black node than paths that do not. As this violates property 5 (all paths + * from any given node to its leaf nodes contain the same number of black + * nodes), the tree must be rebalanced. There are several cases to consider:

+ * + *
    + *
  1. N is the new root.
  2. + *
  3. {@link XTreeNode.sibling S} is red.
  4. + *
  5. + * {@link XTreeNode.parent P}, {@link XTreeNode.sibling S}, and + * {@link XTreeNode.sibling S}'s children are black.
  6. + *
  7. + * {@link XTreeNode.sibling S} and {@link XTreeNode.sibling S}'s children are + * black, but {@link XTreeNode.parent P} is + * red. + *
  8. + *
  9. + * {@link XTreeNode.sibling S} is black, + * {@link XTreeNode.sibling S}'s left child is red, + * {@link XTreeNode.sibling S}'s right child is black, and + * N is the left child of its parent. + *
  10. + *
  11. + * {@link XTreeNode.sibling S} is black, + * {@link XTreeNode.sibling S}'s right child is red, and + * N is the left child of its parent {@link XTreeNode.parent P}. + *
  12. + *
* - * @param compare A binary predicate determines order of elements. - */ - constructor(compare: (x: T, y: T) => boolean); - /** - * Contruct from elements. + *

Again, the function calls all use tail recursion, so the algorithm is in-place.

* - * @param array Elements to be contained. - */ - constructor(array: Array); - /** - * Contruct from elements with compare. + *

In the algorithm above, all cases are chained in order, except in delete case 3 where it can recurse + * to case 1 back to the parent node: this is the only case where an iterative implementation will + * effectively loop. No more than h loops back to case 1 will occur (where h is the height of the tree). + * And because the probability for escalation decreases exponentially with each iteration the average + * removal cost is constant.

* - * @param array Elements to be contained. - * @param compare A binary predicate determines order of elements. - */ - constructor(array: Array, compare: (x: T, y: T) => boolean); - /** - * Copy Constructor. - */ - constructor(container: TreeMultiSet); - /** - * Copy Constructor with compare. + *

Additionally, no tail recursion ever occurs on a child node, so the tail recursion loop can only + * move from a child back to its successive ancestors. If a rotation occurs in case 2 (which is the only + * possibility of rotation within the loop of cases 1–3), then the parent of the node N + * becomes red after the rotation and we will exit the loop. Therefore, at most one + * rotation will occur within this loop. Since no more than two additional rotations will occur after + * exiting the loop, at most three rotations occur in total.

* - * @param container A container to be copied. - * @param compare A binary predicate determines order of elements. + * @param val An element to erase. */ - constructor(container: TreeMultiSet, compare: (x: T, y: T) => boolean); + erase(val: T): void; /** - * Range Constructor. + *

N is the new root.

* - * @param begin Input interator of the initial position in a sequence. - * @param end Input interator of the final position in a sequence. - */ - constructor(begin: Iterator, end: Iterator); - /** - * Construct from range and compare. + *

In this case, we are done. We removed one black node from every path, + * and the new root is black, so the properties are preserved.

* - * @param begin Input interator of the initial position in a sequence. - * @param end Input interator of the final position in a sequence. - * @param compare A binary predicate determines order of elements. - */ - constructor(begin: Iterator, end: Iterator, compare: (x: T, y: T) => boolean); - /** - * @inheritdoc - */ - clear(): void; - /** - * @inheritdoc - */ - find(val: T): SetIterator; - /** - * @inheritdoc - */ - count(val: T): number; - /** - * @inheritdoc - */ - key_comp(): (x: T, y: T) => boolean; - /** - * @inheritdoc - */ - value_comp(): (x: T, y: T) => boolean; - /** - * @inheritdoc + *

Note

+ *

In cases 2, 5, and 6, we assume N is the left child of its parent + * {@link XTreeNode.parent P}. If it is the right child, left and right should be reversed throughout + * these three cases. Again, the code examples take both cases into account.

+ * + * @param N A node to be erased or swapped. */ - lower_bound(val: T): SetIterator; + private erase_case1(N); /** - * @inheritdoc + *

{@link XTreeNode.sibling S} is red.

+ * + *

+ * + *

In this case we reverse the colors of {@link XTreeNode.parent P} and + * {@link XTreeNode.sibling S}, and then rotate left at {@link XTreeNode.parent P}, turning + * {@link XTreeNode.sibling S} into N's grandparent.

+ * + *

Note that {@link XTreeNode.parent P} has to be black as it had a + * red child. The resulting subtree has a path short one + * black node so we are not done. Now N has a + * black sibling and a red parent, so we can proceed + * to step 4, 5, or 6. (Its new sibling is black because it was once the child + * of the red {@link XTreeNode.sibling S}.) In later cases, we will re-label + * N's new sibling as {@link XTreeNode.sibling S}.

+ * + * @param N A node to be erased or swapped. */ - upper_bound(val: T): SetIterator; + private erase_case2(N); /** - * @inheritdoc + *

{@link XTreeNode.parent P}, {@link XTreeNode.sibling S}, and {@link XTreeNode.sibling + * S}'s children are black.

+ * + *

+ * + *

In this case, we simply repaint {@link XTreeNode.sibling S} red. The + * result is that all paths passing through {@link XTreeNode.sibling S}, which are precisely those + * paths not passing through N, have one less black node. + * Because deleting N's original parent made all paths passing through N have + * one less black node, this evens things up.

+ * + *

However, all paths through {@link XTreeNode.parent P} now have one fewer + * black node than paths that do not pass through + * {@link XTreeNode.parent P}, so property 5 (all paths from any given node to its leaf nodes contain + * the same number of black nodes) is still violated.

+ * + *

To correct this, we perform the rebalancing procedure on {@link XTreeNode.parent P}, starting + * at case 1.

+ * + * @param N A node to be erased or swapped. */ - equal_range(val: T): Pair, SetIterator>; + private erase_case3(N); /** - * @hidden + *

{@link XTreeNode.sibling S} and {@link XTreeNode.sibling S}'s children are + * black, but {@link XTreeNode.parent P} is red.

+ * + *

+ * + *

In this case, we simply exchange the colors of {@link XTreeNode.sibling S} and + * {@link XTreeNode.parent P}. This does not affect the number of black + * nodes on paths going through {@link XTreeNode.sibling S}, but it does add one to the number of + * black nodes on paths going through N, making up for the + * deleted black node on those paths.

+ * + * @param N A node to be erased or swapped. */ - protected _Insert_by_val(val: T): any; + private erase_case4(N); /** - * @hidden + *

{@link XTreeNode.sibling S} is black, {@link XTreeNode.sibling S}'s + * left child is red, {@link XTreeNode.sibling S}'s right child is + * black, and N is the left child of its parent.

+ * + *

+ * + *

In this case we rotate right at {@link XTreeNode.sibling S}, so that + * {@link XTreeNode.sibling S}'s left child becomes {@link XTreeNode.sibling S}'s parent and + * N's new sibling. We then exchange the colors of {@link XTreeNode.sibling S} and its + * new parent.

+ * + *

All paths still have the same number of black nodes, but now + * N has a black sibling whose right child is + * red, so we fall into case 6. Neither N nor its parent are affected + * by this transformation. (Again, for case 6, we relabel N's new sibling as + * {@link XTreeNode.sibling S}.)

+ * + * @param N A node to be erased or swapped. */ - protected _Insert_by_hint(hint: SetIterator, val: T): SetIterator; + private erase_case5(N); /** - * @hidden + *

{@link XTreeNode.sibling S} is black, + * {@link XTreeNode.sibling S}'s right child is red, and N is + * the left child of its parent {@link XTreeNode.parent P}.

+ * + *

In this case we rotate left at {@link XTreeNode.parent P}, so that + * {@link XTreeNode.sibling S} becomes the parent of {@link XTreeNode.parent P} and + * {@link XTreeNode.sibling S}'s right child. We then exchange the colors of + * {@link XTreeNode.parent P} and {@link XTreeNode.sibling S}, and make + * {@link XTreeNode.sibling S}'s right child black.

+ * + *

The subtree still has the same color at its root, so Properties 4 (Both children of every + * red node are black) and 5 (All paths from any + * given node to its leaf nodes contain the same number of black nodes) are + * not violated. However, N now has one additional black + * ancestor: either {@link XTreeNode.parent P} has become black, or it + * was black and {@link XTreeNode.sibling S} was added as a + * black grandparent.

+ * + *

Thus, the paths passing through N pass through one additional + * black node.

+ * + *

+ * + *

Meanwhile, if a path does not go through N, then there are two possibilities:

+ *
    + *
  1. + * It goes through N's new sibling SL, a node with arbitrary color and the root of + * the subtree labeled 3 (s. diagram). Then, it must go through {@link XTreeNode.sibling S} and + * {@link XTreeNode.parent P}, both formerly and currently, as they have only exchanged colors + * and places. Thus the path contains the same number of black nodes. + *
  2. + *
  3. + * It goes through N's new uncle, {@link XTreeNode.sibling S}'s right child. Then, + * it formerly went through {@link XTreeNode.sibling S}, {@link XTreeNode.sibling S}'s + * parent, and {@link XTreeNode.sibling S}'s right child SR (which was + * red), but now only goes through {@link XTreeNode.sibling S}, which + * has assumed the color of its former parent, and {@link XTreeNode.sibling S}'s right child, + * which has changed from red to black (assuming + * {@link XTreeNode.sibling S}'s color: black). The net effect is + * that this path goes through the same number of black nodes. + *
  4. + *
+ * + *

Either way, the number of black nodes on these paths does not change. + * Thus, we have restored Properties 4 (Both children of every red node are + * black) and 5 (All paths from any given node to its leaf nodes contain the + * same number of black nodes). The white node in the diagram can be either + * red or black, but must refer to the same color + * both before and after the transformation.

+ * + * @param N A node to be erased or swapped. */ - protected _Insert_by_range>(first: InputIterator, last: InputIterator): void; + private erase_case6(node); /** - * @inheritdoc + * Rotate a node left. + * + * @param node Node to rotate left. */ - protected _Handle_insert(first: SetIterator, last: SetIterator): void; + protected rotate_left(node: XTreeNode): void; /** - * @inheritdoc + * Rotate a node to right. + * + * @param node A node to rotate right. */ - protected _Handle_erase(first: SetIterator, last: SetIterator): void; + protected rotate_right(node: XTreeNode): void; /** - *

Swap content.

- * - *

Exchanges the content of the container by the content of obj, which is another - * {@link TreeMultiSet set} of the same type. Sizes abd container type may differ.

- * - *

After the call to this member function, the elements in this container are those which were - * in obj before the call, and the elements of obj are those which were in this. All - * iterators, references and pointers remain valid for the swapped objects.

- * - *

Notice that a non-member function exists with the same name, {@link std.swap swap}, overloading that - * algorithm with an optimization that behaves like this member function.

+ * Replace a node. * - * @param obj Another {@link TreeMultiSet set container} of the same type of elements as this (i.e., - * with the same template parameters, Key and T) whose content is swapped - * with that of this {@link TreeMultiSet container}. + * @param oldNode Ordinary node to be replaced. + * @param newNode Target node to replace. */ - swap(obj: TreeMultiSet): void; + protected replace_node(oldNode: XTreeNode, newNode: XTreeNode): void; /** - * @inheritdoc + * Fetch color from a node. + * + * @param node A node to fetch color. + * @retur color. */ - swap(obj: base.IContainer): void; + private fetch_color(node); } } -declare namespace std.TreeMultiMap { - type iterator = std.MapIterator; - type reverse_iterator = std.MapReverseIterator; -} -declare namespace std { +declare namespace std.base { /** - *

Tree-structured multiple-key map.

+ *

Common interface for tree-structured map.

* - *

{@link TreeMultiMap TreeMultiMaps} are associative containers that store elements formed by a combination of - * a key value and a mapped value, following a specific order, and where multiple elements can - * have equivalent keys.

+ *

{@link ITreeMap ITreeMaps} are associative containers that store elements formed by a combination of + * a key value and a mapped value, following a specific order.

* - *

In a {@link TreeMultiMap}, the key values are generally used to sort and uniquely identify + *

In a {@link ITreeMap}, the key values are generally used to sort and uniquely identify * the elements, while the mapped values store the content associated to this key. The types of * key and mapped value may differ, and are grouped together in member type * value_type, which is a {@link Pair} type combining both:

* *

typedef Pair value_type;

* - *

Internally, the elements in a {@link TreeMultiMap}are always sorted by its key following a + *

Internally, the elements in a {@link ITreeMap}are always sorted by its key following a * strict weak ordering criterion indicated by its internal comparison method (of {@link less}).

* - *

{@link TreeMultiMap}containers are generally slower than {@link HashMap} containers + *

{@link ITreeMap}containers are generally slower than {@link IHashMap} containers * to access individual elements by their key, but they allow the direct iteration on subsets based * on their order.

* - *

{@link TreeMultiMap TreeMultiMaps} are typically implemented as binary search trees.

+ *

{@link ITreeMap TreeMultiMaps} are typically implemented as binary search trees.

* - *

< - * img src="http://samchon.github.io/typescript-stl/images/design/class_diagram/map_containers.png" style="max-width: 100%" />

+ *

+ *

* *

Container properties

*
*
Associative
- *
- * Elements in associative containers are referenced by their key and not by their absolute - * position in the container. - *
+ *
Elements in associative containers are referenced by their key and not by their absolute + * position in the container.
* *
Ordered
- *
- * The elements in the container follow a strict order at all times. All inserted elements are - * given a position in this order. - *
+ *
The elements in the container follow a strict order at all times. All inserted elements are + * given a position in this order.
* *
Map
- *
- * Each element associates a key to a mapped value: - * Keys are meant to identify the elements whose main content is the mapped value. - *
- * - *
Multiple equivalent keys
- *
Multiple elements in the container can have equivalent keys.
+ *
Each element associates a key to a mapped value: + * Keys are meant to identify the elements whose main content is the mapped value.
*
* * @param Type of the keys. Each element in a map is uniquely identified by its key value. * @param Type of the mapped value. Each element in a map stores some data as its mapped value. * - * @reference http://www.cplusplus.com/reference/map/multimap + * @reference http://www.cplusplus.com/reference/map * @author Jeongho Nam */ - class TreeMultiMap extends base.MultiMap implements base.ITreeMap { - /** - * @hidden - */ - private tree_; - /** - * Default Constructor. - */ - constructor(); + interface ITreeMap { /** - * Construct from compare. + *

Return key comparison function.

* - * @param compare A binary predicate determines order of elements. - */ - constructor(compare: (x: Key, y: Key) => boolean); - /** - * Contruct from elements. + *

Returns a references of the comparison function used by the container to compare keys.

* - * @param array Elements to be contained. - */ - constructor(array: Array>); - /** - * Contruct from elements. + *

The comparison object of a {@link ITreeMap tree-map object} is set on + * {@link TreeMap.constructor construction}. Its type (Key) is the last parameter of the + * {@link ITreeMap.constructor constructors}. By default, this is a {@link less} function, which returns the same + * as operator<.

* - * @param array Elements to be contained. - * @param compare A binary predicate determines order of elements. - */ - constructor(array: Array>, compare: (x: Key, y: Key) => boolean); - /** - * Contruct from tuples. + *

This function determines the order of the elements in the container: it is a function pointer that takes + * two arguments of the same type as the element keys, and returns true if the first argument + * is considered to go before the second in the strict weak ordering it defines, and false otherwise. + *

* - * @param array Tuples to be contained. - */ - constructor(array: Array<[Key, T]>); - /** - * Contruct from tuples. + *

Two keys are considered equivalent if {@link key_comp} returns false reflexively (i.e., no + * matter the order in which the keys are passed as arguments).

* - * @param array Tuples to be contained. - * @param compare A binary predicate determines order of elements. + * @return The comparison function. */ - constructor(array: Array<[Key, T]>, compare: (x: Key, y: Key) => boolean); + key_comp(): (x: Key, y: Key) => boolean; /** - * Copy Constructor. + *

Return value comparison function.

* - * @param container Another map to copy. - */ - constructor(container: TreeMultiMap); - /** - * Copy Constructor. + *

Returns a comparison function that can be used to compare two elements to get whether the key of the first + * one goes before the second.

* - * @param container Another map to copy. - * @param compare A binary predicate determines order of elements. - */ - constructor(container: TreeMultiMap, compare: (x: Key, y: Key) => boolean); - /** - * Range Constructor. + *

The arguments taken by this function object are of member type std.Pair (defined in + * {@link ITreeMap}), but the mapped type (T) part of the value is not taken into consideration in this + * comparison.

* - * @param begin nput interator of the initial position in a sequence. - * @param end Input interator of the final position in a sequence. - */ - constructor(begin: Iterator>, end: Iterator>); - /** - * Range Constructor. + *

This comparison class returns true if the {@link Pair.first key} of the first argument + * is considered to go before that of the second (according to the strict weak ordering specified by the + * container's comparison function, {@link key_comp}), and false otherwise.

* - * @param begin nput interator of the initial position in a sequence. - * @param end Input interator of the final position in a sequence. - * @param compare A binary predicate determines order of elements. - */ - constructor(begin: Iterator>, end: Iterator>, compare: (x: Key, y: Key) => boolean); - /** - * @inheritdoc - */ - clear(): void; - /** - * @inheritdoc - */ - find(key: Key): MapIterator; - /** - * @inheritdoc - */ - count(key: Key): number; - /** - * @inheritdoc - */ - key_comp(): (x: Key, y: Key) => boolean; - /** - * @inheritdoc + * @return The comparison function for element values. */ value_comp(): (x: Pair, y: Pair) => boolean; /** - * @inheritdoc - */ - lower_bound(key: Key): MapIterator; - /** - * @inheritdoc - */ - upper_bound(key: Key): MapIterator; - /** - * @inheritdoc - */ - equal_range(key: Key): Pair, MapIterator>; - /** - * @hidden - */ - protected _Insert_by_pair(pair: Pair): any; - /** - * @hidden - */ - protected _Insert_by_hint(hint: MapIterator, pair: Pair): MapIterator; - /** - * @hidden - */ - protected _Insert_by_range>>(first: InputIterator, last: InputIterator): void; - /** - * @inheritdoc - */ - protected _Handle_insert(first: MapIterator, last: MapIterator): void; - /** - * @inheritdoc - */ - protected _Handle_erase(first: MapIterator, last: MapIterator): void; - /** - *

Swap content.

- * - *

Exchanges the content of the container by the content of obj, which is another - * {@link TreeMapMulti map} of the same type. Sizes abd container type may differ.

- * - *

After the call to this member function, the elements in this container are those which were - * in obj before the call, and the elements of obj are those which were in this. All - * iterators, references and pointers remain valid for the swapped objects.

+ *

Return iterator to lower bound.

* - *

Notice that a non-member function exists with the same name, {@link std.swap swap}, overloading that - * algorithm with an optimization that behaves like this member function.

+ *

Returns an iterator pointing to the first element in the container whose key is not considered to + * go before k (i.e., either it is equivalent or goes after).

* - * @param obj Another {@link TreeMapMulti map container} of the same type of elements as this (i.e., - * with the same template parameters, Key and T) whose content is swapped - * with that of this {@link TreeMapMulti container}. - */ - swap(obj: TreeMultiMap): void; - /** - * @inheritdoc - */ - swap(obj: base.IContainer>): void; - } -} -declare namespace std { - /** - *

System error exception.

- * - *

This class defines the type of objects thrown as exceptions to report conditions originating during - * runtime from the operating system or other low-level application program interfaces which have an - * associated {@link ErrorCode}.

- * - *

The class inherits from {@link RuntimeError}, to which it adds an {@link ErrorCode} as - * member code (and defines a specialized what member).

- * - *

- *

- * - * @reference http://www.cplusplus.com/reference/system_error/system_error - * @author Jeongho Nam - */ - class SystemError extends RuntimeError { - /** - * @hidden - */ - protected code_: ErrorCode; - /** - * Construct from an error code. + *

The function uses its internal comparison object (key_comp) to determine this, returning an + * iterator to the first element for which key_comp(k, element_key) would return false.

* - * @param code An {@link ErrorCode} object. - */ - constructor(code: ErrorCode); - /** - * Construct from an error code and message. + *

If the {@link ITreeMap} class is instantiated with the default comparison type ({@link less}), + * the function returns an iterator to the first element whose key is not less than k

. * - * @param code An {@link ErrorCode} object. - * @param message A message incorporated in the string returned by member {@link what what()}. - */ - constructor(code: ErrorCode, message: string); - /** - * Construct from a numeric value and error category. + *

A similar member function, {@link upper_bound}, has the same behavior as {@link lower_bound}, except + * in the case that the {@link ITreeMap} contains an element with a key equivalent to k: In this + * case, {@link lower_bound} returns an iterator pointing to that element, whereas {@link upper_bound} + * returns an iterator pointing to the next element.

* - * @param val A numerical value identifying an error code. - * @param category A reference to an {@link ErrorCode} object. + * @param k Key to search for. + * + * @return An iterator to the the first element in the container whose key is not considered to go before + * k, or {@link ITreeMap.end} if all keys are considered to go before k. */ - constructor(val: number, category: ErrorCategory); + lower_bound(key: Key): MapIterator; /** - * Construct from a numeric value, error category and message. + *

Return iterator to upper bound.

* - * @param val A numerical value identifying an error code. - * @param category A reference to an {@link ErrorCode} object. - * @param message A message incorporated in the string returned by member {@link what what()}. + *

Returns an iterator pointing to the first element in the container whose key is considered to + * go after k

. + * + *

The function uses its internal comparison object (key_comp) to determine this, returning an + * iterator to the first element for which key_comp(k, element_key) would return true.

+ * + *

If the {@link ITreeMap} class is instantiated with the default comparison type ({@link less}), + * the function returns an iterator to the first element whose key is greater than k

. + * + *

A similar member function, {@link lower_bound}, has the same behavior as {@link upper_bound}, except + * in the case that the map contains an element with a key equivalent to k: In this case + * {@link lower_bound} returns an iterator pointing to that element, whereas {@link upper_bound} returns an + * iterator pointing to the next element.

+ * + * @param k Key to search for. + * + * @return An iterator to the the first element in the container whose key is considered to go after + * k, or {@link TreeMap.end end} if no keys are considered to go after k. */ - constructor(val: number, category: ErrorCategory, message: string); + upper_bound(key: Key): MapIterator; /** - *

Get error code.

+ *

Get range of equal elements.

* - *

Returns the {@link ErrorCode} object associated with the exception.

+ *

Returns the bounds of a range that includes all the elements in the container which have a key + * equivalent to k

. * - *

This value is either the {@link ErrorCode} passed to the construction or its equivalent - * (if constructed with a value and a {@link category}.

+ *

If no matches are found, the range returned has a length of zero, with both iterators pointing to + * the first element that has a key considered to go after k according to the container's internal + * comparison object (key_comp).

* - * @return The {@link ErrorCode} associated with the object. + *

Two keys are considered equivalent if the container's comparison object returns false reflexively + * (i.e., no matter the order in which the keys are passed as arguments).

+ * + * @param k Key to search for. + * + * @return The function returns a {@link Pair}, whose member {@link Pair.first} is the lower bound of + * the range (the same as {@link lower_bound}), and {@link Pair.second} is the upper bound + * (the same as {@link upper_bound}). */ - code(): ErrorCode; + equal_range(key: Key): Pair, MapIterator>; } } -declare namespace std { +declare namespace std.base { /** - *

Error category.

- * - *

This type serves as a base class for specific category types.

- * - *

Category types are used to identify the source of an error. They also define the relation between - * {@link ErrorCode} and {@link ErrorCondition}objects of its category, as well as the message set for {@link ErrorCode} - * objects. - * - *

Objects of these types have no distinct values and are not-copyable and not-assignable, and thus can only be - * passed by reference. As such, only one object of each of these types shall exist, each uniquely identifying its own - * category: all error codes and conditions of a same category shall return a reference to same object.

+ *

A red-black tree storing {@link MapIterator MapIterators}.

* - *

- *

+ *

+ *

* - * @reference http://www.cplusplus.com/reference/system_error/error_category * @author Jeongho Nam */ - abstract class ErrorCategory { + class PairTree extends XTree> { + /** + * @hidden + */ + private map_; + /** + * @hidden + */ + private compare_; /** * Default Constructor. */ - constructor(); + constructor(map: TreeMap | TreeMultiMap, compare?: (x: Key, y: Key) => boolean); + find(key: Key): XTreeNode>; + find(it: MapIterator): XTreeNode>; /** - *

Return category name.

+ * @hidden + */ + private find_by_key(key); + /** + *

Return iterator to lower bound.

* - *

In derived classes, the function returns a string naming the category.

+ *

Returns an iterator pointing to the first element in the container whose key is not considered to + * go before k (i.e., either it is equivalent or goes after).

* - *

In {@link ErrorCategory}, it is a pure virtual member function.

+ *

The function uses its internal comparison object (key_comp) to determine this, returning an + * iterator to the first element for which key_comp(k, element_key) would return false.

* - *
    - *
  • In the {@link GenericCategory} object, it returns "generic".
  • - *
  • In the {@link SystemCategory} object, it returns "system".
  • - *
  • In the {@link IOStreamCategory} object, it returns "iostream".
  • - *
+ *

If the {@link ITreeMap} class is instantiated with the default comparison type ({@link less}), + * the function returns an iterator to the first element whose key is not less than k

. * - * @return The category name. + *

A similar member function, {@link upper_bound}, has the same behavior as {@link lower_bound}, except + * in the case that the {@link ITreeMap} contains an element with a key equivalent to k: In this + * case, {@link lower_bound} returns an iterator pointing to that element, whereas {@link upper_bound} + * returns an iterator pointing to the next element.

+ * + * @param k Key to search for. + * + * @return An iterator to the the first element in the container whose key is not considered to go before + * k, or {@link ITreeMap.end} if all keys are considered to go before k. */ - abstract name(): string; + lower_bound(key: Key): MapIterator; /** - *

Error message.

+ *

Return iterator to upper bound.

* - *

In derived classes, the function returns a string object with a message describing the error condition - * denoted by val.

+ *

Returns an iterator pointing to the first element in the container whose key is considered to + * go after k

. * - *

In {@link ErrorCategory}, it is a pure virtual member function.

+ *

The function uses its internal comparison object (key_comp) to determine this, returning an + * iterator to the first element for which key_comp(k, element_key) would return true.

* - *

This function is called both by {@link ErrorCode.message ErrorCode.message()} and - * {@link ErrorCondition.message ErrorCondition.message()} to obtain the corresponding message in the - * {@link category}. Therefore, numerical values used by custom error codes and - * {@link ErrorCondition error conditions} should only match for a category if they describe the same error.

+ *

If the {@link ITreeMap} class is instantiated with the default comparison type ({@link less}), + * the function returns an iterator to the first element whose key is greater than k

. * - * @param val A numerical value identifying an error condition. - * If the {@link ErrorCategory} object is the {@link GenericCategory}, this argument is equivalent to an - * {@link errno} value. + *

A similar member function, {@link lower_bound}, has the same behavior as {@link upper_bound}, except + * in the case that the map contains an element with a key equivalent to k: In this case + * {@link lower_bound} returns an iterator pointing to that element, whereas {@link upper_bound} returns an + * iterator pointing to the next element.

* - * @return A string object with the message. + * @param k Key to search for. + * + * @return An iterator to the the first element in the container whose key is considered to go after + * k, or {@link TreeMap.end end} if no keys are considered to go after k. */ - abstract message(val: number): string; + upper_bound(key: Key): MapIterator; /** - *

Default error condition.

- * - *

Returns the default {@link ErrorCondition}object of this category that is associated with the - * {@link ErrorCode} identified by a value of val.

- * - *

Its definition in the base class {@link ErrorCategory} returns the same as constructing an - * {@link ErrorCondition} object with: + *

Get range of equal elements.

* - *

new ErrorCondition(val, *this);

+ *

Returns the bounds of a range that includes all the elements in the container which have a key + * equivalent to k

. * - *

As a virtual member function, this behavior can be overriden in derived classes.

+ *

If no matches are found, the range returned has a length of zero, with both iterators pointing to + * the first element that has a key considered to go after k according to the container's internal + * comparison object (key_comp).

* - *

This function is called by the default definition of member {@link equivalent equivalent()}, which is used to - * compare {@link ErrorCondition error conditions} with error codes.

+ *

Two keys are considered equivalent if the container's comparison object returns false reflexively + * (i.e., no matter the order in which the keys are passed as arguments).

* - * @param val A numerical value identifying an error condition. + * @param k Key to search for. * - * @return The default {@link ErrorCondition}object associated with condition value val for this category. + * @return The function returns a {@link Pair}, whose member {@link Pair.first} is the lower bound of + * the range (the same as {@link lower_bound}), and {@link Pair.second} is the upper bound + * (the same as {@link upper_bound}). */ - default_error_condition(val: number): ErrorCondition; + equal_range(key: Key): Pair, MapIterator>; /** - *

Check error code equivalence.

+ *

Return key comparison function.

* - *

Checks whether, for the category, an {@link ErrorCode error code} is equivalent to an - * {@link ErrorCondition error condition.

+ *

Returns a references of the comparison function used by the container to compare keys.

* - *

This function is called by the overloads of comparison operators when an {@link ErrorCondition} object is - * compared to an {@link ErrorCode} object to check for equality or inequality. If either one of those objects' - * {@link ErrorCategory categories} considers the other equivalent using this function, they are considered - * equivalent by the operator.

+ *

The comparison object of a {@link ITreeMap tree-map object} is set on + * {@link TreeMap.constructor construction}. Its type (Key) is the last parameter of the + * {@link ITreeMap.constructor constructors}. By default, this is a {@link less} function, which returns the same + * as operator<.

* - *

As a virtual member function, this behavior can be overridden in derived classes to define a different - * correspondence mechanism for each {@link ErrorCategory} type.

+ *

This function determines the order of the elements in the container: it is a function pointer that takes + * two arguments of the same type as the element keys, and returns true if the first argument + * is considered to go before the second in the strict weak ordering it defines, and false otherwise. + *

* - * @param val_code A numerical value identifying an error code. - * @param cond An object of an {@link ErrorCondition} type. + *

Two keys are considered equivalent if {@link key_comp} returns false reflexively (i.e., no + * matter the order in which the keys are passed as arguments).

* - * @return true if the arguments are considered equivalent. false otherwise. + * @return The comparison function. */ - equivalent(val_code: number, cond: ErrorCondition): boolean; + key_comp(): (x: Key, y: Key) => boolean; /** - *

Check error code equivalence.

- * - *

Checks whether, for the category, an {@link ErrorCode error code} is equivalent to an - * {@link ErrorCondition error condition.

+ *

Return value comparison function.

* - *

This function is called by the overloads of comparison operators when an {@link ErrorCondition} object is - * compared to an {@link ErrorCode} object to check for equality or inequality. If either one of those objects' - * {@link ErrorCategory categories} considers the other equivalent using this function, they are considered - * equivalent by the operator.

+ *

Returns a comparison function that can be used to compare two elements to get whether the key of the first + * one goes before the second.

* - *

As a virtual member function, this behavior can be overridden in derived classes to define a different - * correspondence mechanism for each {@link ErrorCategory} type.

+ *

The arguments taken by this function object are of member type std.Pair (defined in + * {@link ITreeMap}), but the mapped type (T) part of the value is not taken into consideration in this + * comparison.

* - * @param code An object of an {@link ErrorCode} type. - * @param val_cond A numerical value identifying an error code. + *

This comparison class returns true if the {@link Pair.first key} of the first argument + * is considered to go before that of the second (according to the strict weak ordering specified by the + * container's comparison function, {@link key_comp}), and false otherwise.

* - * @return true if the arguments are considered equivalent. false otherwise. + * @return The comparison function for element values. */ - equivalent(code: ErrorCode, val_cond: number): boolean; - } -} -declare namespace std { - /** - *

Error condition.

- * - *

Objects of this type hold a condition {@link value} associated with a {@link category}.

- * - *

Objects of this type describe errors in a generic way so that they may be portable across different - * systems. This is in contrast with {@link ErrorCode} objects, that may contain system-specific - * information.

- * - *

Because {@link ErrorCondition}objects can be compared with error_code objects directly by using - * relational operators, {@link ErrorCondition}objects are generally used to check whether - * a particular {@link ErrorCode} obtained from the system matches a specific error condition no matter - * the system.

- * - *

The {@link ErrorCategory categories} associated with the {@link ErrorCondition} and the - * {@link ErrorCode} define the equivalences between them.

- * - *

- *

- * - * @reference http://www.cplusplus.com/reference/system_error/error_condition - * @author Jeongho Nam - */ - class ErrorCondition extends base.ErrorInstance { + value_comp(): (x: Pair, y: Pair) => boolean; /** - * Default Constructor. + * @inheritdoc */ - constructor(); + is_equal_to(left: MapIterator, right: MapIterator): boolean; /** - * Construct from a numeric value and error category. - * - * @param val A numerical value identifying an error condition. - * @param category A reference to an {@link ErrorCategory} object. + * @inheritdoc */ - constructor(val: number, category: ErrorCategory); + is_less(left: MapIterator, right: MapIterator): boolean; } } -declare namespace std { +declare namespace std.base { /** - *

Error code.

+ *

A common interface for tree-structured set.

* - *

Objects of this type hold an error code {@link value} associated with a {@link category}.

+ *

{@link ITreeSet TreeMultiSets} are containers that store elements following a specific order.

* - *

The operating system and other low-level applications and libraries generate numerical error codes to - * represent possible results. These numerical values may carry essential information for a specific platform, - * but be non-portable from one platform to another.

+ *

In a {@link ITreeSet}, the value of an element also identifies it (the value is itself + * the key, of type T). The value of the elements in a {@link ITreeSet} cannot + * be modified once in the container (the elements are always const), but they can be inserted or removed + * from the

* - *

Objects of this class associate such numerical codes to {@link ErrorCategory error categories}, so that they - * can be interpreted when needed as more abstract (and portable) {@link ErrorCondition error conditions}.

+ *

Internally, the elements in a {@link ITreeSet TreeMultiSets} are always sorted following a strict + * weak ordering criterion indicated by its internal comparison method (of {@link IComparable.less less}).

* - *

- *

+ *

{@link ITreeSet} containers are generally slower than {@link IHashSet} containers + * to access individual elements by their key, but they allow the direct iteration on subsets based on + * their order.

* - * @reference http://www.cplusplus.com/reference/system_error/error_code - * @author Jeongho Nam - */ - class ErrorCode extends base.ErrorInstance { - /** - * Default Constructor. - */ - constructor(); - /** - * Construct from a numeric value and error category. - * - * @param val A numerical value identifying an error code. - * @param category A reference to an {@link ErrorCategory} object. - */ - constructor(val: number, category: ErrorCategory); - } -} -declare namespace std { - /** - *

Running on Node.

+ *

{@link ITreeSet TreeMultiSets} are typically implemented as binary search trees.

* - *

Test whether the JavaScript is running on Node.

+ *

+ *

* - * @references http://stackoverflow.com/questions/17575790/environment-detection-node-js-or-browser - */ - function is_node(): boolean; - /** - *

Pair of values.

+ *

Container properties

+ *
+ *
Associative
+ *
+ * Elements in associative containers are referenced by their key and not by their absolute + * position in the container. + *
* - *

This class couples together a pair of values, which may be of different types (T1 and - * T2). The individual values can be accessed through its public members {@link first} and - * {@link second}.

+ *
Ordered
+ *
+ * The elements in the container follow a strict order at all times. All inserted elements are + * given a position in this order. + *
* - * @param Type of member {@link first}. - * @param Type of member {@link second}. + *
Set
+ *
The value of an element is also the key used to identify it.
+ *
* - * @reference http://www.cplusplus.com/reference/utility/pair + * @param Type of the elements. Each element in a {@link ITreeSet} container is also identified + * by this value (each value is itself also the element's key). + * + * @reference http://www.cplusplus.com/reference/set * @author Jeongho Nam */ - class Pair { + interface ITreeSet { /** - *

A first value in the Pair.

+ *

Return comparison function.

+ * + *

Returns a copy of the comparison function used by the container.

+ * + *

By default, this is a {@link less} object, which returns the same as operator<.

+ * + *

This object determines the order of the elements in the container: it is a function pointer or a function + * object that takes two arguments of the same type as the container elements, and returns true if + * the first argument is considered to go before the second in the strict weak ordering it + * defines, and false otherwise.

+ * + *

Two elements of a {@link ITreeSet} are considered equivalent if {@link key_comp} returns false + * reflexively (i.e., no matter the order in which the elements are passed as arguments).

+ * + *

In {@link ITreeSet} containers, the keys to sort the elements are the values (T) themselves, + * therefore {@link key_comp} and its sibling member function {@link value_comp} are equivalent.

+ * + * @return The comparison function. */ - first: T1; + key_comp(): (x: T, y: T) => boolean; /** - *

A second value in the Pair.

+ *

Return comparison function.

+ * + *

Returns a copy of the comparison function used by the container.

+ * + *

By default, this is a {@link less} object, which returns the same as operator<.

+ * + *

This object determines the order of the elements in the container: it is a function pointer or a function + * object that takes two arguments of the same type as the container elements, and returns true if + * the first argument is considered to go before the second in the strict weak ordering it + * defines, and false otherwise.

+ * + *

Two elements of a {@link ITreeSet} are considered equivalent if {@link key_comp} returns false + * reflexively (i.e., no matter the order in which the elements are passed as arguments).

+ * + *

In {@link ITreeSet} containers, the keys to sort the elements are the values (T) themselves, + * therefore {@link key_comp} and its sibling member function {@link value_comp} are equivalent.

+ * + * @return The comparison function. */ - second: T2; + value_comp(): (x: T, y: T) => boolean; /** - *

Construct from pair values.

+ *

Return iterator to lower bound.

* - * @param first The first value of the Pair - * @param second The second value of the Pair + *

Returns an iterator pointing to the first element in the container which is not considered to + * go before val (i.e., either it is equivalent or goes after).

+ * + *

The function uses its internal comparison object (key_comp) to determine this, returning an + * iterator to the first element for which key_comp(element,val) would return false.

+ * + *

If the {@link ITreeSet} class is instantiated with the default comparison type ({@link less}), + * the function returns an iterator to the first element that is not less than val.

+ + *

A similar member function, {@link upper_bound}, has the same behavior as {@link lower_bound}, except + * in the case that the {@link ITreeSet} contains elements equivalent to val: In this case + * {@link lower_bound} returns an iterator pointing to the first of such elements, whereas + * {@link upper_bound} returns an iterator pointing to the element following the last.

+ * + * @param val Value to compare. + * + * @return An iterator to the the first element in the container which is not considered to go before + * val, or {@link ITreeSet.end} if all elements are considered to go before val. */ - constructor(first: T1, second: T2); + lower_bound(val: T): SetIterator; /** - *

Whether a Pair is equal with the Pair.

- *

Compare each first and second value of two Pair(s) and returns whether they are equal or not.

+ *

Return iterator to upper bound.

* - *

If stored key and value in a Pair are not number or string but an object like a class or struct, - * the comparison will be executed by a member method (SomeObject)::equal_to(). If the object does not have - * the member method equal_to(), only address of pointer will be compared.

+ *

Returns an iterator pointing to the first element in the container which is considered to go after + * val.

+ + *

The function uses its internal comparison object (key_comp) to determine this, returning an + * iterator to the first element for which key_comp(val,element) would return true.

+ + *

If the {@code ITreeSet} class is instantiated with the default comparison type (less), the + * function returns an iterator to the first element that is greater than val.

* - * @param obj A Map to compare - * @return Indicates whether equal or not. + *

A similar member function, {@link lower_bound}, has the same behavior as {@link upper_bound}, except + * in the case that the {@ITreeSet} contains elements equivalent to val: In this case + * {@link lower_bound} returns an iterator pointing to the first of such elements, whereas + * {@link upper_bound} returns an iterator pointing to the element following the last.

+ * + * @param val Value to compare. + * + * @return An iterator to the the first element in the container which is considered to go after + * val, or {@link TreeSet.end end} if no elements are considered to go after val. */ - equal_to(pair: Pair): boolean; - less(pair: Pair): boolean; + upper_bound(val: T): SetIterator; + /** + *

Get range of equal elements.

+ * + *

Returns the bounds of a range that includes all the elements in the container that are equivalent + * to val.

+ * + *

If no matches are found, the range returned has a length of zero, with both iterators pointing to + * the first element that is considered to go after val according to the container's + * internal comparison object (key_comp).

+ * + *

Two elements of a multiset are considered equivalent if the container's comparison object returns + * false reflexively (i.e., no matter the order in which the elements are passed as arguments).

+ * + * @param key Value to search for. + * + * @return The function returns a {@link Pair}, whose member {@link Pair.first} is the lower bound of + * the range (the same as {@link lower_bound}), and {@link Pair.second} is the upper bound + * (the same as {@link upper_bound}). + */ + equal_range(val: T): Pair, SetIterator>; } - /** - *

Construct {@link Pair} object.

- * - *

Constructs a {@link Pair} object with its {@link Pair.first first} element set to x and its - * {@link Pair.second second} element set to y.

- * - *

The template types can be implicitly deduced from the arguments passed to {@link make_pair}.

- * - *

{@link Pair} objects can be constructed from other {@link Pair} objects containing different types, if the - * respective types are implicitly convertible.

- * - * @param x Value for member {@link Pair.first first}. - * @param y Value for member {@link Pair.second second}. - * - * @return A {@link Pair} object whose elements {@link Pair.first first} and {@link Pair.second second} are set to - * x and y respectivelly. - */ - function make_pair(x: T1, y: T2): Pair; -} -declare namespace std { - /** - *

Priority queue.

- * - *

{@link PriorityQueue Priority queues} are a type of container adaptors, specifically designed such that its - * first element is always the greatest of the elements it contains, according to some strict weak ordering - * criterion.

- * - *

This context is similar to a heap, where elements can be inserted at any moment, and only the - * max heap element can be retrieved (the one at the top in the {@link PriorityQueue priority queue}).

- * - *

{@link PriorityQueue Priority queues} are implemented as container adaptors, which are classes that - * use an encapsulated object of a specific container class as its {@link container_ underlying container}, - * providing a specific set of member functions to access its elements. Elements are popped from the "back" - * of the specific container, which is known as the top of the {@link PriorityQueue Priority queue}.

- * - *

The {@link container_ underlying container} may be any of the standard container class templates or some - * other specifically designed container class. The container shall be accessible through - * {@link IArrayIterator random access iterators} and support the following operations:

- * - *
    - *
  • empty()
  • - *
  • size()
  • - *
  • front()
  • - *
  • push_back()
  • - *
  • pop_back()
  • - *
- * - *

The standard container classes {@link Vector} and {@link Deque} fulfill these requirements. By default, if - * no container class is specified for a particular {@link PriorityQueue} class instantiation, the standard - * container {@link Vector} is used.

- * - *

Support of {@link IArrayIterator random access iterators} is required to keep a heap structure internally - * at all times. This is done automatically by the container adaptor by automatically calling the algorithm - * functions make_heap, push_heap and pop_heap when needed.

+} +declare namespace std.base { + /** + *

A red-black Tree storing {@link SetIterator SetIterators}.

* - * @param Type of the elements. + *

+ *

* - * @reference http://www.cplusplus.com/reference/queue/priority_queue/ - * @author Jeongho Nam + * @author Jeongho Nam */ - class PriorityQueue { + class AtomicTree extends XTree> { /** - *

The underlying container for implementing the priority queue.

- * - *

Following standard definition from the C++ committee, the underlying container should be one of - * {@link Vector} or {@link Deque}, however, I've adopted {@link TreeMultiSet} instead of them. Of course, - * there are proper reasons for adapting the {@link TreeMultiSet} even violating standard advice.

- * - *

Underlying container of {@link PriorityQueue} must keep a condition; the highest (or lowest) - * element must be placed on the terminal node for fast retrieval and deletion. To keep the condition with - * {@link Vector} or {@link Deque}, lots of times will only be spent for re-arranging elements. It calls - * rearrangement functions like make_heap, push_heap and pop_head for rearrangement.

- * - *

However, the {@link TreeMultiSet} container always keeps arrangment automatically without additional - * operations and it even meets full criteria of {@link PriorityQueue}. Those are the reason why I've adopted - * {@link TreeMultiSet} as the underlying container of {@link PriorityQueue}.

+ * @hidden */ - private container_; + private set_; /** - * Default Constructor. + * @hidden */ - constructor(); + private compare_; /** - * Construct from compare. - * - * @param compare A binary predicate determines order of elements. + * Default Constructor. */ - constructor(compare: (left: T, right: T) => boolean); + constructor(set: TreeSet | TreeMultiSet, compare?: (x: T, y: T) => boolean); + find(val: T): XTreeNode>; + find(it: SetIterator): XTreeNode>; /** - * Contruct from elements. - * - * @param array Elements to be contained. + * @hidden */ - constructor(array: Array); + private find_by_val(val); /** - * Contruct from elements with compare. + *

Return iterator to lower bound.

* - * @param array Elements to be contained. - * @param compare A binary predicate determines order of elements. - */ - constructor(array: Array, compare: (left: T, right: T) => boolean); - /** - * Copy Constructor. - */ - constructor(container: base.IContainer); - /** - * Copy Constructor with compare. + *

Returns an iterator pointing to the first element in the container which is not considered to + * go before val (i.e., either it is equivalent or goes after).

* - * @param container A container to be copied. - * @param compare A binary predicate determines order of elements. - */ - constructor(container: base.IContainer, compare: (left: T, right: T) => boolean); - /** - * Range Constructor. + *

The function uses its internal comparison object (key_comp) to determine this, returning an + * iterator to the first element for which key_comp(element,val) would return false.

* - * @param begin Input interator of the initial position in a sequence. - * @param end Input interator of the final position in a sequence. - */ - constructor(begin: Iterator, end: Iterator); - /** - * Range Constructor with compare. + *

If the {@link ITreeSet} class is instantiated with the default comparison type ({@link less}), + * the function returns an iterator to the first element that is not less than val.

+ + *

A similar member function, {@link upper_bound}, has the same behavior as {@link lower_bound}, except + * in the case that the {@link ITreeSet} contains elements equivalent to val: In this case + * {@link lower_bound} returns an iterator pointing to the first of such elements, whereas + * {@link upper_bound} returns an iterator pointing to the element following the last.

* - * @param begin Input interator of the initial position in a sequence. - * @param end Input interator of the final position in a sequence. - * @param compare A binary predicate determines order of elements. + * @param val Value to compare. + * + * @return An iterator to the the first element in the container which is not considered to go before + * val, or {@link ITreeSet.end} if all elements are considered to go before val. */ - constructor(begin: Iterator, end: Iterator, compare: (left: T, right: T) => boolean); + lower_bound(val: T): SetIterator; /** - *

Return size.

+ *

Return iterator to upper bound.

* - *

Returns the number of elements in the {@link PriorityQueue}.

+ *

Returns an iterator pointing to the first element in the container which is considered to go after + * val.

+ + *

The function uses its internal comparison object (key_comp) to determine this, returning an + * iterator to the first element for which key_comp(val,element) would return true.

+ + *

If the {@code ITreeSet} class is instantiated with the default comparison type (less), the + * function returns an iterator to the first element that is greater than val.

* - *

This member function effectively calls member {@link IArray.size size} of the - * {@link container_ underlying container} object.

+ *

A similar member function, {@link lower_bound}, has the same behavior as {@link upper_bound}, except + * in the case that the {@ITreeSet} contains elements equivalent to val: In this case + * {@link lower_bound} returns an iterator pointing to the first of such elements, whereas + * {@link upper_bound} returns an iterator pointing to the element following the last.

* - * @return The number of elements in the underlying + * @param val Value to compare. + * + * @return An iterator to the the first element in the container which is considered to go after + * val, or {@link TreeSet.end end} if no elements are considered to go after val. */ - size(): number; + upper_bound(val: T): SetIterator; /** - *

Test whether container is empty.

+ *

Get range of equal elements.

* - *

Returns whether the {@link PriorityQueue} is empty: i.e. whether its {@link size} is zero.

+ *

Returns the bounds of a range that includes all the elements in the container that are equivalent + * to val.

* - *

This member function effectively calls member {@link IARray.empty empty} of the - * {@link container_ underlying container} object.

+ *

If no matches are found, the range returned has a length of zero, with both iterators pointing to + * the first element that is considered to go after val according to the container's + * internal comparison object (key_comp).

+ * + *

Two elements of a multiset are considered equivalent if the container's comparison object returns + * false reflexively (i.e., no matter the order in which the elements are passed as arguments).

+ * + * @param key Value to search for. + * + * @return The function returns a {@link Pair}, whose member {@link Pair.first} is the lower bound of + * the range (the same as {@link lower_bound}), and {@link Pair.second} is the upper bound + * (the same as {@link upper_bound}). */ - empty(): boolean; + equal_range(val: T): Pair, SetIterator>; /** - *

Access top element.

+ *

Return comparison function.

* - *

Returns a constant reference to the top element in the {@link PriorityQueue}.

+ *

Returns a copy of the comparison function used by the container.

* - *

The top element is the element that compares higher in the {@link PriorityQueue}, and the next that is - * removed from the container when {@link PriorityQueue.pop} is called.

+ *

By default, this is a {@link less} object, which returns the same as operator<.

* - *

This member function effectively calls member {@link IArray.front front} of the - * {@link container_ underlying container} object.

+ *

This object determines the order of the elements in the container: it is a function pointer or a function + * object that takes two arguments of the same type as the container elements, and returns true if + * the first argument is considered to go before the second in the strict weak ordering it + * defines, and false otherwise.

* - * @return A reference to the top element in the {@link PriorityQueue}. + *

Two elements of a {@link ITreeSet} are considered equivalent if {@link key_comp} returns false + * reflexively (i.e., no matter the order in which the elements are passed as arguments).

+ * + *

In {@link ITreeSet} containers, the keys to sort the elements are the values (T) themselves, + * therefore {@link key_comp} and its sibling member function {@link value_comp} are equivalent.

+ * + * @return The comparison function. */ - top(): T; + key_comp(): (x: T, y: T) => boolean; /** - *

Insert element.

+ *

Return comparison function.

* - *

Inserts a new element in the {@link PriorityQueue}. The content of this new element is initialized to - * val. + *

Returns a copy of the comparison function used by the container.

* - *

This member function effectively calls the member function {@link IArray.push_back push_back} of the - * {@link container_ underlying container} object, and then reorders it to its location in the heap by calling - * the push_heap algorithm on the range that includes all the elements of the

+ *

By default, this is a {@link less} object, which returns the same as operator<.

* - * @param val Value to which the inserted element is initialized. - */ - push(val: T): void; - /** - *

Remove top element.

+ *

This object determines the order of the elements in the container: it is a function pointer or a function + * object that takes two arguments of the same type as the container elements, and returns true if + * the first argument is considered to go before the second in the strict weak ordering it + * defines, and false otherwise.

* - *

Removes the element on top of the {@link PriorityQueue}, effectively reducing its {@link size} by one. - * The element removed is the one with the highest (or lowest) value.

+ *

Two elements of a {@link ITreeSet} are considered equivalent if {@link key_comp} returns false + * reflexively (i.e., no matter the order in which the elements are passed as arguments).

* - *

The value of this element can be retrieved before being popped by calling member - * {@link PriorityQueue.top}.

+ *

In {@link ITreeSet} containers, the keys to sort the elements are the values (T) themselves, + * therefore {@link key_comp} and its sibling member function {@link value_comp} are equivalent.

* - *

This member function effectively calls the pop_heap algorithm to keep the heap property of - * {@link PriorityQueue PriorityQueues} and then calls the member function {@link IArray.pop_back pop_back} of - * the {@link container_ underlying container} object to remove the element.

+ * @return The comparison function. */ - pop(): void; + value_comp(): (x: T, y: T) => boolean; /** - *

Swap contents.

- * - *

Exchanges the contents of the container adaptor by those of obj, swapping both the - * {@link container_ underlying container} value and their comparison function using the corresponding - * {@link std.swap swap} non-member functions (unqualified).

- * - *

This member function has a noexcept specifier that matches the combined noexcept of the - * {@link IArray.swap swap} operations on the {@link container_ underlying container} and the comparison - * functions.

+ * @inheritdoc + */ + is_equal_to(left: SetIterator, right: SetIterator): boolean; + /** + * @inheritdoc + */ + is_less(left: SetIterator, right: SetIterator): boolean; + } +} +declare namespace std.base { + /** + *

A node in an XTree.

+ * + * @param Type of elements. + * + * @inventor Rudolf Bayer + * @author Migrated by Jeongho Nam + */ + class XTreeNode { + /** + * Parent of the node. + */ + parent: XTreeNode; + /** + * Left child in the node. + */ + left: XTreeNode; + /** + * Right child in the node. + */ + right: XTreeNode; + /** + * Value stored in the node. + */ + value: T; + /** + * Color of the node. + */ + color: Color; + /** + * Construct from value and color of node. * - * @param obj {@link PriorityQueue} container adaptor of the same type (i.e., instantiated with the same - * template parameters, T). Sizes may differ. + * @param value Value to be stored in. + * @param color Color of the node, red or black. */ - swap(obj: PriorityQueue): void; + constructor(value: T, color: Color); + /** + * Get grand-parent. + */ + grand_parent: XTreeNode; + /** + * Get sibling, opposite side node in same parent. + */ + sibling: XTreeNode; + /** + * Get uncle, parent's sibling. + */ + uncle: XTreeNode; } } diff --git a/lib/typescript-stl.js b/lib/typescript-stl.js index bd602349..d13849c2 100644 --- a/lib/typescript-stl.js +++ b/lib/typescript-stl.js @@ -1869,52 +1869,6 @@ var std; })(std || (std = {})); /// var std; -(function (std) { - var base; - (function (base) { - /** - *

Static class holding enumeration codes of color of Red-black tree.

- * - *

Color codes imposed to nodes of RB-Tree are following those rules:

- * - *
    - *
  1. A node is either red or black.
  2. - *
  3. The root is black. This rule is sometimes omitted. Since the root can - * always be changed from red to black, but not - * necessarily vice versa, this rule has little effect on analysis.
  4. - *
  5. All leaves (NIL; null) are black.
  6. - *
  7. If a node is red, then both its children are - * black.
  8. - *
  9. Every path from a given node to any of its descendant NIL nodes contains the same number of - * black nodes. Some definitions: the number of - * black nodes from the root to a node is the node's - * black depth; the uniform number of black - * nodes in all paths from root to the leaves is called the black-height of - * the red-black tree.
  10. - *
- * - * @author Migrated by Jeongho Nam - */ - (function (Color) { - /** - *

Code of color black.

- * - *
    - *
  • Those are clearly black: root, leaf nodes or children nodes of red.
  • - *
  • Every path from a given nodes containes the same number of black nodes exclude NIL(s).
  • - *
- */ - Color[Color["BLACK"] = 0] = "BLACK"; - /** - *

Code of color red.

- */ - Color[Color["RED"] = 1] = "RED"; - })(base.Color || (base.Color = {})); - var Color = base.Color; - })(base = std.base || (std.base = {})); -})(std || (std = {})); -/// -var std; (function (std) { var base; (function (base) { @@ -1978,507 +1932,202 @@ var std; base.Container = Container; })(base = std.base || (std.base = {})); })(std || (std = {})); -/// +/// +// Iterator definitions. +// +// @reference http://www.cplusplus.com/reference/iterator +// @author Jeongho Nam var std; (function (std) { - var base; - (function (base) { + /** + *

Bi-directional iterator.

+ * + *

{@link Iterator Bidirectional iterators} are iterators that can be used to access the sequence of elements + * in a range in both directions (towards the end and towards the beginning).

+ * + *

All {@link IArrayIterator random-access iterators} are also valid {@link Iterrator bidirectional iterators}. + *

+ * + *

There is not a single type of {@link Iterator bidirectional iterator}: {@link IContainer Each container} + * may define its own specific iterator type able to iterate through it and access its elements.

+ * + *

+ * + *

+ * + * @reference http://www.cplusplus.com/reference/iterator/BidirectionalIterator + * @author Jeongho Nam + */ + var Iterator = (function () { + /* --------------------------------------------------------- + CONSTRUCTORS + --------------------------------------------------------- */ /** - *

An abstract error instance.

+ * Construct from the source {@link IContainer container}. * - *

{@link ErrorInstance} is an abstract class of {@link ErrorCode} and {@link ErrorCondition} - * holding an error instance's identifier {@link value}, associated with a {@link category}.

+ * @param source The source + */ + function Iterator(source) { + this.source_ = source; + } + /** + * Advances the {@link Iterator} by n element positions. * - *

The operating system and other low-level applications and libraries generate numerical error codes to - * represent possible results. These numerical values may carry essential information for a specific platform, - * but be non-portable from one platform to another.

+ * @param n Number of element positions to advance. + * @return An advanced iterator. + */ + Iterator.prototype.advance = function (n) { + var it = this; + var i; + if (n >= 0) { + for (i = 0; i < n; i++) + if (it.equal_to(this.source_.end())) + return this.source_.end(); + else + it = it.next(); + } + else { + n = n * -1; + for (i = 0; i < n; i++) + if (it.equal_to(this.source_.end())) + return this.source_.end(); + else + it = it.prev(); + } + return it; + }; + /* --------------------------------------------------------- + ACCESSORS + --------------------------------------------------------- */ + /** + * Get source + */ + Iterator.prototype.get_source = function () { + return this.source_; + }; + /** + *

Whether an iterator is equal with the iterator.

* - *

Objects of this class associate such numerical codes to {@link ErrorCategory error categories}, - * so that they can be interpreted when needed as more abstract (and portable) - * {@link ErrorCondition error conditions}.

+ *

Compare two iterators and returns whether they are equal or not.

* - *

- *

+ *

Note

+ *

Iterator's equal_to() only compare souce container and index number.

* - * @author Jeongho Nam + *

Although elements in a pair, key and value are equal_to, if the source map or + * index number is different, then the {@link equal_to equal_to()} will return false. If you want to + * compare the elements of a pair, compare them directly by yourself.

+ * + * @param obj An iterator to compare + * @return Indicates whether equal or not. */ - var ErrorInstance = (function () { - function ErrorInstance(val, category) { - if (val === void 0) { val = 0; } - if (category === void 0) { category = null; } - this.assign(val, category); - } - /** - *

Assign error instance.

- * - *

Assigns the {@link ErrorCode} object a value of val associated with the {@link ErrorCategory}.

- * - * @param val A numerical value identifying an error instance. - * @param category A reference to an {@link ErrorCategory} object. - */ - ErrorInstance.prototype.assign = function (val, category) { - this.category_ = category; - this.value_ = val; - }; + Iterator.prototype.equal_to = function (obj) { + return this.source_ == obj.source_; + }; + Object.defineProperty(Iterator.prototype, "value", { /** - *

Clear error instance.

+ *

Get value of the iterator is pointing.

* - *

Clears the value in the {@link ErrorCode} object so that it is set to a value of 0 of the - * {@link ErrorCategory.systemCategory ErrorCategory.systemCategory()} (indicating no error).

+ * @return A value of the iterator. */ - ErrorInstance.prototype.clear = function () { - this.value_ = 0; - }; + get: function () { + throw new std.LogicError("Have to be overriden."); + }, + enumerable: true, + configurable: true + }); + return Iterator; + }()); + std.Iterator = Iterator; +})(std || (std = {})); +var std; +(function (std) { + /** + *

This class reverses the direction in which a bidirectional or random-access iterator iterates through a range. + *

+ * + *

A copy of the original iterator (the {@link Iterator base iterator}) is kept internally and used to reflect + * the operations performed on the {@link ReverseIterator}: whenever the {@link ReverseIterator} is incremented, its + * {@link Iterator base iterator} is decreased, and vice versa. A copy of the {@link Iterator base iterator} with the + * current state can be obtained at any time by calling member {@link base}.

+ * + *

Notice however that when an iterator is reversed, the reversed version does not point to the same element in + * the range, but to the one preceding it. This is so, in order to arrange for the past-the-end element of a + * range: An iterator pointing to a past-the-end element in a range, when reversed, is pointing to the last element + * (not past it) of the range (this would be the first element of the reversed range). And if an iterator to the + * first element in a range is reversed, the reversed iterator points to the element before the first element (this + * would be the past-the-end element of the reversed range).

+ * + *

+ * + *

+ * + * @reference http://www.cplusplus.com/reference/iterator/reverse_iterator + * @author Jeongho Nam + */ + var ReverseIterator = (function (_super) { + __extends(ReverseIterator, _super); + /* --------------------------------------------------------- + CONSTRUCTORS + --------------------------------------------------------- */ + /** + * Construct from base iterator. + * + * @param base A reference of the base iterator, which iterates in the opposite direction. + */ + function ReverseIterator(base) { + if (base == null) + _super.call(this, null); + else { + _super.call(this, base.get_source()); + this.base_ = base.prev(); + } + } + /** + *

Return base iterator.

+ * + *

Return a reference of the base iteraotr.

+ * + *

The base iterator is an iterator of the same type as the one used to construct the {@link ReverseIterator}, + * but pointing to the element next to the one the {@link ReverseIterator} is currently pointing to + * (a {@link ReverseIterator} has always an offset of -1 with respect to its base iterator). + * + * @return A reference of the base iterator, which iterates in the opposite direction. + */ + ReverseIterator.prototype.base = function () { + return this.base_.next(); + }; + Object.defineProperty(ReverseIterator.prototype, "value", { /* --------------------------------------------------------- ACCESSORS --------------------------------------------------------- */ /** - *

Get category.

- * - *

Returns a reference to the {@link ErrorCategory} associated with the {@link ErrorCode} object.

- * - * @return A reference to a non-copyable object of a type derived from {@link ErrorCategory}. - */ - ErrorInstance.prototype.category = function () { - return this.category_; - }; - /** - *

Error value.

- * - *

Returns the error value associated with the {@link ErrorCode} object.

+ *

Get value of the iterator is pointing.

* - * @return The error value. + * @return A value of the reverse iterator. */ - ErrorInstance.prototype.value = function () { - return this.value_; - }; - /** - *

Get message.

- * - *

Returns the message associated with the error instance.

- * - *

Error messages are defined by the {@link category} the error instance belongs to.

- * - *

This function returns the same as if the following member was called:

- * - *

category().message(value())

- * - * @return A string object with the message associated with the {@link ErrorCode}. - */ - ErrorInstance.prototype.message = function () { - if (this.category_ == null || this.value_ == 0) - return ""; - else - return this.category_.message(this.value_); - }; - /** - *

Default error condition.

- * - *

Returns the default {@link ErrorCondition}object associated with the {@link ErrorCode} object.

- * - *

This function returns the same as if the following member was called:

- * - *

category().default_error_condition(value())

- * - *

{@link ErrorCategory.default_error_condition ErrorCategory.default_error_condition()} - * is a virtual member function, that can operate differently for each category.

- * - * @return An {@link ErrorCondition}object that corresponds to the {@link ErrorCode} object. - */ - ErrorInstance.prototype.default_error_condition = function () { - if (this.category_ == null || this.value_ == 0) - return null; - else - return this.category_.default_error_condition(this.value_); - }; - /* --------------------------------------------------------- - OPERATORS - --------------------------------------------------------- */ - /** - *

Convert to bool.

- * - *

Returns whether the error instance has a numerical {@link value} other than 0.

- * - *

If it is zero (which is generally used to represent no error), the function returns false, otherwise it returns true.

- * - * @return true if the error's numerical value is not zero. - * false otherwise. - */ - ErrorInstance.prototype.to_bool = function () { - return this.value_ != 0; - }; - return ErrorInstance; - }()); - base.ErrorInstance = ErrorInstance; - })(base = std.base || (std.base = {})); -})(std || (std = {})); -/// -var std; -(function (std) { - var base; - (function (base) { - (function (Hash) { - Hash[Hash["MIN_SIZE"] = 10] = "MIN_SIZE"; - Hash[Hash["RATIO"] = 1] = "RATIO"; - Hash[Hash["MAX_RATIO"] = 2] = "MAX_RATIO"; - })(base.Hash || (base.Hash = {})); - var Hash = base.Hash; + get: function () { + return this.base_.value; + }, + enumerable: true, + configurable: true + }); + /* --------------------------------------------------------- + MOVERS + --------------------------------------------------------- */ /** - *

Hask buckets.

- * - * @author Jeongho Nam + * @inheritdoc */ - var HashBuckets = (function () { - /* --------------------------------------------------------- - CONSTRUCTORS - --------------------------------------------------------- */ - /** - * Default Constructor. - */ - function HashBuckets() { - this.clear(); - } - /** - *

Reconstruction of hash table.

- * - *

All the elements in the hash buckets are rearranged according to their hash value into the new set of - * buckets. This may alter the order of iteration of elements within the container.

- * - *

Notice that {@link rehash rehashes} are automatically performed whenever its number of elements is going - * to greater than its own {@link capacity}.

- * - * @param size Number of bucket size to rehash. - */ - HashBuckets.prototype.rehash = function (size) { - if (size < Hash.MIN_SIZE) - size = Hash.MIN_SIZE; - var prev_matrix = this.buckets_; - this.buckets_ = new std.Vector(); - for (var i = 0; i < size; i++) - this.buckets_.push_back(new std.Vector()); - for (var i = 0; i < prev_matrix.size(); i++) - for (var j = 0; j < prev_matrix.at(i).size(); j++) { - var val = prev_matrix.at(i).at(j); - var bucket = this.buckets_.at(this.hash_index(val)); - bucket.push_back(val); - this.item_size_++; - } - }; - HashBuckets.prototype.clear = function () { - this.buckets_ = new std.Vector(); - this.item_size_ = 0; - for (var i = 0; i < Hash.MIN_SIZE; i++) - this.buckets_.push_back(new std.Vector()); - }; - /* --------------------------------------------------------- - ACCESSORS - --------------------------------------------------------- */ - HashBuckets.prototype.size = function () { - return this.buckets_.size(); - }; - HashBuckets.prototype.item_size = function () { - return this.item_size_; - }; - HashBuckets.prototype.capacity = function () { - return this.buckets_.size() * Hash.MAX_RATIO; - }; - HashBuckets.prototype.at = function (index) { - return this.buckets_.at(index); - }; - HashBuckets.prototype.hash_index = function (val) { - return std.hash(val) % this.buckets_.size(); - }; - /* --------------------------------------------------------- - ELEMENTS I/O - --------------------------------------------------------- */ - HashBuckets.prototype.insert = function (val) { - this.buckets_.at(this.hash_index(val)).push_back(val); - if (++this.item_size_ > this.capacity()) - this.rehash(this.item_size_ * Hash.RATIO); - }; - HashBuckets.prototype.erase = function (val) { - var bucket = this.buckets_.at(this.hash_index(val)); - for (var i = 0; i < bucket.size(); i++) - if (bucket.at(i) == val) { - bucket.splice(i, 1); - this.item_size_--; - break; - } - }; - return HashBuckets; - }()); - base.HashBuckets = HashBuckets; - })(base = std.base || (std.base = {})); -})(std || (std = {})); -/// -/// -var std; -(function (std) { - var base; - (function (base) { + ReverseIterator.prototype.prev = function () { + return this.create_neighbor(this.base().next()); + }; /** - *

Hash buckets storing {@link MapIterator MapIterators}.

- * - *

- * - *

- * - * @author Jeongho Nam + * @inheritdoc */ - var MapHashBuckets = (function (_super) { - __extends(MapHashBuckets, _super); - function MapHashBuckets(map) { - _super.call(this); - this.map = map; - } - MapHashBuckets.prototype.find = function (key) { - var index = std.hash(key) % this.size(); - var bucket = this.at(index); - for (var i = 0; i < bucket.size(); i++) - if (std.equal_to(bucket.at(i).first, key)) - return bucket.at(i); - return this.map.end(); - }; - return MapHashBuckets; - }(base.HashBuckets)); - base.MapHashBuckets = MapHashBuckets; - })(base = std.base || (std.base = {})); -})(std || (std = {})); -/// -/// -var std; -(function (std) { - var base; - (function (base) { + ReverseIterator.prototype.next = function () { + return this.create_neighbor(this.base().prev()); + }; /** - *

Hash buckets storing {@link SetIterator SetIterators}.

- * - *

- * - *

- * - * @author Jeongho Nam - */ - var SetHashBuckets = (function (_super) { - __extends(SetHashBuckets, _super); - function SetHashBuckets(set) { - _super.call(this); - this.set = set; - } - SetHashBuckets.prototype.find = function (val) { - var index = std.hash(val) % this.size(); - var bucket = this.at(index); - for (var i = 0; i < bucket.size(); i++) - if (std.equal_to(bucket.at(i).value, val)) - return bucket.at(i); - return this.set.end(); - }; - return SetHashBuckets; - }(base.HashBuckets)); - base.SetHashBuckets = SetHashBuckets; - })(base = std.base || (std.base = {})); -})(std || (std = {})); -/// -/// -/// -/// -/// -/// -// Iterator definitions. -// -// @reference http://www.cplusplus.com/reference/iterator -// @author Jeongho Nam -var std; -(function (std) { - /** - *

Bi-directional iterator.

- * - *

{@link Iterator Bidirectional iterators} are iterators that can be used to access the sequence of elements - * in a range in both directions (towards the end and towards the beginning).

- * - *

All {@link IArrayIterator random-access iterators} are also valid {@link Iterrator bidirectional iterators}. - *

- * - *

There is not a single type of {@link Iterator bidirectional iterator}: {@link IContainer Each container} - * may define its own specific iterator type able to iterate through it and access its elements.

- * - *

- * - *

- * - * @reference http://www.cplusplus.com/reference/iterator/BidirectionalIterator - * @author Jeongho Nam - */ - var Iterator = (function () { - /* --------------------------------------------------------- - CONSTRUCTORS - --------------------------------------------------------- */ - /** - * Construct from the source {@link IContainer container}. - * - * @param source The source - */ - function Iterator(source) { - this.source_ = source; - } - /** - * Advances the {@link Iterator} by n element positions. - * - * @param n Number of element positions to advance. - * @return An advanced iterator. - */ - Iterator.prototype.advance = function (n) { - var it = this; - var i; - if (n >= 0) { - for (i = 0; i < n; i++) - if (it.equal_to(this.source_.end())) - return this.source_.end(); - else - it = it.next(); - } - else { - n = n * -1; - for (i = 0; i < n; i++) - if (it.equal_to(this.source_.end())) - return this.source_.end(); - else - it = it.prev(); - } - return it; - }; - /* --------------------------------------------------------- - ACCESSORS - --------------------------------------------------------- */ - /** - * Get source - */ - Iterator.prototype.get_source = function () { - return this.source_; - }; - /** - *

Whether an iterator is equal with the iterator.

- * - *

Compare two iterators and returns whether they are equal or not.

- * - *

Note

- *

Iterator's equal_to() only compare souce container and index number.

- * - *

Although elements in a pair, key and value are equal_to, if the source map or - * index number is different, then the {@link equal_to equal_to()} will return false. If you want to - * compare the elements of a pair, compare them directly by yourself.

- * - * @param obj An iterator to compare - * @return Indicates whether equal or not. - */ - Iterator.prototype.equal_to = function (obj) { - return this.source_ == obj.source_; - }; - Object.defineProperty(Iterator.prototype, "value", { - /** - *

Get value of the iterator is pointing.

- * - * @return A value of the iterator. - */ - get: function () { - throw new std.LogicError("Have to be overriden."); - }, - enumerable: true, - configurable: true - }); - return Iterator; - }()); - std.Iterator = Iterator; -})(std || (std = {})); -var std; -(function (std) { - /** - *

This class reverses the direction in which a bidirectional or random-access iterator iterates through a range. - *

- * - *

A copy of the original iterator (the {@link Iterator base iterator}) is kept internally and used to reflect - * the operations performed on the {@link ReverseIterator}: whenever the {@link ReverseIterator} is incremented, its - * {@link Iterator base iterator} is decreased, and vice versa. A copy of the {@link Iterator base iterator} with the - * current state can be obtained at any time by calling member {@link base}.

- * - *

Notice however that when an iterator is reversed, the reversed version does not point to the same element in - * the range, but to the one preceding it. This is so, in order to arrange for the past-the-end element of a - * range: An iterator pointing to a past-the-end element in a range, when reversed, is pointing to the last element - * (not past it) of the range (this would be the first element of the reversed range). And if an iterator to the - * first element in a range is reversed, the reversed iterator points to the element before the first element (this - * would be the past-the-end element of the reversed range).

- * - *

- * - *

- * - * @reference http://www.cplusplus.com/reference/iterator/reverse_iterator - * @author Jeongho Nam - */ - var ReverseIterator = (function (_super) { - __extends(ReverseIterator, _super); - /* --------------------------------------------------------- - CONSTRUCTORS - --------------------------------------------------------- */ - /** - * Construct from base iterator. - * - * @param base A reference of the base iterator, which iterates in the opposite direction. - */ - function ReverseIterator(base) { - if (base == null) - _super.call(this, null); - else { - _super.call(this, base.get_source()); - this.base_ = base.prev(); - } - } - /** - *

Return base iterator.

- * - *

Return a reference of the base iteraotr.

- * - *

The base iterator is an iterator of the same type as the one used to construct the {@link ReverseIterator}, - * but pointing to the element next to the one the {@link ReverseIterator} is currently pointing to - * (a {@link ReverseIterator} has always an offset of -1 with respect to its base iterator). - * - * @return A reference of the base iterator, which iterates in the opposite direction. - */ - ReverseIterator.prototype.base = function () { - return this.base_.next(); - }; - Object.defineProperty(ReverseIterator.prototype, "value", { - /* --------------------------------------------------------- - ACCESSORS - --------------------------------------------------------- */ - /** - *

Get value of the iterator is pointing.

- * - * @return A value of the reverse iterator. - */ - get: function () { - return this.base_.value; - }, - enumerable: true, - configurable: true - }); - /* --------------------------------------------------------- - MOVERS - --------------------------------------------------------- */ - /** - * @inheritdoc - */ - ReverseIterator.prototype.prev = function () { - return this.create_neighbor(this.base().next()); - }; - /** - * @inheritdoc - */ - ReverseIterator.prototype.next = function () { - return this.create_neighbor(this.base().prev()); - }; - /** - * @inheritdoc + * @inheritdoc */ ReverseIterator.prototype.advance = function (n) { return this.create_neighbor(this.base().advance(-n)); @@ -2591,4352 +2240,2730 @@ var std; } std.end = end; })(std || (std = {})); -/// -/// -/// +/// +/// +/// var std; (function (std) { - var base; - (function (base) { - /** - *

An abstract map.

- * - *

{@link MapContainer MapContainers} are associative containers that store elements formed by a combination - * of a key value (Key) and a mapped value (T), and which allows for fast retrieval - * of individual elements based on their keys.

- * - *

In a {@link MapContainer}, the key values are generally used to identify the elements, while the - * mapped values store the content associated to this key. The types of key and - * mapped value may differ, and are grouped together in member type value_type, which is a - * {@link Pair} type combining both:

- * - *

typedef pair value_type;

- * - *

{@link MapContainer} stores elements, keeps sequence and enables indexing by inserting elements into a - * {@link List} and registering {@link ListIterator iterators} of the {@link data_ list container} to an index - * table like {@link RBTree tree} or {@link HashBuckets hash-table}.

- * - *

- *

- * - *

Container properties

- *
- *
Associative
- *
- * Elements in associative containers are referenced by their key and not by their absolute position - * in the container. - *
- * - *
Map
- *
- * Each element associates a key to a mapped value: - * Keys are meant to identify the elements whose main content is the mapped value. - *
- *
- * - * @param Type of the keys. Each element in a map is identified by its key value. - * @param Type of the mapped value. Each element in a map stores some data as its mapped value. - * - * @author Jeongho Nam - */ - var MapContainer = (function (_super) { - __extends(MapContainer, _super); - /* --------------------------------------------------------- - CONSTURCTORS - --------------------------------------------------------- */ - /** - * Default Constructor. - */ - function MapContainer() { - _super.call(this); - this.data_ = new std.List(); - } - /** - * @inheritdoc - */ - MapContainer.prototype.assign = function (first, last) { - // INSERT - this.clear(); - this.insert(first, last); - }; - /** - * @inheritdoc - */ - MapContainer.prototype.clear = function () { - // TO BE ABSTRACT - this.data_.clear(); - }; - /** - *

Return iterator to beginning.

- * - *

Returns an iterator referring the first element in the

- * - *

Note

- *

If the container is {@link empty}, the returned iterator is same with {@link end end()}.

- * - * @return An iterator to the first element in the The iterator containes the first element's value. - */ - MapContainer.prototype.begin = function () { - return new std.MapIterator(this, this.data_.begin()); - }; - /** - *

Return iterator to end.

- *

Returns an iterator referring to the past-the-end element in the

- * - *

The past-the-end element is the theoretical element that would follow the last element in the - * It does not point to any element, and thus shall not be dereferenced.

- * - *

Because the ranges used by functions of the container do not include the element reference by their - * closing iterator, this function is often used in combination with {@link MapContainer}.{@link begin} to - * specify a range including all the elements in the

- * - *

Note

- *

Returned iterator from {@link MapContainer}.{@link end} does not refer any element. Trying to accessing - * element by the iterator will cause throwing exception ({@link OutOfRange}).

- * - *

If the container is {@link empty}, this function returns the same as {@link begin}.

- * - * @return An iterator to the end element in the - */ - MapContainer.prototype.end = function () { - return new std.MapIterator(this, this.data_.end()); - }; - /** - *

Return {@link MapReverseIterator reverse iterator} to reverse beginning.

- * - *

Returns a {@link MapReverseIterator reverse iterator} pointing to the last element in the container - * (i.e., its reverse beginning).

- * - * {@link MapReverseIterator Reverse iterators} iterate backwards: increasing them moves them towards the - * beginning of the container.

- * - *

{@link rbegin} points to the element preceding the one that would be pointed to by member {@link end}. - *

- * - * @return A {@link MapReverseIterator reverse iterator} to the reverse beginning of the sequence - * - */ - MapContainer.prototype.rbegin = function () { - return new std.MapReverseIterator(this.end()); - }; - /** - *

Return {@link MapReverseIterator reverse iterator} to reverse end.

- * - *

Returns a {@link MapReverseIterator reverse iterator} pointing to the theoretical element right before - * the first element in the {@link MapContainer map container} (which is considered its reverse end). - *

- * - *

The range between {@link MapContainer}.{@link rbegin} and {@link MapContainer}.{@link rend} contains - * all the elements of the container (in reverse order).

- * - * @return A {@link MapReverseIterator reverse iterator} to the reverse end of the sequence - */ - MapContainer.prototype.rend = function () { - return new std.MapReverseIterator(this.begin()); - }; - /* --------------------------------------------------------- - ELEMENTS - --------------------------------------------------------- */ - /** - *

Whether have the item or not.

- * - *

Indicates whether a map has an item having the specified identifier.

- * - * @param key Key value of the element whose mapped value is accessed. - * - * @return Whether the map has an item having the specified identifier. - */ - MapContainer.prototype.has = function (key) { - return !this.find(key).equal_to(this.end()); - }; - /** - * Return the number of elements in the map. - */ - MapContainer.prototype.size = function () { - return this.data_.size(); - }; - MapContainer.prototype.push = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i - 0] = arguments[_i]; - } - // TO BE ABSTRACT - for (var i = 0; i < args.length; i++) - if (args[i] instanceof std.Pair) - this._Insert_by_pair(args[i]); - else if (args[i] instanceof Array) - this.insert_by_tuple(args[i]); - return this.size(); - }; - MapContainer.prototype.emplace_hint = function (hint) { - var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; - } - if (args.length == 1) - return this.insert(hint, args[0]); - else - return this.insert(hint, std.make_pair(args[0], args[1])); - }; - MapContainer.prototype.insert = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i - 0] = arguments[_i]; - } - if (args.length == 1 && args[0] instanceof std.Pair) { - return this._Insert_by_pair(args[0]); - } - else if (args.length == 1 && args[0] instanceof Array) { - return this.insert_by_tuple(args[0]); - } - else if (args.length == 2 && args[0] instanceof std.Iterator && args[1] instanceof std.Iterator) { - return this._Insert_by_range(args[0], args[1]); - } - else { - var ret = void 0; - var is_reverse_iterator = false; - // REVERSE_ITERATOR TO ITERATOR - if (args[0] instanceof std.MapReverseIterator) { - is_reverse_iterator = true; - args[0] = args[0].base().prev(); - } - // INSERT AN ELEMENT - if (args[1] instanceof std.Pair) - ret = this._Insert_by_hint(args[0], args[1]); - else - ret = this.insert_by_hint_with_tuple(args[0], args[1]); - // RETURN BRANCHES - if (is_reverse_iterator == true) - return new std.MapReverseIterator(ret.next()); - else - return ret; - } - }; + /** + *

Double ended queue.

+ * + *

{@link Deque} (usually pronounced like "deck") is an irregular acronym of + * double-ended queue. Double-ended queues are sequence containers with dynamic sizes that can be + * expanded or contracted on both ends (either its front or its back).

+ * + *

Specific libraries may implement deques in different ways, generally as some form of dynamic array. But in any + * case, they allow for the individual elements to be accessed directly through random access iterators, with storage + * handled automatically by expanding and contracting the container as needed.

+ * + *

Therefore, they provide a functionality similar to vectors, but with efficient insertion and deletion of + * elements also at the beginning of the sequence, and not only at its end. But, unlike {@link Vector Vectors}, + * {@link Deque Deques} are not guaranteed to store all its elements in contiguous storage locations: accessing + * elements in a deque by offsetting a pointer to another element causes undefined behavior.

+ * + *

Both {@link Vector}s and {@link Deque}s provide a very similar interface and can be used for similar purposes, + * but internally both work in quite different ways: While {@link Vector}s use a single array that needs to be + * occasionally reallocated for growth, the elements of a {@link Deque} can be scattered in different chunks of + * storage, with the container keeping the necessary information internally to provide direct access to any of its + * elements in constant time and with a uniform sequential interface (through iterators). Therefore, + * {@link Deque Deques} are a little more complex internally than {@link Vector}s, but this allows them to grow more + * efficiently under certain circumstances, especially with very long sequences, where reallocations become more + * expensive.

+ * + *

For operations that involve frequent insertion or removals of elements at positions other than the beginning or + * the end, {@link Deque Deques} perform worse and have less consistent iterators and references than + * {@link List Lists}.

+ * + *

+ * + *

+ * + *

Container properties

+ *
+ *
Sequence
+ *
Elements in sequence containers are ordered in a strict linear sequence. Individual elements + * are accessed by their position in this sequence.
+ * + *
Dynamic array
+ *
Generally implemented as a dynamic array, it allows direct access to any element in the + * sequence and provides relatively fast addition/removal of elements at the beginning or the end + * of the sequence.
+ *
+ * + * @param Type of the elements. + * + * @reference http://www.cplusplus.com/reference/deque/deque/ + * @author Jeongho Nam + */ + var Deque = (function (_super) { + __extends(Deque, _super); + function Deque() { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i - 0] = arguments[_i]; + } + _super.call(this); + if (args.length == 0) { + this.clear(); + } + if (args.length == 1 && args[0] instanceof Array) { + var array = args[0]; + this.clear(); + this.push.apply(this, array); + } + else if (args.length == 1 && args[0] instanceof Deque) { + var container = args[0]; + this.assign(container.begin(), container.end()); + } + else if (args.length == 2 && + args[0] instanceof std.Iterator && args[1] instanceof std.Iterator) { + var begin_1 = args[0]; + var end_1 = args[1]; + this.assign(begin_1, end_1); + } + } + Object.defineProperty(Deque, "ROW", { + /// + // Row size of the {@link matrix_ matrix} which contains elements. + // + // Note that the {@link ROW} affects on time complexity of accessing and inserting element. + // Accessing element is {@link ROW} times slower than ordinary {@link Vector} and inserting element + // in middle position is {@link ROW} times faster than ordinary {@link Vector}. + // + // When the {@link ROW} returns 8, time complexity of accessing element is O(8) and inserting + // element in middle position is O(N/8). ({@link Vector}'s time complexity of accessement is O(1) + // and inserting element is O(N)). /** * @hidden */ - MapContainer.prototype.insert_by_tuple = function (tuple) { - return this._Insert_by_pair(new std.Pair(tuple[0], tuple[1])); - }; + get: function () { return 8; }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Deque, "MIN_CAPACITY", { + /// + // Minimum {@link capacity}. + // + // Although a {@link Deque} has few elements, even no element is belonged to, the {@link Deque} + // keeps the minimum {@link capacity} at least. /** * @hidden */ - MapContainer.prototype.insert_by_hint_with_tuple = function (hint, tuple) { - return this._Insert_by_hint(hint, std.make_pair(tuple[0], tuple[1])); - }; - MapContainer.prototype.erase = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i - 0] = arguments[_i]; + get: function () { return 100; }, + enumerable: true, + configurable: true + }); + // Get column size; {@link capacity_ capacity} / {@link ROW row}. + /** + * @hidden + */ + Deque.prototype.get_col_size = function () { + return Math.floor(this.capacity_ / Deque.ROW); + }; + Deque.prototype.assign = function (first, second) { + // CLEAR PREVIOUS CONTENTS + this.clear(); + if (first instanceof std.Iterator && second instanceof std.Iterator) { + var begin_2 = first; + var end_2 = second; + var size = 0; + for (var it = begin_2; !it.equal_to(end_2); it = it.next()) + size++; + // RESERVE + this.reserve(size); + this.size_ = size; + // ASSIGN CONTENTS + var array = this.matrix_[0]; + for (var it = begin_2; !it.equal_to(end_2); it = it.next()) { + if (array.length >= this.get_col_size()) { + array = new Array(); + this.matrix_.push(array); + } + array.push(it.value); } - if (args.length == 1 && (args[0] instanceof std.Iterator == false || args[0].get_source() != this)) - return this.erase_by_key(args[0]); - else if (args.length == 1) - return this.erase_by_iterator(args[0]); - else - return this.erase_by_iterator(args[0], args[1]); - }; - /** - * @hidden - */ - MapContainer.prototype.erase_by_key = function (key) { - var it = this.find(key); - if (it.equal_to(this.end()) == true) - return 0; - this.erase_by_iterator(it); - return 1; - }; - /** - * @hidden - */ - MapContainer.prototype.erase_by_iterator = function (first, last) { - if (last === void 0) { last = first.next(); } - var ret; - var is_reverse_iterator = false; - // REVERSE ITERATOR TO ITERATOR - if (first instanceof std.MapReverseIterator) { - is_reverse_iterator = true; - var first_it = last.base(); - var last_it = first.base(); - first = first_it; - last = last_it; + } + else { + var size = first; + var val = second; + // RESERVE + this.reserve(size); + this.size_ = size; + // ASSIGN CONTENTS + var array = this.matrix_[0]; + for (var i = 0; i < size; i++) { + if (array.length >= this.get_col_size()) { + array = new Array(); + this.matrix_.push(array); + } + array.push(val); } - // ERASE ELEMENTS - ret = this.erase_by_range(first, last); - // RETURN BRANCHES - if (is_reverse_iterator == true) - return new std.MapReverseIterator(ret.next()); - else - return ret; - }; - /** - * @hidden - */ - MapContainer.prototype.erase_by_range = function (begin, end) { - // ERASE - var listIterator = this.data_.erase(begin.get_list_iterator(), end.get_list_iterator()); - // POST-PROCESS - this._Handle_erase(begin, end); - return new std.MapIterator(this, listIterator); - }; - /* --------------------------------------------------------- - SWAP - --------------------------------------------------------- */ - /** - * @hidden - */ - MapContainer.prototype._Swap = function (obj) { - _a = [obj.data_, this.data_], this.data_ = _a[0], obj.data_ = _a[1]; - var _a; - }; - return MapContainer; - }(base.Container)); - base.MapContainer = MapContainer; - })(base = std.base || (std.base = {})); -})(std || (std = {})); -var std; -(function (std) { - /** - *

An iterator of {@link MapContainer map container}.

- * - *

- *

- * - * @author Jeongho Nam - */ - var MapIterator = (function (_super) { - __extends(MapIterator, _super); - /* --------------------------------------------------------- - CONSTRUCTORS - --------------------------------------------------------- */ + } + }; /** - * Construct from the {@link MapContainer source map} and {@link ListIterator list iterator}. - * - * @param source The source {@link MapContainer}. - * @param list_iterator A {@link ListIterator} pointing {@link Pair} of key and value. + * @inheritdoc */ - function MapIterator(source, list_iterator) { - _super.call(this, source); - this.list_iterator_ = list_iterator; - } - /* --------------------------------------------------------- - MOVERS - --------------------------------------------------------- */ + Deque.prototype.reserve = function (capacity) { + // MEMORIZE + var prevMatrix = this.matrix_; + var prevSize = this.size_; + // REFRESH + this.matrix_ = new Array(); + this.matrix_.push(new Array()); + ///// + // RE-FILL + ///// + var array = this.matrix_[0]; + for (var i = 0; i < prevMatrix.length; i++) + for (var j = 0; j < prevMatrix[i].length; j++) { + if (array.length >= this.get_col_size()) { + array = new Array(); + this.matrix_.push(array); + } + array.push(prevMatrix[i][j]); + } + }; /** - * Get iterator to previous element. + * @inheritdoc */ - MapIterator.prototype.prev = function () { - return new MapIterator(this.map, this.list_iterator_.prev()); + Deque.prototype.clear = function () { + // CLEAR CONTENTS + this.matrix_ = new Array(); + this.matrix_.push(new Array()); + // RE-INDEX + this.size_ = 0; + this.capacity_ = Deque.MIN_CAPACITY; }; + /* ========================================================= + ACCESSORS + - GETTERS & SETTERS + - ITERATORS + ========================================================= */ /** - * Get iterator to next element. + * @inheritdoc */ - MapIterator.prototype.next = function () { - return new MapIterator(this.map, this.list_iterator_.next()); + Deque.prototype.begin = function () { + if (this.empty() == true) + return this.end(); + else + return new std.DequeIterator(this, 0); }; /** - * Advances the Iterator by n element positions. - * - * @param step Number of element positions to advance. - * @return An advanced Iterator. + * @inheritdoc */ - MapIterator.prototype.advance = function (step) { - return new MapIterator(this.map, this.list_iterator_.advance(step)); + Deque.prototype.end = function () { + return new std.DequeIterator(this, -1); }; - Object.defineProperty(MapIterator.prototype, "map", { - /* --------------------------------------------------------- - ACCESSORS - --------------------------------------------------------- */ - /** - * @hidden - */ - get: function () { - return this.source_; - }, - enumerable: true, - configurable: true - }); /** - * Get ListIterator. + * @inheritdoc */ - MapIterator.prototype.get_list_iterator = function () { - return this.list_iterator_; + Deque.prototype.rbegin = function () { + return new std.DequeReverseIterator(this.end()); }; - Object.defineProperty(MapIterator.prototype, "value", { - /** - * @inheritdoc - */ - get: function () { - return this.list_iterator_.value; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(MapIterator.prototype, "first", { - /** - * Get first, key element. - */ - get: function () { - return this.list_iterator_.value.first; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(MapIterator.prototype, "second", { - /** - * Get second, value element. - */ - get: function () { - return this.list_iterator_.value.second; - }, - /** - * Set second value. - */ - set: function (val) { - this.list_iterator_.value.second = val; - }, - enumerable: true, - configurable: true - }); - /* --------------------------------------------------------- - COMPARISONS - --------------------------------------------------------- */ /** - *

Whether an iterator is equal with the iterator.

- * - *

Compare two iterators and returns whether they are equal or not.

- * - * @param obj An iterator to compare - * @return Indicates whether equal or not. + * @inheritdoc */ - MapIterator.prototype.equal_to = function (obj) { - return this.source_ == obj.source_ && this.list_iterator_.equal_to(obj.list_iterator_); + Deque.prototype.rend = function () { + return new std.DequeReverseIterator(this.begin()); }; - MapIterator.prototype.less = function (obj) { - return std.less(this.first, obj.first); + /** + * @inheritdoc + */ + Deque.prototype.size = function () { + return this.size_; }; - MapIterator.prototype.hash = function () { - return std.hash(this.first); + /** + * @inheritdoc + */ + Deque.prototype.empty = function () { + return this.size_ == 0; }; - MapIterator.prototype.swap = function (obj) { - this.list_iterator_.swap(obj.list_iterator_); + /** + * @inheritdoc + */ + Deque.prototype.capacity = function () { + return this.capacity_; }; - return MapIterator; - }(std.Iterator)); - std.MapIterator = MapIterator; - /** - *

A reverse-iterator of {@link MapContainer map container}.

- * - *

- *

- * - * @author Jeongho Nam - */ - var MapReverseIterator = (function (_super) { - __extends(MapReverseIterator, _super); - /* --------------------------------------------------------- - CONSTRUCTORS - --------------------------------------------------------- */ /** - * Construct from base iterator. - * - * @param base A reference of the base iterator, which iterates in the opposite direction. + * @inheritdoc */ - function MapReverseIterator(base) { - _super.call(this, base); - } + Deque.prototype.at = function (index) { + if (index > this.size()) + throw new std.OutOfRange("Target index is greater than Deque's size."); + var indexPair = this.fetch_index(index); + return this.matrix_[indexPair.first][indexPair.second]; + }; + /** + * @inheritdoc + */ + Deque.prototype.set = function (index, val) { + if (index > this.size()) + throw new std.OutOfRange("Target index is greater than Deque's size."); + var indexPair = this.fetch_index(index); + this.matrix_[indexPair.first][indexPair.second] = val; + }; + /** + * @inheritdoc + */ + Deque.prototype.front = function () { + return this.matrix_[0][0]; + }; + /** + * @inheritdoc + */ + Deque.prototype.back = function () { + var lastArray = this.matrix_[this.matrix_.length - 1]; + return lastArray[lastArray.length - 1]; + }; + /** + // Fetch row and column's index. /** * @hidden */ - MapReverseIterator.prototype.create_neighbor = function (base) { - return new MapReverseIterator(base); + Deque.prototype.fetch_index = function (index) { + var row; + for (row = 0; row < this.matrix_.length; row++) { + var array = this.matrix_[row]; + if (index < array.length) + break; + index -= array.length; + } + if (row == this.matrix_.length) + row--; + return std.make_pair(row, index); }; - Object.defineProperty(MapReverseIterator.prototype, "first", { - /* --------------------------------------------------------- - ACCESSORS - --------------------------------------------------------- */ - /** - * Get first, key element. - */ - get: function () { - return this.base_.first; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(MapReverseIterator.prototype, "second", { - /** - * Get second, value element. - */ - get: function () { - return this.base_.second; - }, - /** - * Set second value. - */ - set: function (val) { - this.base_.second = val; - }, - enumerable: true, - configurable: true - }); - return MapReverseIterator; - }(std.ReverseIterator)); - std.MapReverseIterator = MapReverseIterator; -})(std || (std = {})); -/// -/// -var std; -(function (std) { - var base; - (function (base) { + /* ========================================================= + ELEMENTS I/O + - PUSH & POP + - INSERT + - ERASE + - PRE & POST-PROCESS + - SWAP + ============================================================ + PUSH & POP + --------------------------------------------------------- */ /** - *

An abstract multi-map.

- * - *

{@link MultiMap MultiMaps} are associative containers that store elements formed by a combination of a - * key value (Key) and a mapped value (T), and which allows for fast retrieval of - * individual elements based on their keys.

- * - *

In a {@link MapContainer}, the key values are generally used to identify the elements, while the - * mapped values store the content associated to this key. The types of key and - * mapped value may differ, and are grouped together in member type value_type, which is a - * {@link Pair} type combining both:

- * - *

typedef pair value_type;

- * - *

{@link UniqueMap} stores elements, keeps sequence and enables indexing by inserting elements into a - * {@link List} and registering {@link ListIterator iterators} of the {@link data_ list container} to an index - * table like {@link RBTree tree} or {@link HashBuckets hash-table}.

- * - *

- *

- * - *

Container properties

- *
- *
Associative
- *
- * Elements in associative containers are referenced by their key and not by their absolute position - * in the container. - *
- * - *
Map
- *
- * Each element associates a key to a mapped value: - * Keys are meant to identify the elements whose main content is the mapped value. - *
- * - *
Multiple equivalent keys
- *
Multiple elements in the container can have equivalent keys.
- *
- * - * @param Type of the keys. Each element in a map is identified by its key value. - * @param Type of the mapped value. Each element in a map stores some data as its mapped value. - * - * @author Jeongho Nam + * @inheritdoc */ - var MultiMap = (function (_super) { - __extends(MultiMap, _super); - function MultiMap() { - _super.apply(this, arguments); + Deque.prototype.push = function () { + var items = []; + for (var _i = 0; _i < arguments.length; _i++) { + items[_i - 0] = arguments[_i]; } - MultiMap.prototype.emplace = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i - 0] = arguments[_i]; - } - if (args.length == 1) - return this._Insert_by_pair(args[0]); - else - return this._Insert_by_pair(std.make_pair(args[0], args[1])); - }; - MultiMap.prototype.insert = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i - 0] = arguments[_i]; + // RE-SIZE + if (this.size_ + items.length > this.capacity_) + this.reserve(this.size_ + items.length); + // INSERTS + var array = this.matrix_[this.matrix_.length - 1]; + for (var i = 0; i < items.length; i++) { + if (array.length >= this.get_col_size()) { + array = new Array(); + this.matrix_.push(array); } - return _super.prototype.insert.apply(this, args); - }; - return MultiMap; - }(base.MapContainer)); - base.MultiMap = MultiMap; - })(base = std.base || (std.base = {})); -})(std || (std = {})); -/// -/// -/// -var std; -(function (std) { - var base; - (function (base) { + array.push(items[i]); + } + // INDEXING + this.size_ += items.length; + return this.size_; + }; /** - *

An abstract set.

- * - *

{@link SetContainer SetContainers} are containers that store elements allowing fast retrieval of - * individual elements based on their value.

- * - *

In an {@link SetContainer}, the value of an element is at the same time its key, used to - * identify it. Keys are immutable, therefore, the elements in an {@link SetContainer} cannot be - * modified once in the container - they can be inserted and removed, though.

- * - *

{@link SetContainer} stores elements, keeps sequence and enables indexing by inserting elements into a - * {@link List} and registering {@link ListIterator iterators} of the {@link data_ list container} to an index - * table like {@link RBTree tree} or {@link HashBuckets hash-table}.

- * - *

- *

- * - *

Container properties

- *
- *
Associative
- *
- * Elements in associative containers are referenced by their key and not by their absolute - * position in the container. - *
- * - *
Set
- *
The value of an element is also the key used to identify it.
- *
- * - * @param Type of the elements. Each element in a {@link SetContainer} container is also identified - * by this value (each value is itself also the element's key). - * - * @author Jeongho Nam - */ - var SetContainer = (function (_super) { - __extends(SetContainer, _super); - /* --------------------------------------------------------- - CONSTURCTORS - --------------------------------------------------------- */ - /** - * Default Constructor. - */ - function SetContainer() { - _super.call(this); - this.data_ = new std.List(); - } - /** - * @inheritdoc - */ - SetContainer.prototype.assign = function (begin, end) { - // INSERT - this.clear(); - this.insert(begin, end); - }; - /** - * @inheritdoc - */ - SetContainer.prototype.clear = function () { - // TO BE ABSTRACT - this.data_.clear(); - }; - /** - * @inheritdoc - */ - SetContainer.prototype.begin = function () { - return new std.SetIterator(this, this.data_.begin()); - }; - /** - * @inheritdoc - */ - SetContainer.prototype.end = function () { - return new std.SetIterator(this, this.data_.end()); - }; - /** - * @inheritdoc - */ - SetContainer.prototype.rbegin = function () { - return new std.SetReverseIterator(this.end()); - }; - /** - * @inheritdoc - */ - SetContainer.prototype.rend = function () { - return new std.SetReverseIterator(this.begin()); - }; - /* --------------------------------------------------------- - ELEMENTS - --------------------------------------------------------- */ - /** - *

Whether have the item or not.

- * - *

Indicates whether a set has an item having the specified identifier.

- * - * @param key Key value of the element whose mapped value is accessed. - * - * @return Whether the set has an item having the specified identifier. - */ - SetContainer.prototype.has = function (val) { - return !this.find(val).equal_to(this.end()); - }; - /** - * @inheritdoc - */ - SetContainer.prototype.size = function () { - return this.data_.size(); - }; - ///** - // * @hidden - // */ - //protected _Get_data(): List - //{ - // return this.data_; - //} - /* ========================================================= - ELEMENTS I/O - - INSERT - - ERASE - - POST-PROCESS - - SWAP - ============================================================ - INSERT - --------------------------------------------------------- */ - /** - * @inheritdoc - */ - SetContainer.prototype.push = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i - 0] = arguments[_i]; - } - // TO BE ABSTRACT - for (var i = 0; i < args.length; i++) - this._Insert_by_val(args[i]); - return this.size(); - }; - SetContainer.prototype.insert = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i - 0] = arguments[_i]; - } - if (args.length == 1) - return this._Insert_by_val(args[0]); - else if (args.length == 2 && args[0] instanceof std.Iterator) { - if (args[1] instanceof std.Iterator && args[0].get_source() != this && args[1].get_source() != this) { - // IT DOESN'T CONTAIN POSITION - // RANGES TO INSERT ONLY - return this._Insert_by_range(args[0], args[1]); - } - else { - var ret = void 0; - var is_reverse_iterator = false; - // REVERSE_ITERATOR TO ITERATOR - if (args[0] instanceof std.SetReverseIterator) { - is_reverse_iterator = true; - args[0] = args[0].base().prev(); - } - // INSERT AN ELEMENT - ret = this._Insert_by_hint(args[0], args[1]); - // RETURN BRANCHES - if (is_reverse_iterator == true) - return new std.SetReverseIterator(ret.next()); - else - return ret; - } - } - }; - SetContainer.prototype.erase = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i - 0] = arguments[_i]; - } - if (args.length == 1 && (args[0] instanceof std.Iterator == false || args[0].get_source() != this)) - return this.erase_by_val(args[0]); - else if (args.length == 1) - return this.erase_by_iterator(args[0]); - else - return this.erase_by_iterator(args[0], args[1]); - }; - /** - * @hidden - */ - SetContainer.prototype.erase_by_iterator = function (first, last) { - if (last === void 0) { last = first.next(); } - var ret; - var is_reverse_iterator = false; - // REVERSE ITERATOR TO ITERATOR - if (first instanceof std.SetReverseIterator) { - is_reverse_iterator = true; - var first_it = last.base(); - var last_it = first.base(); - first = first_it; - last = last_it; - } - // ERASE ELEMENTS - ret = this.erase_by_range(first, last); - // RETURN BRANCHES - if (is_reverse_iterator == true) - return new std.SetReverseIterator(ret.next()); - else - return ret; - }; - /** - * @hidden - */ - SetContainer.prototype.erase_by_val = function (val) { - // TEST WHETHER EXISTS - var it = this.find(val); - if (it.equal_to(this.end()) == true) - return 0; - // ERASE - this.erase_by_iterator(it); - return 1; - }; - /** - * @hidden - */ - SetContainer.prototype.erase_by_range = function (begin, end) { - // ERASE - var list_iterator = this.data_.erase(begin.get_list_iterator(), end.get_list_iterator()); - // POST-PROCESS - this._Handle_erase(begin, end); - return new std.SetIterator(this, list_iterator); //begin.prev(); - }; - /* --------------------------------------------------------- - SWAP - --------------------------------------------------------- */ - /** - * @hidden - */ - SetContainer.prototype._Swap = function (obj) { - _a = [obj.data_, this.data_], this.data_ = _a[0], obj.data_ = _a[1]; - var _a; - }; - return SetContainer; - }(base.Container)); - base.SetContainer = SetContainer; - })(base = std.base || (std.base = {})); -})(std || (std = {})); -var std; -(function (std) { - /** - *

An iterator of a Set.

- * - *

- *

- * - * @author Jeongho Nam - */ - var SetIterator = (function (_super) { - __extends(SetIterator, _super); - /** - *

Construct from source and index number.

- * - *

Note

- *

Do not create iterator directly.

- *

Use begin(), find() or end() in Map instead.

- * - * @param map The source Set to reference. - * @param index Sequence number of the element in the source Set. + * @inheritdoc */ - function SetIterator(source, it) { - _super.call(this, source); - this.list_iterator_ = it; - } - /* --------------------------------------------------------- - MOVERS - --------------------------------------------------------- */ + Deque.prototype.push_front = function (val) { + // INSERT TO THE FRONT + this.matrix_[0].unshift(val); + this.size_++; + if (this.size_ > this.capacity_) + this.reserve(this.size_ * 2); + }; /** * @inheritdoc */ - SetIterator.prototype.prev = function () { - return new SetIterator(this.set, this.list_iterator_.prev()); + Deque.prototype.push_back = function (val) { + var lastArray = this.matrix_[this.matrix_.length - 1]; + if (lastArray.length >= this.get_col_size() && this.matrix_.length < Deque.ROW) { + lastArray = new Array(); + this.matrix_.push(lastArray); + } + lastArray.push(val); + this.size_++; + if (this.size_ > this.capacity_) + this.reserve(this.size_ * 2); }; /** * @inheritdoc */ - SetIterator.prototype.next = function () { - return new SetIterator(this.set, this.list_iterator_.next()); + Deque.prototype.pop_front = function () { + if (this.empty() == true) + return; // SOMEWHERE PLACE TO THROW EXCEPTION + // EREASE FIRST ELEMENT + this.matrix_[0].shift(); + this.size_--; + if (this.matrix_[0].length == 0 && this.matrix_.length > 1) + this.matrix_.shift(); }; /** * @inheritdoc */ - SetIterator.prototype.advance = function (size) { - return new SetIterator(this.set, this.list_iterator_.advance(size)); + Deque.prototype.pop_back = function () { + if (this.empty() == true) + return; // SOMEWHERE PLACE TO THROW EXCEPTION + // ERASE LAST ELEMENT + var lastArray = this.matrix_[this.matrix_.length - 1]; + lastArray.splice(lastArray.length - 1, 1); + this.size_--; + if (lastArray.length == 0 && this.matrix_.length > 1) + this.matrix_.splice(this.matrix_.length - 1, 1); }; - Object.defineProperty(SetIterator.prototype, "set", { - /* --------------------------------------------------------- - ACCESSORS - --------------------------------------------------------- */ - /** - * @hidden - */ - get: function () { - return this.source_; - }, - enumerable: true, - configurable: true - }); - SetIterator.prototype.get_list_iterator = function () { - return this.list_iterator_; + Deque.prototype.insert = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i - 0] = arguments[_i]; + } + // REVERSE_ITERATOR TO ITERATOR + var ret; + var is_reverse_iterator = false; + if (args[0] instanceof std.DequeReverseIterator) { + is_reverse_iterator = true; + args[0] = args[0].base().prev(); + } + // BRANCHES + if (args.length == 2) + ret = this.insert_by_val(args[0], args[1]); + else if (args.length == 3 && typeof args[1] == "number") + ret = this._Insert_by_repeating_val(args[0], args[1], args[2]); + else + ret = this._Insert_by_range(args[0], args[1], args[2]); + // RETURNS + if (is_reverse_iterator == true) + return new std.DequeReverseIterator(ret.next()); + else + return ret; }; - Object.defineProperty(SetIterator.prototype, "value", { - /** - * @inheritdoc - */ - get: function () { - return this.list_iterator_.value; - }, - enumerable: true, - configurable: true - }); - /* --------------------------------------------------------- - COMPARISONS - --------------------------------------------------------- */ /** - * @inheritdoc + * @hidden */ - SetIterator.prototype.equal_to = function (obj) { - return _super.prototype.equal_to.call(this, obj) && this.list_iterator_ == obj.list_iterator_; + Deque.prototype.insert_by_val = function (position, val) { + return this._Insert_by_repeating_val(position, 1, val); }; /** - * @inheritdoc + * @hidden */ - SetIterator.prototype.less = function (obj) { - return std.less(this.value, obj.value); + Deque.prototype._Insert_by_repeating_val = function (position, n, val) { + // CONSTRUCT ITEMS + var items = []; + items.length = n; + for (var i = 0; i < n; i++) + items[i] = val; + // INSERT ELEMENTS + if (position.equal_to(this.end())) { + this.push.apply(this, items); + return this.begin(); + } + else + return this.insert_by_items(position, items); }; /** - * @inheritdoc + * @hidden */ - SetIterator.prototype.hash = function () { - return std.hash(this.value); + Deque.prototype._Insert_by_range = function (position, begin, end) { + // CONSTRUCT ITEMS + var items = []; + for (var it = begin; !it.equal_to(end); it = it.next()) + items.push(it.value); + // INSERT ELEMENTS + if (position.equal_to(this.end())) { + this.push.apply(this, items); + return this.begin(); + } + else + return this.insert_by_items(position, items); }; /** - * @inheritdoc + * @hidden */ - SetIterator.prototype.swap = function (obj) { - this.list_iterator_.swap(obj.list_iterator_); + Deque.prototype.insert_by_items = function (position, items) { + var item_size = items.length; + this.size_ += item_size; + if (this.size_ <= this.capacity_) { + // ------------------------------------------------------ + // WHEN FITTING INTO RESERVED CAPACITY IS POSSIBLE + // ------------------------------------------------------ + // INSERTS CAREFULLY CONSIDERING THE COL_SIZE + var index_pair = this.fetch_index(position.index); + var index = index_pair.first; + var spliced_values = this.matrix_[index].splice(index_pair.second); + if (spliced_values.length != 0) + items = items.concat.apply(items, spliced_values); + if (this.matrix_[index].length < Deque.ROW) { + this.matrix_[index] = (_a = this.matrix_[index]).concat.apply(_a, items.splice(0, Deque.ROW - this.matrix_[index].length)); + } + var splicedArray = this.matrix_.splice(index + 1); + // INSERTS + while (items.length != 0) + this.matrix_.push(items.splice(0, Math.min(Deque.ROW, items.length))); + // CONCAT WITH BACKS + this.matrix_ = (_b = this.matrix_).concat.apply(_b, splicedArray); + } + else { + // ----------------------------------------------------- + // WHEN CANNOT BE FIT INTO THE RESERVED CAPACITY + // ----------------------------------------------------- + // JUST INSERT CARELESSLY + // AND KEEP BLANACE BY THE RESERVE() METHOD + if (position.equal_to(this.end()) == true) { + this.matrix_.push(items); // ALL TO THE LAST + } + else { + var indexPair = this.fetch_index(position.index); + var index = indexPair.first; + var splicedValues = this.matrix_[index].splice(indexPair.second); + if (splicedValues.length != 0) + items = items.concat.apply(items, splicedValues); + // ALL TO THE MIDDLE + this.matrix_[index] = (_c = this.matrix_[index]).concat.apply(_c, items); + } + // AND KEEP BALANCE BY RESERVE() + this.reserve(this.size_); + } + return position; + var _a, _b, _c; }; - return SetIterator; - }(std.Iterator)); - std.SetIterator = SetIterator; + Deque.prototype.erase = function (first, last) { + if (last === void 0) { last = first.next(); } + var ret; + var is_reverse_iterator = false; + // REVERSE_ITERATOR TO ITERATOR + if (first instanceof std.DequeReverseIterator) { + is_reverse_iterator = true; + var first_it = last.base(); + var last_it = first.base(); + first = first_it; + last = last_it; + } + // ERASE ELEMENTS + ret = this._Erase_by_range(first, last); + // RETURN BRANCHES + if (is_reverse_iterator == true) + return new std.DequeReverseIterator(ret.next()); + else + return ret; + }; + /** + * @hidden + */ + Deque.prototype._Erase_by_range = function (first, last) { + if (first.index == -1) + return first; + // INDEXING + var size; + if (last.index == -1) + size = this.size() - first.index; + else + size = last.index - first.index; + this.size_ -= size; + // ERASING + while (size != 0) { + var indexPair = this.fetch_index(first.index); + var array = this.matrix_[indexPair.first]; + var myDeleteSize = Math.min(size, array.length - indexPair.second); + array.splice(indexPair.second, myDeleteSize); + if (array.length == 0 && this.matrix_.length > 1) + this.matrix_.splice(indexPair.first, 1); + size -= myDeleteSize; + } + if (last.index == -1) + return this.end(); + else + return first; + }; + Deque.prototype.swap = function (obj) { + if (obj instanceof Deque) { + _a = [obj.matrix_, this.matrix_], this.matrix_ = _a[0], obj.matrix_ = _a[1]; + _b = [obj.size_, this.size_], this.size_ = _b[0], obj.size_ = _b[1]; + _c = [obj.capacity_, this.capacity_], this.capacity_ = _c[0], obj.capacity_ = _c[1]; + } + else + _super.prototype.swap.call(this, obj); + var _a, _b, _c; + }; + return Deque; + }(std.base.Container)); + std.Deque = Deque; +})(std || (std = {})); +var std; +(function (std) { /** - *

A reverse-iterator of Set.

- * - *

- *

+ *

An iterator of {@link Deque}.

* - * @param Type of the elements. + *

+ * + *

* * @author Jeongho Nam */ - var SetReverseIterator = (function (_super) { - __extends(SetReverseIterator, _super); + var DequeIterator = (function (_super) { + __extends(DequeIterator, _super); /* --------------------------------------------------------- CONSTRUCTORS --------------------------------------------------------- */ /** - * Construct from base iterator. + *

Construct from the source {@link Deque container}.

* - * @param base A reference of the base iterator, which iterates in the opposite direction. + *

Note

+ *

Do not create the iterator directly, by yourself.

+ *

Use {@link Deque.begin begin()}, {@link Deque.end end()} in {@link Deque container} instead.

+ * + * @param source The source {@link Deque container} to reference. + * @param index Sequence number of the element in the source {@link Deque}. */ - function SetReverseIterator(base) { - _super.call(this, base); + function DequeIterator(source, index) { + _super.call(this, source); + this.index_ = index; } + Object.defineProperty(DequeIterator.prototype, "deque", { + /* --------------------------------------------------------- + ACCESSORS + --------------------------------------------------------- */ + /** + * @hidden + */ + get: function () { + return this.source_; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(DequeIterator.prototype, "value", { + /** + * @inheritdoc + */ + get: function () { + return this.deque.at(this.index_); + }, + /** + * Set value of the iterator is pointing to. + * + * @param val Value to set. + */ + set: function (val) { + this.deque.set(this.index_, val); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(DequeIterator.prototype, "index", { + /** + * @inheritdoc + */ + get: function () { + return this.index_; + }, + enumerable: true, + configurable: true + }); + /* --------------------------------------------------------- + MOVERS + --------------------------------------------------------- */ /** - * @hidden + * @inheritdoc */ - SetReverseIterator.prototype.create_neighbor = function (base) { - return new SetReverseIterator(base); + DequeIterator.prototype.prev = function () { + if (this.index_ == -1) + return new DequeIterator(this.deque, this.deque.size() - 1); + else if (this.index_ - 1 < 0) + return this.deque.end(); + else + return new DequeIterator(this.deque, this.index_ - 1); }; - return SetReverseIterator; - }(std.ReverseIterator)); - std.SetReverseIterator = SetReverseIterator; -})(std || (std = {})); -/// -/// -var std; -(function (std) { - var base; - (function (base) { /** - *

An abstract set.

- * - *

{@link SetContainer SetContainers} are containers that store elements allowing fast retrieval of - * individual elements based on their value.

- * - *

In an {@link SetContainer}, the value of an element is at the same time its key, used to - * identify it. Keys are immutable, therefore, the elements in an {@link SetContainer} cannot be - * modified once in the container - they can be inserted and removed, though.

- * - *

{@link SetContainer} stores elements, keeps sequence and enables indexing by inserting elements into a - * {@link List} and registering {@link ListIterator iterators} of the {@link data_ list container} to an index - * table like {@link RBTree tree} or {@link HashBuckets hash-table}.

- * - *

- *

- * - *

Container properties

- *
- *
Associative
- *
- * Elements in associative containers are referenced by their key and not by their absolute - * position in the container. - *
+ * @inheritdoc + */ + DequeIterator.prototype.next = function () { + if (this.index_ >= this.source_.size() - 1) + return this.deque.end(); + else + return new DequeIterator(this.deque, this.index_ + 1); + }; + /** + * @inheritdoc + */ + DequeIterator.prototype.advance = function (n) { + var new_index; + if (n < 0 && this.index_ == -1) + new_index = this.deque.size() + n; + else + new_index = this.index_ + n; + if (new_index < 0 || new_index >= this.deque.size()) + return this.deque.end(); + else + return new DequeIterator(this.deque, new_index); + }; + /* --------------------------------------------------------- + COMPARES + --------------------------------------------------------- */ + /** + *

Whether an iterator is equal with the iterator.

* - *
Set
- *
The value of an element is also the key used to identify it.
+ *

Compare two iterators and returns whether they are equal or not.

* - *
Multiple equivalent keys
- *
Multiple elements in the container can have equivalent keys.
- *
+ *

Note

+ *

Iterator's equal_to() only compare souce container and index number.

* - * @param Type of the elements. Each element in a {@link SetContainer} container is also identified - * by this value (each value is itself also the element's key). + *

Although elements in a pair, key and value are equal_to, if the source map or + * index number is different, then the {@link equal_to equal_to()} will return false. If you want to + * compare the elements of a pair, compare them directly by yourself.

* - * @author Jeongho Nam + * @param obj An iterator to compare + * @return Indicates whether equal or not. */ - var MultiSet = (function (_super) { - __extends(MultiSet, _super); - function MultiSet() { - _super.apply(this, arguments); - } - MultiSet.prototype.insert = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i - 0] = arguments[_i]; - } - return _super.prototype.insert.apply(this, args); - }; - return MultiSet; - }(base.SetContainer)); - base.MultiSet = MultiSet; - })(base = std.base || (std.base = {})); + DequeIterator.prototype.equal_to = function (obj) { + return _super.prototype.equal_to.call(this, obj) && this.index_ == obj.index_; + }; + /** + * @inheritdoc + */ + DequeIterator.prototype.swap = function (obj) { + _a = [obj.value, this.value], this.value = _a[0], obj.value = _a[1]; + var _a; + }; + return DequeIterator; + }(std.Iterator)); + std.DequeIterator = DequeIterator; })(std || (std = {})); -/// var std; (function (std) { - var base; - (function (base) { + /** + *

A reverse-iterator of Deque.

+ * + *

+ * + *

+ * + * @param Type of the elements. + * + * @author Jeongho Nam + */ + var DequeReverseIterator = (function (_super) { + __extends(DequeReverseIterator, _super); + /* --------------------------------------------------------- + CONSTRUCTORS + --------------------------------------------------------- */ /** - *

Red-black Tree.

- * - *

A red-black tree is a kind of self-balancing - * binary search tree. Each node of the binary tree has an extra bit, and that bit is often interpreted as the - * color (red or black) of the node. These color bits - * are used to ensure the tree remains approximately balanced during insertions and deletions.

- * - *

Balance is preserved by painting each node of the tree with one of two colors (typically called - * 'red' and 'black') in a way that satisfies certain - * properties, which collectively constrain how unbalanced the tree can become in the worst case. When the tree - * is modified, the new tree is subsequently rearranged and repainted to restore the coloring properties. The - * properties are designed in such a way that this rearranging and recoloring can be performed efficiently.

- * - *

The balancing of the tree is not perfect but it is good enough to allow it to guarantee searching in - * O(log n) time, where n is the total number of elements in the tree. The insertion and deletion operations, - * along with the tree rearrangement and recoloring, are also performed in O(log n) time.

- * - *

Tracking the color of each node requires only 1 bit of information per node because there are only two - * colors. The tree does not contain any other data specific to its being a - * red-black tree so its memory footprint is almost - * identical to a classic (uncolored) binary search tree. In many cases the additional bit of information can - * be stored at no additional memory cost.

- * - *

Properties

- *

In addition to the requirements imposed on a binary search tree the following must be satisfied by a - * red-black tree:

- * - *
    - *
  1. A node is either red or black.
  2. - *
  3. - * The root is black. This rule is sometimes omitted. Since the root can - * always be changed from red to black, but not - * necessarily vice versa, this rule has little effect on analysis. - *
  4. - *
  5. All leaves (NIL; null) are black.
  6. - *
  7. - * If a node is red, then both its children are - * black. - *
  8. - *
  9. - * Every path from a given node to any of its descendant NIL nodes contains the same number of - * black nodes. Some definitions: the number of - * black nodes from the root to a node is the node's - * black depth; the uniform number of black - * nodes in all paths from root to the leaves is called the black-height of - * the red-black tree. - *
  10. - *
- * - *

- * - *

These constraints enforce a critical property of red-black trees: the path from the root to the farthest - * leaf is no more than twice as long as the path from the root to the nearest leaf. The result is that the tree - * is roughly height-balanced. Since operations such as inserting, deleting, and finding values require - * worst-case time proportional to the height of the tree, this theoretical upper bound on the height allows - * red-black trees to be efficient in the worst case, unlike ordinary binary search trees.

+ * Construct from base iterator. * - *

To see why this is guaranteed, it suffices to consider the effect of properties 4 and 5 together. For a - * red-black tree T, let B be the number of black nodes in property 5. Let the - * shortest possible path from the root of T to any leaf consist of B black nodes. - * Longer possible paths may be constructed by inserting red nodes. However, property 4 - * makes it impossible to insert more than one consecutive red node. Therefore, - * ignoring any black NIL leaves, the longest possible path consists of 2*B nodes, - * alternating black and red (this is the worst case). - * Counting the black NIL leaves, the longest possible path consists of 2*B-1 - * nodes.

- * - *

The shortest possible path has all black nodes, and the longest possible - * path alternates between red and black nodes. Since all - * maximal paths have the same number of black nodes, by property 5, this shows - * that no path is more than twice as long as any other path.

- * - * @param Type of elements. - * - * @reference https://en.wikipedia.org/w/index.php?title=Red%E2%80%93black_tree - * @inventor Rudolf Bayer - * @author Migrated by Jeongho Nam + * @param base A reference of the base iterator, which iterates in the opposite direction. */ - var XTree = (function () { - /* ========================================================= - CONSTRUCTOR - ========================================================= */ - /** - * Default Constructor. - */ - function XTree() { - this.root_ = null; - } - XTree.prototype.clear = function () { - this.root_ = null; - }; - /* ========================================================= + function DequeReverseIterator(base) { + _super.call(this, base); + } + /** + * @hidden + */ + DequeReverseIterator.prototype.create_neighbor = function (base) { + return new DequeReverseIterator(base); + }; + Object.defineProperty(DequeReverseIterator.prototype, "value", { + /* --------------------------------------------------------- ACCESSORS - - GETTERS - - COMPARISON - ============================================================ - GETTERS - --------------------------------------------------------- */ - /** - * Find a node from its contained value. - * - * @param val Value to find. - */ - XTree.prototype.find = function (val) { - if (this.root_ == null) - return null; - var node = this.root_; - while (true) { - var newNode = null; - if (this.is_equal_to(val, node.value)) - break; // EQUALS, MEANS MATCHED, THEN TERMINATE - else if (this.is_less(val, node.value)) - newNode = node.left; // LESS, THEN TO THE LEFT - else - newNode = node.right; // GREATER, THEN TO THE RIGHT - // ULTIL CHILD NODE EXISTS - if (newNode == null) - break; - // SHIFT A NEW NODE TO THE NODE TO BE RETURNED - node = newNode; - } - return node; - }; - /** - * Fetch maximum (the rightes?) node from one. - * - * @param node A node to fetch its maximum node. - * @return The maximum node. - */ - XTree.prototype.fetch_maximum = function (node) { - while (node.right != null) - node = node.right; - return node; - }; - /* ========================================================= - ELEMENTS I/O - - INSERT - - ERASE - - COLOR - - ROTATION - ============================================================ - INSERT --------------------------------------------------------- */ /** - *

Insert an element with a new node.

- * - *

Insertion begins by adding the node as any binary search tree insertion does and by coloring it - * red. Whereas in the binary search tree, we always add a leaf, in the red-black - * tree, leaves contain no information, so instead we add a red interior node, with - * two black leaves, in place of an existing - * black leaf.

- * - *

What happens next depends on the color of other nearby nodes. The term uncle node will be used to - * refer to the sibling of a node's parent, as in human family trees. Note that:

- * - *
    - *
  • property 3 (all leaves are black) always holds.
  • - *
  • - * property 4 (both children of every red node are - * black) is threatened only by adding a red - * node, repainting a black node red, or a - * rotation. - *
  • - *
  • - * property 5 (all paths from any given node to its leaf nodes contain the same number of - * black nodes) is threatened only by adding a - * black node, repainting a red node - * black (or vice versa), or a rotation. - *
  • - *
- * - *

Notes

- *
    - *
  1. - * The label N will be used to denote the current node (colored - * red). In the diagrams N carries a blue contour. At the - * beginning, this is the new node being inserted, but the entire procedure may also be applied - * recursively to other nodes (see case 3). {@link XTreeNode.parent P} will denote - * N's parent node, {@link XTreeNode.grand_parent G} will denote N's - * grandparent, and {@link XTreeNode.uncle U} will denote N's uncle. In between - * some cases, the roles and labels of the nodes are exchanged, but in each case, every label continues - * to represent the same node it represented at the beginning of the case. - *
  2. - *
  3. - * If a node in the right (target) half of a diagram carries a blue contour it will become the current - * node in the next iteration and there the other nodes will be newly assigned relative to it. Any - * color shown in the diagram is either assumed in its case or implied by those assumptions. - *
  4. - *
  5. - * A numbered triangle represents a subtree of unspecified depth. A black - * circle atop a triangle means that black-height of subtree is greater - * by one compared to subtree without this circle.
  6. - *
- * - *

There are several cases of red-black tree insertion to handle:

- * - *
    - *
  • N is the root node, i.e., first node of red-black tree.
  • - *
  • - * N's parent ({@link XTreeNode.parent P}) is black. - *
  • - *
  • - * N's parent ({@link XTreeNode.parent P}) and uncle - * ({@link XTreeNode.uncle U}) are red. - *
  • - *
  • - * N is added to right of left child of grandparent, or N is added to left - * of right child of grandparent ({@link XTreeNode.parent P} is red and - * {@link XTreeNode.uncle U} is black). - *
  • - *
  • - * N is added to left of left child of grandparent, or N is added to right - * of right child of grandparent ({@link XTreeNode.parent P} is red and - * {@link XTreeNode.uncle U} is black). - *
  • - *
- * - *

Note

- *

Note that inserting is actually in-place, since all the calls above use tail recursion.

- * - *

In the algorithm above, all cases are chained in order, except in insert case 3 where it can recurse - * to case 1 back to the grandparent node: this is the only case where an iterative implementation will - * effectively loop. Because the problem of repair is escalated to the next higher level but one, it takes - * maximally h⁄2 iterations to repair the tree (where h is the height of the tree). Because the probability - * for escalation decreases exponentially with each iteration the average insertion cost is constant.

- * - * @param val An element to insert. + * @inheritdoc */ - XTree.prototype.insert = function (val) { - var parent = this.find(val); - var node = new base.XTreeNode(val, base.Color.RED); - if (parent == null) - this.root_ = node; - else { - node.parent = parent; - if (this.is_less(node.value, parent.value)) - parent.left = node; - else - parent.right = node; - } - this.insert_case1(node); - }; + get: function () { + return this.base_.value; + }, /** - *

N is the root node, i.e., first node of red-black tree.

- * - *

The current node N is at the {@link root_ root} of the tree.

- * - *

In this case, it is repainted black to satisfy property 2 (the root is - * black). Since this adds one black node to - * every path at once, property 5 (all paths from any given node to its leaf nodes contain the same number - * of black nodes) is not violated.

+ * Set value of the iterator is pointing to. * - * @param N A node to be inserted or swapped. + * @param val Value to set. */ - XTree.prototype.insert_case1 = function (N) { - if (N.parent == null) - N.color = base.Color.BLACK; - else - this.insert_case2(N); - }; + set: function (val) { + this.base_.value = val; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(DequeReverseIterator.prototype, "index", { /** - *

N's parent ({@link XTreeNode.parent P}) is black.

- * - *

The current node's parent {@link XTreeNode.parent P} is black, - * so property 4 (both children of every red node are - * black) is not invalidated.

- * - *

In this case, the tree is still valid. Property 5 (all paths from any given node to its leaf nodes - * contain the same number of black nodes) is not threatened, because the - * current node N has two black leaf children, but because - * N is red, the paths through each of its children have the same - * number of black nodes as the path through the leaf it replaced, which was - * black, and so this property remains satisfied.

- * - * @param N A node to be inserted or swapped. + * Get index. */ - XTree.prototype.insert_case2 = function (N) { - if (this.fetch_color(N.parent) == base.Color.BLACK) - return; - else - this.insert_case3(N); - }; - /** - *

N's parent ({@link XTreeNode.parent P}) and uncle - * ({@link XTreeNode.uncle U}) are red.

- * - *

If both the parent {@link XTreeNode.parent P} and the uncle {@link XTreeNode.uncle U} - * are red, then both of them can be repainted black - * and the grandparent {@link XTreeNode.grand_parent G} becomes red (to - * maintain property 5 (all paths from any given node to its leaf nodes contain the same number of - * black nodes)).

- * - *

Now, the current red node N has a - * black parent. Since any path through the parent or uncle must pass through - * the grandparent, the number of black nodes on these paths has not changed. - * - *

However, the grandparent {@link XTreeNode.grand_parent G} may now violate properties 2 (The - * root is black) or 4 (Both children of every red - * node are black) (property 4 possibly being violated since - * {@link XTreeNode.grand_parent G} may have a red parent).

- * - *

To fix this, the entire procedure is recursively performed on {@link XTreeNode.grand_parent G} - * from case 1. Note that this is a tail-recursive call, so it could be rewritten as a loop; since this is - * the only loop, and any rotations occur after this loop, this proves that a constant number of rotations - * occur.

- * - *

- * - * @param N A node to be inserted or swapped. - */ - XTree.prototype.insert_case3 = function (N) { - if (this.fetch_color(N.uncle) == base.Color.RED) { - N.parent.color = base.Color.BLACK; - N.uncle.color = base.Color.BLACK; - N.grand_parent.color = base.Color.RED; - this.insert_case1(N.grand_parent); - } - else { - this.insert_case4(N); - } - }; + get: function () { + return this.base_.index; + }, + enumerable: true, + configurable: true + }); + return DequeReverseIterator; + }(std.ReverseIterator)); + std.DequeReverseIterator = DequeReverseIterator; +})(std || (std = {})); +/// +// Standard exceptions +// +// This header defines the base class for all exceptions thrown by the elements of the standard library: +// {@link Exception}, along with several types and utilities to assist handling exceptions: +// +// @reference http://www.cplusplus.com/reference/exception/ +// @author Jeongho Nam +var std; +(function (std) { + /** + *

Function handling termination on exception

+ * + *

Calls the current terminate handler.

+ * + *

By default, the terminate handler calls abort. But this behavior can be redefined by calling + * {@link set_terminate}.

+ * + *

This function is automatically called when no catch handler can be found for a thrown exception, + * or for some other exceptional circumstance that makes impossible to continue the exception handling process.

+ * + *

This function is provided so that the terminate handler can be explicitly called by a program that needs to + * abnormally terminate, and works even if {@link set_terminate} has not been used to set a custom terminate handler + * (calling abort in this case).

+ */ + function terminate() { + if (terminate_handler != null) + terminate_handler(); + if (std.is_node() == true) + process.exit(); + else { + window.open("", "_self", ""); + window.close(); + } + } + std.terminate = terminate; + /** + *

Set terminate handler function.

+ * + *

A terminate handler function is a function automatically called when the exception handling process has + * to be abandoned for some reason. This happens when no catch handler can be found for a thrown exception, or for + * some other exceptional circumstance that makes impossible to continue the exception handling process.

+ * + *

Before this function is called by the program for the first time, the default behavior is to call abort.

+ * + *

A program may explicitly call the current terminate handler function by calling {@link terminate}.

+ * + * @param f Function that takes no parameters and returns no value (void). + */ + function set_terminate(f) { + terminate_handler = f; + if (std.is_node() == true) + process.on("uncaughtException", function (error) { + terminate_handler(); + }); + else + window.onerror = + function (message, filename, lineno, colno, error) { + terminate_handler(); + }; + } + std.set_terminate = set_terminate; + /** + *

Get terminate handler function.

+ * + *

The terminate handler function is automatically called when no catch handler can be found + * for a thrown exception, or for some other exceptional circumstance that makes impossible to continue the exception + * handling process.

+ * + *

If no such function has been set by a previous call to {@link set_terminate}, the function returns a + * null-pointer.

+ * + * @return If {@link set_terminate} has previously been called by the program, the function returns the current + * terminate handler function. Otherwise, it returns a null-pointer. + */ + function get_terminate() { + return terminate_handler; + } + std.get_terminate = get_terminate; + /* ========================================================= + + EXCEPTION + + LOGIC_ERROR + - DOMAIN_ERROR + - INVALID_ARGUMENT + - LENGTH_ERROR + - OUT_OF_RANGE + + RUNTIME_ERROR + - OVERFLOW_ERROR + - RANGE_ERROR + - SYSTEM_ERROR + - UNDERFLOW_ERROR + ========================================================= */ + /** + *

Standard exception class.

+ * + *

Base class for standard exceptions.

+ * + *

All objects thrown by components of the standard library are derived from this class. + * Therefore, all standard exceptions can be caught by catching this type by reference.

+ * + *

+ *

+ * + * @reference http://www.cplusplus.com/reference/exception/exception + * @author Jeongho Nam + */ + var Exception = (function (_super) { + __extends(Exception, _super); + function Exception(message) { + if (message === void 0) { message = ""; } + _super.call(this); + this.description = message; + } + /** + *

Get string identifying exception.

+ *

Returns a string that may be used to identify the exception.

+ * + *

The particular representation pointed by the returned value is implementation-defined. + * As a virtual function, derived classes may redefine this function so that specify value are + * returned.

+ */ + Exception.prototype.what = function () { + return this.description; + }; + Object.defineProperty(Exception.prototype, "message", { /** - *

N is added to right of left child of grandparent, or N is added to left - * of right child of grandparent ({@link XTreeNode.parent P} is red and - * {@link XTreeNode.uncle U} is black).

- * - *

The parent {@link XTreeNode.parent P} is red but the uncle - * {@link XTreeNode.uncle U} is black; also, the current node - * N is the right child of {@link XTreeNode.parent P}, and - * {@link XTreeNode.parent P} in turn is the left child of its parent - * {@link XTreeNode.grand_parent G}.

- * - *

In this case, a left rotation on {@link XTreeNode.parent P} that switches the roles of the - * current node N and its parent {@link XTreeNode.parent P} can be performed; then, - * the former parent node {@link XTreeNode.parent P} is dealt with using case 5 - * (relabeling N and {@link XTreeNode.parent P}) because property 4 (both children of - * every red node are black) is still violated.

- * - *

The rotation causes some paths (those in the sub-tree labelled "1") to pass through the node - * N where they did not before. It also causes some paths (those in the sub-tree labelled "3") - * not to pass through the node {@link XTreeNode.parent P} where they did before. However, both of - * these nodes are red, so property 5 (all paths from any given node to its leaf - * nodes contain the same number of black nodes) is not violated by the - * rotation.

- * - *

After this case has been completed, property 4 (both children of every red - * node are black) is still violated, but now we can resolve this by - * continuing to case 5.

- * - *

- * - * @param N A node to be inserted or swapped. + * @inheritdoc */ - XTree.prototype.insert_case4 = function (node) { - if (node == node.parent.right && node.parent == node.grand_parent.left) { - this.rotate_left(node.parent); - node = node.left; - } - else if (node == node.parent.left && node.parent == node.grand_parent.right) { - this.rotate_right(node.parent); - node = node.right; - } - this.insert_case5(node); - }; + get: function () { + return this.description; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Exception.prototype, "name", { /** - *

N is added to left of left child of grandparent, or N is added to right - * of right child of grandparent ({@link XTreeNode.parent P} is red and - * {@link XTreeNode.uncle U} is black).

- * - *

The parent {@link XTreeNode.parent P} is red but the uncle - * {@link XTreeNode.uncle U} is black, the current node N - * is the left child of {@link XTreeNode.parent P}, and {@link XTreeNode.parent P} is the left - * child of its parent {@link XTreeNode.grand_parent G}.

- * - *

In this case, a right rotation on {@link XTreeNode.grand_parent G} is performed; the result is a - * tree where the former parent {@link XTreeNode.parent P} is now the parent of both the current node - * N and the former grandparent {@link XTreeNode.grand_parent G}.

- * - *

{@link XTreeNode.grand_parent G} is known to be black, since its - * former child {@link XTreeNode.parent P} could not have been red otherwise - * (without violating property 4). Then, the colors of {@link XTreeNode.parent P} and - * {@link XTreeNode.grand_parent G} are switched, and the resulting tree satisfies property 4 (both - * children of every red node are black). Property 5 - * (all paths from any given node to its leaf nodes contain the same number of - * black nodes) also remains satisfied, since all paths that went through any - * of these three nodes went through {@link XTreeNode.grand_parent G} before, and now they all go - * through {@link XTreeNode.parent P}. In each case, this is the only - * black node of the three.

- * - *

- * - * @param N A node to be inserted or swapped. + * @inheritdoc */ - XTree.prototype.insert_case5 = function (node) { - node.parent.color = base.Color.BLACK; - node.grand_parent.color = base.Color.RED; - if (node == node.parent.left && node.parent == node.grand_parent.left) - this.rotate_right(node.grand_parent); - else - this.rotate_left(node.grand_parent); - }; - /* --------------------------------------------------------- - ERASE - --------------------------------------------------------- */ - /** - *

Erase an element with its node.

- * - *

In a regular binary search tree when deleting a node with two non-leaf children, we find either the - * maximum element in its left subtree (which is the in-order predecessor) or the minimum element in its - * right subtree (which is the in-order successor) and move its value into the node being deleted (as shown - * here). We then delete the node we copied the value from, which must have fewer than two non-leaf children. - * (Non-leaf children, rather than all children, are specified here because unlike normal binary search - * trees, red-black trees can have leaf nodes anywhere, so that all nodes are either internal nodes with - * two children or leaf nodes with, by definition, zero children. In effect, internal nodes having two leaf - * children in a red-black tree are like the leaf nodes in a regular binary search tree.) Because merely - * copying a value does not violate any red-black properties, this reduces to the problem of deleting a node - * with at most one non-leaf child. Once we have solved that problem, the solution applies equally to the - * case where the node we originally want to delete has at most one non-leaf child as to the case just - * considered where it has two non-leaf children.

- * - *

Therefore, for the remainder of this discussion we address the deletion of a node with at most one - * non-leaf child. We use the label M to denote the node to be deleted; C will denote a - * selected child of M, which we will also call "its child". If M does have a non-leaf child, - * call that its child, C; otherwise, choose either leaf as its child, C.

- * - *

If M is a red node, we simply replace it with its child C, - * which must be black by property 4. (This can only occur when M has - * two leaf children, because if the red node M had a - * black non-leaf child on one side but just a leaf child on the other side, - * then the count of black nodes on both sides would be different, thus the - * tree would violate property 5.) All paths through the deleted node will simply pass through one fewer - * red node, and both the deleted node's parent and child must be - * black, so property 3 (all leaves are black) - * and property 4 (both children of every red node are - * black) still hold.

- * - *

Another simple case is when M is black and C is - * red. Simply removing a black node could break - * Properties 4 (“Both children of every red node are - * black”) and 5 (“All paths from any given node to its leaf nodes contain the - * same number of black nodes”), but if we repaint C - * black, both of these properties are preserved.

- * - *

The complex case is when both M and C are black. (This - * can only occur when deleting a black node which has two leaf children, - * because if the black node M had a black - * non-leaf child on one side but just a leaf child on the other side, then the count of - * black nodes on both sides would be different, thus the tree would have been - * an invalid red-black tree by violation of property 5.) We begin by replacing M with its child - * C. We will relabel this child C (in its new position) N, and its sibling (its - * new parent's other child) {@link XTreeNode.sibling S}. ({@link XTreeNode.sibling S} was - * previously the sibling of M.)

- * - *

In the diagrams below, we will also use {@link XTreeNode.parent P} for N's new - * parent (M's old parent), SL for {@link XTreeNode.sibling S}'s left child, and - * SR for {@link XTreeNode.sibling S}'s right child ({@link XTreeNode.sibling S} cannot - * be a leaf because if M and C were black, then - * {@link XTreeNode.parent P}'s one subtree which included M counted two - * black-height and thus {@link XTreeNode.parent P}'s other subtree - * which includes {@link XTreeNode.sibling S} must also count two - * black-height, which cannot be the case if {@link XTreeNode.sibling S} - * is a leaf node).

- * - *

Notes

- *
    - *
  1. - * The label N will be used to denote the current node (colored - * black). In the diagrams N carries a blue contour. At the - * beginning, this is the replacement node and a leaf, but the entire procedure may also be applied - * recursively to other nodes (see case 3). In between some cases, the roles and labels of the nodes - * are exchanged, but in each case, every label continues to represent the same node it represented at - * the beginning of the case. - *
  2. - *
  3. - * If a node in the right (target) half of a diagram carries a blue contour it will become the current - * node in the next iteration and there the other nodes will be newly assigned relative to it. Any - * color shown in the diagram is either assumed in its case or implied by those assumptions. - * White represents an arbitrary color (either red or - * black), but the same in both halves of the diagram. - *
  4. - *
  5. - * A numbered triangle represents a subtree of unspecified depth. A black - * circle atop a triangle means that black-height of subtree is greater - * by one compared to subtree without this circle. - *
  6. - *
- * - *

If both N and its original parent are black, then - * deleting this original parent causes paths which proceed through N to have one fewer - * black node than paths that do not. As this violates property 5 (all paths - * from any given node to its leaf nodes contain the same number of black - * nodes), the tree must be rebalanced. There are several cases to consider:

- * - *
    - *
  1. N is the new root.
  2. - *
  3. {@link XTreeNode.sibling S} is red.
  4. - *
  5. - * {@link XTreeNode.parent P}, {@link XTreeNode.sibling S}, and - * {@link XTreeNode.sibling S}'s children are black.
  6. - *
  7. - * {@link XTreeNode.sibling S} and {@link XTreeNode.sibling S}'s children are - * black, but {@link XTreeNode.parent P} is - * red. - *
  8. - *
  9. - * {@link XTreeNode.sibling S} is black, - * {@link XTreeNode.sibling S}'s left child is red, - * {@link XTreeNode.sibling S}'s right child is black, and - * N is the left child of its parent. - *
  10. - *
  11. - * {@link XTreeNode.sibling S} is black, - * {@link XTreeNode.sibling S}'s right child is red, and - * N is the left child of its parent {@link XTreeNode.parent P}. - *
  12. - *
- * - *

Again, the function calls all use tail recursion, so the algorithm is in-place.

- * - *

In the algorithm above, all cases are chained in order, except in delete case 3 where it can recurse - * to case 1 back to the parent node: this is the only case where an iterative implementation will - * effectively loop. No more than h loops back to case 1 will occur (where h is the height of the tree). - * And because the probability for escalation decreases exponentially with each iteration the average - * removal cost is constant.

- * - *

Additionally, no tail recursion ever occurs on a child node, so the tail recursion loop can only - * move from a child back to its successive ancestors. If a rotation occurs in case 2 (which is the only - * possibility of rotation within the loop of cases 1–3), then the parent of the node N - * becomes red after the rotation and we will exit the loop. Therefore, at most one - * rotation will occur within this loop. Since no more than two additional rotations will occur after - * exiting the loop, at most three rotations occur in total.

- * - * @param val An element to erase. - */ - XTree.prototype.erase = function (val) { - var node = this.find(val); - if (node == null || this.is_equal_to(val, node.value) == false) - return; - if (node.left != null && node.right != null) { - var pred = this.fetch_maximum(node.left); - node.value = pred.value; - node = pred; - } - var child = (node.right == null) ? node.left : node.right; - if (this.fetch_color(node) == base.Color.BLACK) { - node.color = this.fetch_color(child); - this.erase_case1(node); - } - this.replace_node(node, child); - }; - /** - *

N is the new root.

- * - *

In this case, we are done. We removed one black node from every path, - * and the new root is black, so the properties are preserved.

- * - *

Note

- *

In cases 2, 5, and 6, we assume N is the left child of its parent - * {@link XTreeNode.parent P}. If it is the right child, left and right should be reversed throughout - * these three cases. Again, the code examples take both cases into account.

- * - * @param N A node to be erased or swapped. - */ - XTree.prototype.erase_case1 = function (N) { - if (N.parent == null) - return; - else - this.erase_case2(N); - }; - /** - *

{@link XTreeNode.sibling S} is red.

- * - *

- * - *

In this case we reverse the colors of {@link XTreeNode.parent P} and - * {@link XTreeNode.sibling S}, and then rotate left at {@link XTreeNode.parent P}, turning - * {@link XTreeNode.sibling S} into N's grandparent.

- * - *

Note that {@link XTreeNode.parent P} has to be black as it had a - * red child. The resulting subtree has a path short one - * black node so we are not done. Now N has a - * black sibling and a red parent, so we can proceed - * to step 4, 5, or 6. (Its new sibling is black because it was once the child - * of the red {@link XTreeNode.sibling S}.) In later cases, we will re-label - * N's new sibling as {@link XTreeNode.sibling S}.

- * - * @param N A node to be erased or swapped. - */ - XTree.prototype.erase_case2 = function (N) { - if (this.fetch_color(N.sibling) == base.Color.RED) { - N.parent.color = base.Color.RED; - N.sibling.color = base.Color.BLACK; - if (N == N.parent.left) - this.rotate_left(N.parent); - else - this.rotate_right(N.parent); - } - this.erase_case3(N); - }; - /** - *

{@link XTreeNode.parent P}, {@link XTreeNode.sibling S}, and {@link XTreeNode.sibling - * S}'s children are black.

- * - *

- * - *

In this case, we simply repaint {@link XTreeNode.sibling S} red. The - * result is that all paths passing through {@link XTreeNode.sibling S}, which are precisely those - * paths not passing through N, have one less black node. - * Because deleting N's original parent made all paths passing through N have - * one less black node, this evens things up.

- * - *

However, all paths through {@link XTreeNode.parent P} now have one fewer - * black node than paths that do not pass through - * {@link XTreeNode.parent P}, so property 5 (all paths from any given node to its leaf nodes contain - * the same number of black nodes) is still violated.

- * - *

To correct this, we perform the rebalancing procedure on {@link XTreeNode.parent P}, starting - * at case 1.

- * - * @param N A node to be erased or swapped. - */ - XTree.prototype.erase_case3 = function (N) { - if (this.fetch_color(N.parent) == base.Color.BLACK && - this.fetch_color(N.sibling) == base.Color.BLACK && - this.fetch_color(N.sibling.left) == base.Color.BLACK && - this.fetch_color(N.sibling.right) == base.Color.BLACK) { - N.sibling.color = base.Color.RED; - this.erase_case1(N.parent); - } - else - this.erase_case4(N); - }; - /** - *

{@link XTreeNode.sibling S} and {@link XTreeNode.sibling S}'s children are - * black, but {@link XTreeNode.parent P} is red.

- * - *

- * - *

In this case, we simply exchange the colors of {@link XTreeNode.sibling S} and - * {@link XTreeNode.parent P}. This does not affect the number of black - * nodes on paths going through {@link XTreeNode.sibling S}, but it does add one to the number of - * black nodes on paths going through N, making up for the - * deleted black node on those paths.

- * - * @param N A node to be erased or swapped. - */ - XTree.prototype.erase_case4 = function (N) { - if (this.fetch_color(N.parent) == base.Color.RED && - N.sibling != null && - this.fetch_color(N.sibling) == base.Color.BLACK && - this.fetch_color(N.sibling.left) == base.Color.BLACK && - this.fetch_color(N.sibling.right) == base.Color.BLACK) { - N.sibling.color = base.Color.RED; - N.parent.color = base.Color.BLACK; - } - else - this.erase_case5(N); - }; - /** - *

{@link XTreeNode.sibling S} is black, {@link XTreeNode.sibling S}'s - * left child is red, {@link XTreeNode.sibling S}'s right child is - * black, and N is the left child of its parent.

- * - *

- * - *

In this case we rotate right at {@link XTreeNode.sibling S}, so that - * {@link XTreeNode.sibling S}'s left child becomes {@link XTreeNode.sibling S}'s parent and - * N's new sibling. We then exchange the colors of {@link XTreeNode.sibling S} and its - * new parent.

- * - *

All paths still have the same number of black nodes, but now - * N has a black sibling whose right child is - * red, so we fall into case 6. Neither N nor its parent are affected - * by this transformation. (Again, for case 6, we relabel N's new sibling as - * {@link XTreeNode.sibling S}.)

- * - * @param N A node to be erased or swapped. - */ - XTree.prototype.erase_case5 = function (N) { - if (N == N.parent.left && - N.sibling != null && - this.fetch_color(N.sibling) == base.Color.BLACK && - this.fetch_color(N.sibling.left) == base.Color.RED && - this.fetch_color(N.sibling.right) == base.Color.BLACK) { - N.sibling.color = base.Color.RED; - N.sibling.left.color = base.Color.BLACK; - this.rotate_right(N.sibling); - } - else if (N == N.parent.right && - N.sibling != null && - this.fetch_color(N.sibling) == base.Color.BLACK && - this.fetch_color(N.sibling.left) == base.Color.BLACK && - this.fetch_color(N.sibling.right) == base.Color.RED) { - N.sibling.color = base.Color.RED; - N.sibling.right.color = base.Color.BLACK; - this.rotate_left(N.sibling); - } - }; - /** - *

{@link XTreeNode.sibling S} is black, - * {@link XTreeNode.sibling S}'s right child is red, and N is - * the left child of its parent {@link XTreeNode.parent P}.

- * - *

In this case we rotate left at {@link XTreeNode.parent P}, so that - * {@link XTreeNode.sibling S} becomes the parent of {@link XTreeNode.parent P} and - * {@link XTreeNode.sibling S}'s right child. We then exchange the colors of - * {@link XTreeNode.parent P} and {@link XTreeNode.sibling S}, and make - * {@link XTreeNode.sibling S}'s right child black.

- * - *

The subtree still has the same color at its root, so Properties 4 (Both children of every - * red node are black) and 5 (All paths from any - * given node to its leaf nodes contain the same number of black nodes) are - * not violated. However, N now has one additional black - * ancestor: either {@link XTreeNode.parent P} has become black, or it - * was black and {@link XTreeNode.sibling S} was added as a - * black grandparent.

- * - *

Thus, the paths passing through N pass through one additional - * black node.

- * - *

- * - *

Meanwhile, if a path does not go through N, then there are two possibilities:

- *
    - *
  1. - * It goes through N's new sibling SL, a node with arbitrary color and the root of - * the subtree labeled 3 (s. diagram). Then, it must go through {@link XTreeNode.sibling S} and - * {@link XTreeNode.parent P}, both formerly and currently, as they have only exchanged colors - * and places. Thus the path contains the same number of black nodes. - *
  2. - *
  3. - * It goes through N's new uncle, {@link XTreeNode.sibling S}'s right child. Then, - * it formerly went through {@link XTreeNode.sibling S}, {@link XTreeNode.sibling S}'s - * parent, and {@link XTreeNode.sibling S}'s right child SR (which was - * red), but now only goes through {@link XTreeNode.sibling S}, which - * has assumed the color of its former parent, and {@link XTreeNode.sibling S}'s right child, - * which has changed from red to black (assuming - * {@link XTreeNode.sibling S}'s color: black). The net effect is - * that this path goes through the same number of black nodes. - *
  4. - *
- * - *

Either way, the number of black nodes on these paths does not change. - * Thus, we have restored Properties 4 (Both children of every red node are - * black) and 5 (All paths from any given node to its leaf nodes contain the - * same number of black nodes). The white node in the diagram can be either - * red or black, but must refer to the same color - * both before and after the transformation.

- * - * @param N A node to be erased or swapped. - */ - XTree.prototype.erase_case6 = function (node) { - node.sibling.color = this.fetch_color(node.parent); - node.parent.color = base.Color.BLACK; - if (node == node.parent.left) { - node.sibling.right.color = base.Color.BLACK; - this.rotate_left(node.parent); - } - else { - node.sibling.left.color = base.Color.BLACK; - this.rotate_right(node.parent); - } - }; - /* --------------------------------------------------------- - ROTATION - --------------------------------------------------------- */ - /** - * Rotate a node left. - * - * @param node Node to rotate left. - */ - XTree.prototype.rotate_left = function (node) { - var right = node.right; - this.replace_node(node, right); - node.right = right.left; - if (right.left != null) - right.left.parent = node; - right.left = node; - node.parent = right; - }; - /** - * Rotate a node to right. - * - * @param node A node to rotate right. - */ - XTree.prototype.rotate_right = function (node) { - var left = node.left; - this.replace_node(node, left); - node.left = left.right; - if (left.right != null) - left.right.parent = node; - left.right = node; - node.parent = left; - }; - /** - * Replace a node. - * - * @param oldNode Ordinary node to be replaced. - * @param newNode Target node to replace. - */ - XTree.prototype.replace_node = function (oldNode, newNode) { - if (oldNode.parent == null) - this.root_ = newNode; - else { - if (oldNode == oldNode.parent.left) - oldNode.parent.left = newNode; - else - oldNode.parent.right = newNode; - } - if (newNode != null) - newNode.parent = oldNode.parent; - }; - /* --------------------------------------------------------- - COLOR - --------------------------------------------------------- */ - /** - * Fetch color from a node. - * - * @param node A node to fetch color. - * @retur color. - */ - XTree.prototype.fetch_color = function (node) { - if (node == null) - return base.Color.BLACK; - else - return node.color; - }; - return XTree; - }()); - base.XTree = XTree; - })(base = std.base || (std.base = {})); -})(std || (std = {})); -/// -/// -var std; -(function (std) { - var base; - (function (base) { - /** - *

A red-black tree storing {@link MapIterator MapIterators}.

- * - *

- *

- * - * @author Jeongho Nam - */ - var PairTree = (function (_super) { - __extends(PairTree, _super); - /* --------------------------------------------------------- - CONSTRUCTOR - --------------------------------------------------------- */ - /** - * Default Constructor. - */ - function PairTree(map, compare) { - if (compare === void 0) { compare = std.less; } - _super.call(this); - this.map_ = map; - this.compare_ = compare; - } - PairTree.prototype.find = function (val) { - if (val instanceof std.MapIterator && val.first instanceof std.SetIterator == false) - return _super.prototype.find.call(this, val); - else - return this.find_by_key(val); - }; - /** - * @hidden - */ - PairTree.prototype.find_by_key = function (key) { - if (this.root_ == null) - return null; - var node = this.root_; - while (true) { - var newNode = null; - if (std.equal_to(key, node.value.first)) - break; // EQUALS, MEANS MATCHED, THEN TERMINATE - else if (this.compare_(key, node.value.first)) - newNode = node.left; // LESS, THEN TO THE LEFT - else - newNode = node.right; // GREATER, THEN TO THE RIGHT - // ULTIL CHILD NODE EXISTS - if (newNode == null) - break; - // SHIFT A NEW NODE TO THE NODE TO BE RETURNED - node = newNode; - } - return node; - }; - /* --------------------------------------------------------- - BOUNDS - --------------------------------------------------------- */ - /** - *

Return iterator to lower bound.

- * - *

Returns an iterator pointing to the first element in the container whose key is not considered to - * go before k (i.e., either it is equivalent or goes after).

- * - *

The function uses its internal comparison object (key_comp) to determine this, returning an - * iterator to the first element for which key_comp(k, element_key) would return false.

- * - *

If the {@link ITreeMap} class is instantiated with the default comparison type ({@link less}), - * the function returns an iterator to the first element whose key is not less than k

. - * - *

A similar member function, {@link upper_bound}, has the same behavior as {@link lower_bound}, except - * in the case that the {@link ITreeMap} contains an element with a key equivalent to k: In this - * case, {@link lower_bound} returns an iterator pointing to that element, whereas {@link upper_bound} - * returns an iterator pointing to the next element.

- * - * @param k Key to search for. - * - * @return An iterator to the the first element in the container whose key is not considered to go before - * k, or {@link ITreeMap.end} if all keys are considered to go before k. - */ - PairTree.prototype.lower_bound = function (key) { - var node = this.find(key); - if (node == null) - return this.map_.end(); - else if (this.compare_(node.value.first, key)) - return node.value.next(); - else { - var it = node.value; - while (!std.equal_to(it, this.map_.end()) && this.compare_(it.first, key)) - it = it.next(); - return it; - } - }; - /** - *

Return iterator to upper bound.

- * - *

Returns an iterator pointing to the first element in the container whose key is considered to - * go after k

. - * - *

The function uses its internal comparison object (key_comp) to determine this, returning an - * iterator to the first element for which key_comp(k, element_key) would return true.

- * - *

If the {@link ITreeMap} class is instantiated with the default comparison type ({@link less}), - * the function returns an iterator to the first element whose key is greater than k

. - * - *

A similar member function, {@link lower_bound}, has the same behavior as {@link upper_bound}, except - * in the case that the map contains an element with a key equivalent to k: In this case - * {@link lower_bound} returns an iterator pointing to that element, whereas {@link upper_bound} returns an - * iterator pointing to the next element.

- * - * @param k Key to search for. - * - * @return An iterator to the the first element in the container whose key is considered to go after - * k, or {@link TreeMap.end end} if no keys are considered to go after k. - */ - PairTree.prototype.upper_bound = function (key) { - var node = this.find(key); - if (node == null) - return this.map_.end(); - else { - var it = node.value; - while (!std.equal_to(it, this.map_.end()) && (std.equal_to(it.first, key) || this.compare_(it.first, key))) - it = it.next(); - return it; - } - }; - /** - *

Get range of equal elements.

- * - *

Returns the bounds of a range that includes all the elements in the container which have a key - * equivalent to k

. - * - *

If no matches are found, the range returned has a length of zero, with both iterators pointing to - * the first element that has a key considered to go after k according to the container's internal - * comparison object (key_comp).

- * - *

Two keys are considered equivalent if the container's comparison object returns false reflexively - * (i.e., no matter the order in which the keys are passed as arguments).

- * - * @param k Key to search for. - * - * @return The function returns a {@link Pair}, whose member {@link Pair.first} is the lower bound of - * the range (the same as {@link lower_bound}), and {@link Pair.second} is the upper bound - * (the same as {@link upper_bound}). - */ - PairTree.prototype.equal_range = function (key) { - return std.make_pair(this.lower_bound(key), this.upper_bound(key)); - }; - /* --------------------------------------------------------- - COMPARISON - --------------------------------------------------------- */ - /** - *

Return key comparison function.

- * - *

Returns a references of the comparison function used by the container to compare keys.

- * - *

The comparison object of a {@link ITreeMap tree-map object} is set on - * {@link TreeMap.constructor construction}. Its type (Key) is the last parameter of the - * {@link ITreeMap.constructor constructors}. By default, this is a {@link less} function, which returns the same - * as operator<.

- * - *

This function determines the order of the elements in the container: it is a function pointer that takes - * two arguments of the same type as the element keys, and returns true if the first argument - * is considered to go before the second in the strict weak ordering it defines, and false otherwise. - *

- * - *

Two keys are considered equivalent if {@link key_comp} returns false reflexively (i.e., no - * matter the order in which the keys are passed as arguments).

- * - * @return The comparison function. - */ - PairTree.prototype.key_comp = function () { - return this.compare_; - }; - /** - *

Return value comparison function.

- * - *

Returns a comparison function that can be used to compare two elements to get whether the key of the first - * one goes before the second.

- * - *

The arguments taken by this function object are of member type std.Pair (defined in - * {@link ITreeMap}), but the mapped type (T) part of the value is not taken into consideration in this - * comparison.

- * - *

This comparison class returns true if the {@link Pair.first key} of the first argument - * is considered to go before that of the second (according to the strict weak ordering specified by the - * container's comparison function, {@link key_comp}), and false otherwise.

- * - * @return The comparison function for element values. - */ - PairTree.prototype.value_comp = function () { - var compare = this.compare_; - var fn = function (x, y) { - return compare(x.first, y.first); - }; - return fn; - }; - /** - * @inheritdoc - */ - PairTree.prototype.is_equal_to = function (left, right) { - return std.equal_to(left.first, right.first); - }; - /** - * @inheritdoc - */ - PairTree.prototype.is_less = function (left, right) { - return this.compare_(left.first, right.first); - }; - return PairTree; - }(base.XTree)); - base.PairTree = PairTree; - })(base = std.base || (std.base = {})); -})(std || (std = {})); -/// -/// -var std; -(function (std) { - var base; - (function (base) { - /** - *

A red-black Tree storing {@link SetIterator SetIterators}.

- * - *

- *

- * - * @author Jeongho Nam - */ - var AtomicTree = (function (_super) { - __extends(AtomicTree, _super); - /* --------------------------------------------------------- - CONSTRUCTOR - --------------------------------------------------------- */ - /** - * Default Constructor. - */ - function AtomicTree(set, compare) { - if (compare === void 0) { compare = std.less; } - _super.call(this); - this.set_ = set; - this.compare_ = compare; - } - AtomicTree.prototype.find = function (val) { - if (val instanceof std.SetIterator && val.value instanceof std.SetIterator == false) - return _super.prototype.find.call(this, val); - else - return this.find_by_val(val); - }; - /** - * @hidden - */ - AtomicTree.prototype.find_by_val = function (val) { - if (this.root_ == null) - return null; - var node = this.root_; - while (true) { - var newNode = null; - if (std.equal_to(val, node.value.value)) - break; // EQUALS, MEANS MATCHED, THEN TERMINATE - else if (this.compare_(val, node.value.value)) - newNode = node.left; // LESS, THEN TO THE LEFT - else - newNode = node.right; // GREATER, THEN TO THE RIGHT - // ULTIL CHILD NODE EXISTS - if (newNode == null) - break; - // SHIFT A NEW NODE TO THE NODE TO BE RETURNED - node = newNode; - } - return node; - }; - /* --------------------------------------------------------- - BOUNDS - --------------------------------------------------------- */ - /** - *

Return iterator to lower bound.

- * - *

Returns an iterator pointing to the first element in the container which is not considered to - * go before val (i.e., either it is equivalent or goes after).

- * - *

The function uses its internal comparison object (key_comp) to determine this, returning an - * iterator to the first element for which key_comp(element,val) would return false.

- * - *

If the {@link ITreeSet} class is instantiated with the default comparison type ({@link less}), - * the function returns an iterator to the first element that is not less than val.

- - *

A similar member function, {@link upper_bound}, has the same behavior as {@link lower_bound}, except - * in the case that the {@link ITreeSet} contains elements equivalent to val: In this case - * {@link lower_bound} returns an iterator pointing to the first of such elements, whereas - * {@link upper_bound} returns an iterator pointing to the element following the last.

- * - * @param val Value to compare. - * - * @return An iterator to the the first element in the container which is not considered to go before - * val, or {@link ITreeSet.end} if all elements are considered to go before val. - */ - AtomicTree.prototype.lower_bound = function (val) { - var node = this.find(val); - if (node == null) - return this.set_.end(); - else if (std.equal_to(node.value.value, val)) - return node.value; - else { - var it = node.value; - while (!std.equal_to(it, this.set_.end()) && this.compare_(it.value, val)) - it = it.next(); - return it; - } - }; - /** - *

Return iterator to upper bound.

- * - *

Returns an iterator pointing to the first element in the container which is considered to go after - * val.

- - *

The function uses its internal comparison object (key_comp) to determine this, returning an - * iterator to the first element for which key_comp(val,element) would return true.

- - *

If the {@code ITreeSet} class is instantiated with the default comparison type (less), the - * function returns an iterator to the first element that is greater than val.

- * - *

A similar member function, {@link lower_bound}, has the same behavior as {@link upper_bound}, except - * in the case that the {@ITreeSet} contains elements equivalent to val: In this case - * {@link lower_bound} returns an iterator pointing to the first of such elements, whereas - * {@link upper_bound} returns an iterator pointing to the element following the last.

- * - * @param val Value to compare. - * - * @return An iterator to the the first element in the container which is considered to go after - * val, or {@link TreeSet.end end} if no elements are considered to go after val. - */ - AtomicTree.prototype.upper_bound = function (val) { - var node = this.find(val); - if (node == null) - return this.set_.end(); - else { - var it = node.value; - while (!std.equal_to(it, this.set_.end()) && (std.equal_to(it.value, val) || this.compare_(it.value, val))) - it = it.next(); - return it; - } - }; - /** - *

Get range of equal elements.

- * - *

Returns the bounds of a range that includes all the elements in the container that are equivalent - * to val.

- * - *

If no matches are found, the range returned has a length of zero, with both iterators pointing to - * the first element that is considered to go after val according to the container's - * internal comparison object (key_comp).

- * - *

Two elements of a multiset are considered equivalent if the container's comparison object returns - * false reflexively (i.e., no matter the order in which the elements are passed as arguments).

- * - * @param key Value to search for. - * - * @return The function returns a {@link Pair}, whose member {@link Pair.first} is the lower bound of - * the range (the same as {@link lower_bound}), and {@link Pair.second} is the upper bound - * (the same as {@link upper_bound}). - */ - AtomicTree.prototype.equal_range = function (val) { - return std.make_pair(this.lower_bound(val), this.upper_bound(val)); - }; - /* --------------------------------------------------------- - COMPARISON - --------------------------------------------------------- */ - /** - *

Return comparison function.

- * - *

Returns a copy of the comparison function used by the container.

- * - *

By default, this is a {@link less} object, which returns the same as operator<.

- * - *

This object determines the order of the elements in the container: it is a function pointer or a function - * object that takes two arguments of the same type as the container elements, and returns true if - * the first argument is considered to go before the second in the strict weak ordering it - * defines, and false otherwise.

- * - *

Two elements of a {@link ITreeSet} are considered equivalent if {@link key_comp} returns false - * reflexively (i.e., no matter the order in which the elements are passed as arguments).

- * - *

In {@link ITreeSet} containers, the keys to sort the elements are the values (T) themselves, - * therefore {@link key_comp} and its sibling member function {@link value_comp} are equivalent.

- * - * @return The comparison function. - */ - AtomicTree.prototype.key_comp = function () { - return this.compare_; - }; - /** - *

Return comparison function.

- * - *

Returns a copy of the comparison function used by the container.

- * - *

By default, this is a {@link less} object, which returns the same as operator<.

- * - *

This object determines the order of the elements in the container: it is a function pointer or a function - * object that takes two arguments of the same type as the container elements, and returns true if - * the first argument is considered to go before the second in the strict weak ordering it - * defines, and false otherwise.

- * - *

Two elements of a {@link ITreeSet} are considered equivalent if {@link key_comp} returns false - * reflexively (i.e., no matter the order in which the elements are passed as arguments).

- * - *

In {@link ITreeSet} containers, the keys to sort the elements are the values (T) themselves, - * therefore {@link key_comp} and its sibling member function {@link value_comp} are equivalent.

- * - * @return The comparison function. - */ - AtomicTree.prototype.value_comp = function () { - return this.compare_; - }; - /** - * @inheritdoc - */ - AtomicTree.prototype.is_equal_to = function (left, right) { - return std.equal_to(left, right); - }; - /** - * @inheritdoc - */ - AtomicTree.prototype.is_less = function (left, right) { - return this.compare_(left.value, right.value); - }; - return AtomicTree; - }(base.XTree)); - base.AtomicTree = AtomicTree; - })(base = std.base || (std.base = {})); -})(std || (std = {})); -/// -/// -var std; -(function (std) { - var base; - (function (base) { - /** - *

An abstract unique-map.

- * - *

{@link UniqueMap UniqueMaps} are associative containers that store elements formed by a combination of a - * key value (Key) and a mapped value (T), and which allows for fast retrieval of - * individual elements based on their keys.

- * - *

In a {@link MapContainer}, the key values are generally used to uniquely identify the elements, - * while the mapped values store the content associated to this key. The types of key and - * mapped value may differ, and are grouped together in member type value_type, which is a - * {@link Pair} type combining both:

- * - *

typedef pair value_type;

- * - *

{@link UniqueMap} stores elements, keeps sequence and enables indexing by inserting elements into a - * {@link List} and registering {@link ListIterator iterators} of the {@link data_ list container} to an index - * table like {@link RBTree tree} or {@link HashBuckets hash-table}.

- * - *

- *

- * - *

Container properties

- *
- *
Associative
- *
- * Elements in associative containers are referenced by their key and not by their absolute position - * in the container. - *
- * - *
Map
- *
- * Each element associates a key to a mapped value: - * Keys are meant to identify the elements whose main content is the mapped value. - *
- * - *
Unique keys
- *
No two elements in the container can have equivalent keys.
- *
- * - * @param Type of the keys. Each element in a map is uniquely identified by its key value. - * @param Type of the mapped value. Each element in a map stores some data as its mapped value. - * - * @author Jeongho Nam - */ - var UniqueMap = (function (_super) { - __extends(UniqueMap, _super); - function UniqueMap() { - _super.apply(this, arguments); - } - /* --------------------------------------------------------- - ACCESSORS - --------------------------------------------------------- */ - /** - * @inheritdoc - */ - UniqueMap.prototype.count = function (key) { - return this.find(key).equal_to(this.end()) ? 0 : 1; - }; - /** - *

Get an element

- * - *

Returns a reference to the mapped value of the element identified with key.

- * - * @param key Key value of the element whose mapped value is accessed. - * - * @throw exception out of range - * - * @return A reference object of the mapped value (_Ty) - */ - UniqueMap.prototype.get = function (key) { - var it = this.find(key); - if (it.equal_to(this.end()) == true) - throw new std.OutOfRange("unable to find the matched key."); - return it.second; - }; - /** - *

Set an item as the specified identifier.

- * - *

If the identifier is already in map, change value of the identifier. If not, then insert the object - * with the identifier.

- * - * @param key Key value of the element whose mapped value is accessed. - * @param val Value, the item. - */ - UniqueMap.prototype.set = function (key, val) { - this.insert_or_assign(key, val); - }; - UniqueMap.prototype.extract = function (param) { - if (param instanceof std.MapIterator) - return this.extract_by_iterator(param); - else if (param instanceof std.MapReverseIterator) - return this.extract_by_reverse_iterator(param); - else - return this.extract_by_key(param); - }; - /** - * @hidden - */ - UniqueMap.prototype.extract_by_key = function (key) { - var it = this.find(key); - if (it.equal_to(this.end()) == true) - throw new std.OutOfRange("No such key exists."); - var ret = it.value; - this.erase(it); - return ret; - }; - /** - * @hidden - */ - UniqueMap.prototype.extract_by_iterator = function (it) { - if (it.equal_to(this.end()) == true || this.has(it.first) == false) - return this.end(); - this.erase(it); - return it; - }; - /** - * @hidden - */ - UniqueMap.prototype.extract_by_reverse_iterator = function (it) { - this.extract_by_iterator(it.base().next()); - return it; - }; - UniqueMap.prototype.emplace = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i - 0] = arguments[_i]; - } - if (args.length == 1) - return this._Insert_by_pair(args[0]); - else - return this._Insert_by_pair(std.make_pair(args[0], args[1])); - }; - UniqueMap.prototype.insert = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i - 0] = arguments[_i]; - } - return _super.prototype.insert.apply(this, args); - }; - UniqueMap.prototype.insert_or_assign = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i - 0] = arguments[_i]; - } - if (args.length == 2) { - return this.insert_or_assign_with_key_value(args[0], args[1]); - } - else if (args.length == 3) { - var ret = void 0; - var is_reverse_iterator = false; - // REVERSE_ITERATOR TO ITERATOR - if (args[0] instanceof std.MapReverseIterator) { - is_reverse_iterator = true; - args[0] = args[0].base().prev(); - } - // INSERT OR ASSIGN AN ELEMENT - ret = this.insert_or_assign_with_hint(args[0], args[1], args[2]); - // RETURN BRANCHES - if (is_reverse_iterator == true) - return new std.MapReverseIterator(ret.next()); - else - return ret; - } - }; - /** - * @hidden - */ - UniqueMap.prototype.insert_or_assign_with_key_value = function (key, value) { - var it = this.find(key); - if (it.equal_to(this.end()) == true) - return this._Insert_by_pair(std.make_pair(key, value)); - else { - it.second = value; - return std.make_pair(it, false); - } - }; - /** - * @hidden - */ - UniqueMap.prototype.insert_or_assign_with_hint = function (hint, key, value) { - return this.insert_or_assign_with_key_value(key, value).first; - }; - return UniqueMap; - }(base.MapContainer)); - base.UniqueMap = UniqueMap; - })(base = std.base || (std.base = {})); -})(std || (std = {})); -/// -/// -var std; -(function (std) { - var base; - (function (base) { - /** - *

An abstract set.

- * - *

{@link SetContainer SetContainers} are containers that store elements allowing fast retrieval of - * individual elements based on their value.

- * - *

In an {@link SetContainer}, the value of an element is at the same time its key, used to uniquely - * identify it. Keys are immutable, therefore, the elements in an {@link SetContainer} cannot be modified - * once in the container - they can be inserted and removed, though.

- * - *

{@link SetContainer} stores elements, keeps sequence and enables indexing by inserting elements into a - * {@link List} and registering {@link ListIterator iterators} of the {@link data_ list container} to an index - * table like {@link RBTree tree} or {@link HashBuckets hash-table}.

- * - *

- *

- * - *

Container properties

- *
- *
Associative
- *
- * Elements in associative containers are referenced by their key and not by their absolute - * position in the container. - *
- * - *
Set
- *
The value of an element is also the key used to identify it.
- * - *
Unique keys
- *
No two elements in the container can have equivalent keys.
- *
- * - * @param Type of the elements. Each element in a {@link SetContainer} container is also identified - * by this value (each value is itself also the element's key). - * - * @author Jeongho Nam - */ - var UniqueSet = (function (_super) { - __extends(UniqueSet, _super); - function UniqueSet() { - _super.apply(this, arguments); - } - /* --------------------------------------------------------- - ACCESSOR - --------------------------------------------------------- */ - /** - * @inheritdoc - */ - UniqueSet.prototype.count = function (key) { - return this.find(key).equal_to(this.end()) ? 0 : 1; - }; - UniqueSet.prototype.extract = function (param) { - if (param instanceof std.SetIterator) - return this.extract_by_iterator(param); - else if (param instanceof std.SetReverseIterator) - return this.extract_by_reverse_iterator(param); - else - return this.extract_by_key(param); - }; - /** - * @hidden - */ - UniqueSet.prototype.extract_by_key = function (val) { - var it = this.find(val); - if (it.equal_to(this.end()) == true) - throw new std.OutOfRange("No such key exists."); - this.erase(val); - return val; - }; - /** - * @hidden - */ - UniqueSet.prototype.extract_by_iterator = function (it) { - if (it.equal_to(this.end()) == true || this.has(it.value) == false) - return this.end(); - this.erase(it); - return it; - }; - /** - * @hidden - */ - UniqueSet.prototype.extract_by_reverse_iterator = function (it) { - this.extract_by_iterator(it.base().next()); - return it; - }; - UniqueSet.prototype.insert = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i - 0] = arguments[_i]; - } - return _super.prototype.insert.apply(this, args); - }; - return UniqueSet; - }(base.SetContainer)); - base.UniqueSet = UniqueSet; - })(base = std.base || (std.base = {})); -})(std || (std = {})); -/// -var std; -(function (std) { - var base; - (function (base) { - /** - *

A node in an XTree.

- * - * @param Type of elements. - * - * @inventor Rudolf Bayer - * @author Migrated by Jeongho Nam - */ - var XTreeNode = (function () { - /* --------------------------------------------------------- - CONSTRUCTORS - --------------------------------------------------------- */ - /** - * Construct from value and color of node. - * - * @param value Value to be stored in. - * @param color Color of the node, red or black. - */ - function XTreeNode(value, color) { - this.value = value; - this.color = color; - this.parent = null; - this.left = null; - this.right = null; - } - Object.defineProperty(XTreeNode.prototype, "grand_parent", { - /** - * Get grand-parent. - */ - get: function () { - return this.parent.parent; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(XTreeNode.prototype, "sibling", { - /** - * Get sibling, opposite side node in same parent. - */ - get: function () { - if (this == this.parent.left) - return this.parent.right; - else - return this.parent.left; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(XTreeNode.prototype, "uncle", { - /** - * Get uncle, parent's sibling. - */ - get: function () { - return this.parent.sibling; - }, - enumerable: true, - configurable: true - }); - return XTreeNode; - }()); - base.XTreeNode = XTreeNode; - })(base = std.base || (std.base = {})); -})(std || (std = {})); -/// -/// -/// -var std; -(function (std) { - /** - *

Double ended queue.

- * - *

{@link Deque} (usually pronounced like "deck") is an irregular acronym of - * double-ended queue. Double-ended queues are sequence containers with dynamic sizes that can be - * expanded or contracted on both ends (either its front or its back).

- * - *

Specific libraries may implement deques in different ways, generally as some form of dynamic array. But in any - * case, they allow for the individual elements to be accessed directly through random access iterators, with storage - * handled automatically by expanding and contracting the container as needed.

- * - *

Therefore, they provide a functionality similar to vectors, but with efficient insertion and deletion of - * elements also at the beginning of the sequence, and not only at its end. But, unlike {@link Vector Vectors}, - * {@link Deque Deques} are not guaranteed to store all its elements in contiguous storage locations: accessing - * elements in a deque by offsetting a pointer to another element causes undefined behavior.

- * - *

Both {@link Vector}s and {@link Deque}s provide a very similar interface and can be used for similar purposes, - * but internally both work in quite different ways: While {@link Vector}s use a single array that needs to be - * occasionally reallocated for growth, the elements of a {@link Deque} can be scattered in different chunks of - * storage, with the container keeping the necessary information internally to provide direct access to any of its - * elements in constant time and with a uniform sequential interface (through iterators). Therefore, - * {@link Deque Deques} are a little more complex internally than {@link Vector}s, but this allows them to grow more - * efficiently under certain circumstances, especially with very long sequences, where reallocations become more - * expensive.

- * - *

For operations that involve frequent insertion or removals of elements at positions other than the beginning or - * the end, {@link Deque Deques} perform worse and have less consistent iterators and references than - * {@link List Lists}.

- * - *

- * - *

- * - *

Container properties

- *
- *
Sequence
- *
Elements in sequence containers are ordered in a strict linear sequence. Individual elements - * are accessed by their position in this sequence.
- * - *
Dynamic array
- *
Generally implemented as a dynamic array, it allows direct access to any element in the - * sequence and provides relatively fast addition/removal of elements at the beginning or the end - * of the sequence.
- *
- * - * @param Type of the elements. - * - * @reference http://www.cplusplus.com/reference/deque/deque/ - * @author Jeongho Nam - */ - var Deque = (function (_super) { - __extends(Deque, _super); - function Deque() { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i - 0] = arguments[_i]; - } - _super.call(this); - if (args.length == 0) { - this.clear(); - } - if (args.length == 1 && args[0] instanceof Array) { - var array = args[0]; - this.clear(); - this.push.apply(this, array); - } - else if (args.length == 1 && args[0] instanceof Deque) { - var container = args[0]; - this.assign(container.begin(), container.end()); - } - else if (args.length == 2 && - args[0] instanceof std.Iterator && args[1] instanceof std.Iterator) { - var begin_1 = args[0]; - var end_1 = args[1]; - this.assign(begin_1, end_1); - } - } - Object.defineProperty(Deque, "ROW", { - /// - // Row size of the {@link matrix_ matrix} which contains elements. - // - // Note that the {@link ROW} affects on time complexity of accessing and inserting element. - // Accessing element is {@link ROW} times slower than ordinary {@link Vector} and inserting element - // in middle position is {@link ROW} times faster than ordinary {@link Vector}. - // - // When the {@link ROW} returns 8, time complexity of accessing element is O(8) and inserting - // element in middle position is O(N/8). ({@link Vector}'s time complexity of accessement is O(1) - // and inserting element is O(N)). - /** - * @hidden - */ - get: function () { return 8; }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Deque, "MIN_CAPACITY", { - /// - // Minimum {@link capacity}. - // - // Although a {@link Deque} has few elements, even no element is belonged to, the {@link Deque} - // keeps the minimum {@link capacity} at least. - /** - * @hidden - */ - get: function () { return 100; }, - enumerable: true, - configurable: true - }); - // Get column size; {@link capacity_ capacity} / {@link ROW row}. - /** - * @hidden - */ - Deque.prototype.get_col_size = function () { - return Math.floor(this.capacity_ / Deque.ROW); - }; - Deque.prototype.assign = function (first, second) { - // CLEAR PREVIOUS CONTENTS - this.clear(); - if (first instanceof std.Iterator && second instanceof std.Iterator) { - var begin_2 = first; - var end_2 = second; - var size = 0; - for (var it = begin_2; !it.equal_to(end_2); it = it.next()) - size++; - // RESERVE - this.reserve(size); - this.size_ = size; - // ASSIGN CONTENTS - var array = this.matrix_[0]; - for (var it = begin_2; !it.equal_to(end_2); it = it.next()) { - if (array.length >= this.get_col_size()) { - array = new Array(); - this.matrix_.push(array); - } - array.push(it.value); - } - } - else { - var size = first; - var val = second; - // RESERVE - this.reserve(size); - this.size_ = size; - // ASSIGN CONTENTS - var array = this.matrix_[0]; - for (var i = 0; i < size; i++) { - if (array.length >= this.get_col_size()) { - array = new Array(); - this.matrix_.push(array); - } - array.push(val); - } - } - }; - /** - * @inheritdoc - */ - Deque.prototype.reserve = function (capacity) { - // MEMORIZE - var prevMatrix = this.matrix_; - var prevSize = this.size_; - // REFRESH - this.matrix_ = new Array(); - this.matrix_.push(new Array()); - ///// - // RE-FILL - ///// - var array = this.matrix_[0]; - for (var i = 0; i < prevMatrix.length; i++) - for (var j = 0; j < prevMatrix[i].length; j++) { - if (array.length >= this.get_col_size()) { - array = new Array(); - this.matrix_.push(array); - } - array.push(prevMatrix[i][j]); - } - }; - /** - * @inheritdoc - */ - Deque.prototype.clear = function () { - // CLEAR CONTENTS - this.matrix_ = new Array(); - this.matrix_.push(new Array()); - // RE-INDEX - this.size_ = 0; - this.capacity_ = Deque.MIN_CAPACITY; - }; - /* ========================================================= - ACCESSORS - - GETTERS & SETTERS - - ITERATORS - ========================================================= */ - /** - * @inheritdoc - */ - Deque.prototype.begin = function () { - if (this.empty() == true) - return this.end(); - else - return new std.DequeIterator(this, 0); - }; - /** - * @inheritdoc - */ - Deque.prototype.end = function () { - return new std.DequeIterator(this, -1); - }; - /** - * @inheritdoc - */ - Deque.prototype.rbegin = function () { - return new std.DequeReverseIterator(this.end()); - }; - /** - * @inheritdoc - */ - Deque.prototype.rend = function () { - return new std.DequeReverseIterator(this.begin()); - }; - /** - * @inheritdoc - */ - Deque.prototype.size = function () { - return this.size_; - }; - /** - * @inheritdoc - */ - Deque.prototype.empty = function () { - return this.size_ == 0; - }; - /** - * @inheritdoc - */ - Deque.prototype.capacity = function () { - return this.capacity_; - }; - /** - * @inheritdoc - */ - Deque.prototype.at = function (index) { - if (index > this.size()) - throw new std.OutOfRange("Target index is greater than Deque's size."); - var indexPair = this.fetch_index(index); - return this.matrix_[indexPair.first][indexPair.second]; - }; - /** - * @inheritdoc - */ - Deque.prototype.set = function (index, val) { - if (index > this.size()) - throw new std.OutOfRange("Target index is greater than Deque's size."); - var indexPair = this.fetch_index(index); - this.matrix_[indexPair.first][indexPair.second] = val; - }; - /** - * @inheritdoc - */ - Deque.prototype.front = function () { - return this.matrix_[0][0]; - }; - /** - * @inheritdoc - */ - Deque.prototype.back = function () { - var lastArray = this.matrix_[this.matrix_.length - 1]; - return lastArray[lastArray.length - 1]; - }; - /** - // Fetch row and column's index. - /** - * @hidden - */ - Deque.prototype.fetch_index = function (index) { - var row; - for (row = 0; row < this.matrix_.length; row++) { - var array = this.matrix_[row]; - if (index < array.length) - break; - index -= array.length; - } - if (row == this.matrix_.length) - row--; - return std.make_pair(row, index); - }; - /* ========================================================= - ELEMENTS I/O - - PUSH & POP - - INSERT - - ERASE - - PRE & POST-PROCESS - - SWAP - ============================================================ - PUSH & POP - --------------------------------------------------------- */ - /** - * @inheritdoc - */ - Deque.prototype.push = function () { - var items = []; - for (var _i = 0; _i < arguments.length; _i++) { - items[_i - 0] = arguments[_i]; - } - // RE-SIZE - if (this.size_ + items.length > this.capacity_) - this.reserve(this.size_ + items.length); - // INSERTS - var array = this.matrix_[this.matrix_.length - 1]; - for (var i = 0; i < items.length; i++) { - if (array.length >= this.get_col_size()) { - array = new Array(); - this.matrix_.push(array); - } - array.push(items[i]); - } - // INDEXING - this.size_ += items.length; - return this.size_; - }; - /** - * @inheritdoc - */ - Deque.prototype.push_front = function (val) { - // INSERT TO THE FRONT - this.matrix_[0].unshift(val); - this.size_++; - if (this.size_ > this.capacity_) - this.reserve(this.size_ * 2); - }; - /** - * @inheritdoc - */ - Deque.prototype.push_back = function (val) { - var lastArray = this.matrix_[this.matrix_.length - 1]; - if (lastArray.length >= this.get_col_size() && this.matrix_.length < Deque.ROW) { - lastArray = new Array(); - this.matrix_.push(lastArray); - } - lastArray.push(val); - this.size_++; - if (this.size_ > this.capacity_) - this.reserve(this.size_ * 2); - }; - /** - * @inheritdoc - */ - Deque.prototype.pop_front = function () { - if (this.empty() == true) - return; // SOMEWHERE PLACE TO THROW EXCEPTION - // EREASE FIRST ELEMENT - this.matrix_[0].shift(); - this.size_--; - if (this.matrix_[0].length == 0 && this.matrix_.length > 1) - this.matrix_.shift(); - }; + get: function () { + return this.constructor["name"]; + }, + enumerable: true, + configurable: true + }); + return Exception; + }(Error)); + std.Exception = Exception; + /* ========================================================= + + LOGIC_ERROR + - DOMAIN_ERROR + - INVALID_ARGUMENT + - LENGTH_ERROR + - OUT_OF_RANGE + ========================================================= */ + /** + *

Logic error exception.

+ * + *

This class defines the type of objects thrown as exceptions to report errors in the internal + * logical of the program, such as violation of logical preconditions or class invariants.

+ * + *

These errors are presumably detectable before the program executes.

+ * + *

It is used as a base class for several logical error exceptions.

+ * + *

+ *

+ * + * @reference http://www.cplusplus.com/reference/stdexcept/logic_error + * @author Jeongho Nam + */ + var LogicError = (function (_super) { + __extends(LogicError, _super); /** - * @inheritdoc + *

Construct from a message.

+ * + * @param message A message representing specification about the Exception. */ - Deque.prototype.pop_back = function () { - if (this.empty() == true) - return; // SOMEWHERE PLACE TO THROW EXCEPTION - // ERASE LAST ELEMENT - var lastArray = this.matrix_[this.matrix_.length - 1]; - lastArray.splice(lastArray.length - 1, 1); - this.size_--; - if (lastArray.length == 0 && this.matrix_.length > 1) - this.matrix_.splice(this.matrix_.length - 1, 1); - }; - Deque.prototype.insert = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i - 0] = arguments[_i]; - } - // REVERSE_ITERATOR TO ITERATOR - var ret; - var is_reverse_iterator = false; - if (args[0] instanceof std.DequeReverseIterator) { - is_reverse_iterator = true; - args[0] = args[0].base().prev(); - } - // BRANCHES - if (args.length == 2) - ret = this.insert_by_val(args[0], args[1]); - else if (args.length == 3 && typeof args[1] == "number") - ret = this._Insert_by_repeating_val(args[0], args[1], args[2]); - else - ret = this._Insert_by_range(args[0], args[1], args[2]); - // RETURNS - if (is_reverse_iterator == true) - return new std.DequeReverseIterator(ret.next()); - else - return ret; - }; + function LogicError(message) { + _super.call(this, message); + } + return LogicError; + }(Exception)); + std.LogicError = LogicError; + /** + *

Domain error exception.

+ * + *

This class defines the type of objects thrown as exceptions to report domain errors.

+ * + *

Generally, the domain of a mathematical function is the subset of values that it is defined for. + * For example, the square root function is only defined for non-negative numbers. Thus, a negative number + * for such a function would qualify as a domain error.

+ * + *

No component of the standard library throws exceptions of this type. It is designed as a standard + * exception to be thrown by programs.

+ * + *

+ *

+ * + * @reference http://www.cplusplus.com/reference/stdexcept/domain_error + * @author Jeongho Nam + */ + var DomainError = (function (_super) { + __extends(DomainError, _super); /** - * @hidden + *

Construct from a message.

+ * + * @param message A message representing specification about the Exception. */ - Deque.prototype.insert_by_val = function (position, val) { - return this._Insert_by_repeating_val(position, 1, val); - }; + function DomainError(message) { + _super.call(this, message); + } + return DomainError; + }(LogicError)); + std.DomainError = DomainError; + /** + *

Invalid argument exception.

+ * + *

This class defines the type of objects thrown as exceptions to report an invalid argument.

+ * + *

It is a standard exception that can be thrown by programs. Some components of the standard library + * also throw exceptions of this type to signal invalid arguments.

+ * + *

+ *

+ * + * @reference http://www.cplusplus.com/reference/stdexcept/invalid_argument + * @author Jeongho Nam + */ + var InvalidArgument = (function (_super) { + __extends(InvalidArgument, _super); /** - * @hidden + *

Construct from a message.

+ * + * @param message A message representing specification about the Exception. */ - Deque.prototype._Insert_by_repeating_val = function (position, n, val) { - // CONSTRUCT ITEMS - var items = []; - items.length = n; - for (var i = 0; i < n; i++) - items[i] = val; - // INSERT ELEMENTS - if (position.equal_to(this.end())) { - this.push.apply(this, items); - return this.begin(); - } - else - return this.insert_by_items(position, items); - }; + function InvalidArgument(message) { + _super.call(this, message); + } + return InvalidArgument; + }(LogicError)); + std.InvalidArgument = InvalidArgument; + /** + *

Length error exception.

+ * + *

This class defines the type of objects thrown as exceptions to report a length error.

+ * + *

It is a standard exception that can be thrown by programs. Some components of the standard library, + * such as vector and string also throw exceptions of this type to signal errors resizing.

+ * + *

+ *

+ * + * @reference http://www.cplusplus.com/reference/stdexcept/length_error + * @author Jeongho Nam + */ + var LengthError = (function (_super) { + __extends(LengthError, _super); /** - * @hidden + *

Construct from a message.

+ * + * @param message A message representing specification about the Exception. */ - Deque.prototype._Insert_by_range = function (position, begin, end) { - // CONSTRUCT ITEMS - var items = []; - for (var it = begin; !it.equal_to(end); it = it.next()) - items.push(it.value); - // INSERT ELEMENTS - if (position.equal_to(this.end())) { - this.push.apply(this, items); - return this.begin(); - } - else - return this.insert_by_items(position, items); - }; + function LengthError(message) { + _super.call(this, message); + } + return LengthError; + }(LogicError)); + std.LengthError = LengthError; + /** + *

Out-of-range exception.

+ * + *

This class defines the type of objects thrown as exceptions to report an out-of-range error.

+ * + *

It is a standard exception that can be thrown by programs. Some components of the standard library, + * such as vector, deque, string and bitset also throw exceptions of this type to signal arguments + * out of range.

+ * + *

+ *

+ * + * @reference http://www.cplusplus.com/reference/stdexcept/out_of_range + * @author Jeongho Nam + */ + var OutOfRange = (function (_super) { + __extends(OutOfRange, _super); /** - * @hidden + *

Construct from a message.

+ * + * @param message A message representing specification about the Exception. */ - Deque.prototype.insert_by_items = function (position, items) { - var item_size = items.length; - this.size_ += item_size; - if (this.size_ <= this.capacity_) { - // ------------------------------------------------------ - // WHEN FITTING INTO RESERVED CAPACITY IS POSSIBLE - // ------------------------------------------------------ - // INSERTS CAREFULLY CONSIDERING THE COL_SIZE - var index_pair = this.fetch_index(position.index); - var index = index_pair.first; - var spliced_values = this.matrix_[index].splice(index_pair.second); - if (spliced_values.length != 0) - items = items.concat.apply(items, spliced_values); - if (this.matrix_[index].length < Deque.ROW) { - this.matrix_[index] = (_a = this.matrix_[index]).concat.apply(_a, items.splice(0, Deque.ROW - this.matrix_[index].length)); - } - var splicedArray = this.matrix_.splice(index + 1); - // INSERTS - while (items.length != 0) - this.matrix_.push(items.splice(0, Math.min(Deque.ROW, items.length))); - // CONCAT WITH BACKS - this.matrix_ = (_b = this.matrix_).concat.apply(_b, splicedArray); - } - else { - // ----------------------------------------------------- - // WHEN CANNOT BE FIT INTO THE RESERVED CAPACITY - // ----------------------------------------------------- - // JUST INSERT CARELESSLY - // AND KEEP BLANACE BY THE RESERVE() METHOD - if (position.equal_to(this.end()) == true) { - this.matrix_.push(items); // ALL TO THE LAST - } - else { - var indexPair = this.fetch_index(position.index); - var index = indexPair.first; - var splicedValues = this.matrix_[index].splice(indexPair.second); - if (splicedValues.length != 0) - items = items.concat.apply(items, splicedValues); - // ALL TO THE MIDDLE - this.matrix_[index] = (_c = this.matrix_[index]).concat.apply(_c, items); - } - // AND KEEP BALANCE BY RESERVE() - this.reserve(this.size_); - } - return position; - var _a, _b, _c; - }; - Deque.prototype.erase = function (first, last) { - if (last === void 0) { last = first.next(); } - var ret; - var is_reverse_iterator = false; - // REVERSE_ITERATOR TO ITERATOR - if (first instanceof std.DequeReverseIterator) { - is_reverse_iterator = true; - var first_it = last.base(); - var last_it = first.base(); - first = first_it; - last = last_it; - } - // ERASE ELEMENTS - ret = this._Erase_by_range(first, last); - // RETURN BRANCHES - if (is_reverse_iterator == true) - return new std.DequeReverseIterator(ret.next()); - else - return ret; - }; + function OutOfRange(message) { + _super.call(this, message); + } + return OutOfRange; + }(LogicError)); + std.OutOfRange = OutOfRange; + /* ========================================================= + + RUNTIME_ERROR + - OVERFLOW_ERROR + - RANGE_ERROR + - SYSTEM_ERROR + - UNDERFLOW_ERROR + ========================================================= */ + /** + *

Runtime error exception.

+ * + *

This class defines the type of objects thrown as exceptions to report errors that can only be + * detected during runtime.

+ * + *

It is used as a base class for several runtime error exceptions.

+ * + *

+ *

+ * + * @reference http://www.cplusplus.com/reference/stdexcept/runtime_error + * @author Jeongho Nam + */ + var RuntimeError = (function (_super) { + __extends(RuntimeError, _super); /** - * @hidden - */ - Deque.prototype._Erase_by_range = function (first, last) { - if (first.index == -1) - return first; - // INDEXING - var size; - if (last.index == -1) - size = this.size() - first.index; - else - size = last.index - first.index; - this.size_ -= size; - // ERASING - while (size != 0) { - var indexPair = this.fetch_index(first.index); - var array = this.matrix_[indexPair.first]; - var myDeleteSize = Math.min(size, array.length - indexPair.second); - array.splice(indexPair.second, myDeleteSize); - if (array.length == 0 && this.matrix_.length > 1) - this.matrix_.splice(indexPair.first, 1); - size -= myDeleteSize; - } - if (last.index == -1) - return this.end(); - else - return first; - }; - Deque.prototype.swap = function (obj) { - if (obj instanceof Deque) { - _a = [obj.matrix_, this.matrix_], this.matrix_ = _a[0], obj.matrix_ = _a[1]; - _b = [obj.size_, this.size_], this.size_ = _b[0], obj.size_ = _b[1]; - _c = [obj.capacity_, this.capacity_], this.capacity_ = _c[0], obj.capacity_ = _c[1]; - } - else - _super.prototype.swap.call(this, obj); - var _a, _b, _c; - }; - return Deque; - }(std.base.Container)); - std.Deque = Deque; -})(std || (std = {})); -var std; -(function (std) { + *

Construct from a message.

+ * + * @param message A message representing specification about the Exception. + */ + function RuntimeError(message) { + _super.call(this, message); + } + return RuntimeError; + }(Exception)); + std.RuntimeError = RuntimeError; /** - *

An iterator of {@link Deque}.

+ *

Overflow error exception.

* - *

- * - *

+ *

This class defines the type of objects thrown as exceptions to arithmetic overflow errors.

+ * + *

It is a standard exception that can be thrown by programs. Some components of the standard library + * also throw exceptions of this type to signal range errors.

+ * + *

+ *

* + * @reference http://www.cplusplus.com/reference/stdexcept/overflow_error * @author Jeongho Nam */ - var DequeIterator = (function (_super) { - __extends(DequeIterator, _super); - /* --------------------------------------------------------- - CONSTRUCTORS - --------------------------------------------------------- */ + var OverflowError = (function (_super) { + __extends(OverflowError, _super); /** - *

Construct from the source {@link Deque container}.

- * - *

Note

- *

Do not create the iterator directly, by yourself.

- *

Use {@link Deque.begin begin()}, {@link Deque.end end()} in {@link Deque container} instead.

+ *

Construct from a message.

* - * @param source The source {@link Deque container} to reference. - * @param index Sequence number of the element in the source {@link Deque}. + * @param message A message representing specification about the Exception. */ - function DequeIterator(source, index) { - _super.call(this, source); - this.index_ = index; + function OverflowError(message) { + _super.call(this, message); } - Object.defineProperty(DequeIterator.prototype, "deque", { - /* --------------------------------------------------------- - ACCESSORS - --------------------------------------------------------- */ - /** - * @hidden - */ - get: function () { - return this.source_; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(DequeIterator.prototype, "value", { - /** - * @inheritdoc - */ - get: function () { - return this.deque.at(this.index_); - }, - /** - * Set value of the iterator is pointing to. - * - * @param val Value to set. - */ - set: function (val) { - this.deque.set(this.index_, val); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(DequeIterator.prototype, "index", { - /** - * @inheritdoc - */ - get: function () { - return this.index_; - }, - enumerable: true, - configurable: true - }); - /* --------------------------------------------------------- - MOVERS - --------------------------------------------------------- */ - /** - * @inheritdoc - */ - DequeIterator.prototype.prev = function () { - if (this.index_ == -1) - return new DequeIterator(this.deque, this.deque.size() - 1); - else if (this.index_ - 1 < 0) - return this.deque.end(); - else - return new DequeIterator(this.deque, this.index_ - 1); - }; - /** - * @inheritdoc - */ - DequeIterator.prototype.next = function () { - if (this.index_ >= this.source_.size() - 1) - return this.deque.end(); - else - return new DequeIterator(this.deque, this.index_ + 1); - }; - /** - * @inheritdoc - */ - DequeIterator.prototype.advance = function (n) { - var new_index; - if (n < 0 && this.index_ == -1) - new_index = this.deque.size() + n; - else - new_index = this.index_ + n; - if (new_index < 0 || new_index >= this.deque.size()) - return this.deque.end(); - else - return new DequeIterator(this.deque, new_index); - }; - /* --------------------------------------------------------- - COMPARES - --------------------------------------------------------- */ + return OverflowError; + }(RuntimeError)); + std.OverflowError = OverflowError; + /** + *

Underflow error exception.

+ * + *

This class defines the type of objects thrown as exceptions to arithmetic underflow errors.

+ * + *

No component of the standard library throws exceptions of this type. It is designed as a standard + * exception to be thrown by programs.

+ * + *

+ *

+ * + * @reference http://www.cplusplus.com/reference/stdexcept/underflow_error + * @author Jeongho Nam + */ + var UnderflowError = (function (_super) { + __extends(UnderflowError, _super); /** - *

Whether an iterator is equal with the iterator.

- * - *

Compare two iterators and returns whether they are equal or not.

- * - *

Note

- *

Iterator's equal_to() only compare souce container and index number.

- * - *

Although elements in a pair, key and value are equal_to, if the source map or - * index number is different, then the {@link equal_to equal_to()} will return false. If you want to - * compare the elements of a pair, compare them directly by yourself.

+ *

Construct from a message.

* - * @param obj An iterator to compare - * @return Indicates whether equal or not. - */ - DequeIterator.prototype.equal_to = function (obj) { - return _super.prototype.equal_to.call(this, obj) && this.index_ == obj.index_; - }; - /** - * @inheritdoc + * @param message A message representing specification about the Exception. */ - DequeIterator.prototype.swap = function (obj) { - _a = [obj.value, this.value], this.value = _a[0], obj.value = _a[1]; - var _a; - }; - return DequeIterator; - }(std.Iterator)); - std.DequeIterator = DequeIterator; -})(std || (std = {})); -var std; -(function (std) { + function UnderflowError(message) { + _super.call(this, message); + } + return UnderflowError; + }(RuntimeError)); + std.UnderflowError = UnderflowError; /** - *

A reverse-iterator of Deque.

+ *

Range error exception.

* - *

- * - *

+ *

This class defines the type of objects thrown as exceptions to report range errors in internal + * computations.

* - * @param Type of the elements. + *

It is a standard exception that can be thrown by programs. Some components of the standard library + * also throw exceptions of this type to signal range errors.

* + *

+ *

+ * + * @reference http://www.cplusplus.com/reference/stdexcept/range_error * @author Jeongho Nam */ - var DequeReverseIterator = (function (_super) { - __extends(DequeReverseIterator, _super); - /* --------------------------------------------------------- - CONSTRUCTORS - --------------------------------------------------------- */ + var RangeError = (function (_super) { + __extends(RangeError, _super); /** - * Construct from base iterator. + *

Construct from a message.

* - * @param base A reference of the base iterator, which iterates in the opposite direction. + * @param message A message representing specification about the Exception. */ - function DequeReverseIterator(base) { - _super.call(this, base); + function RangeError(message) { + _super.call(this, message); } - /** - * @hidden - */ - DequeReverseIterator.prototype.create_neighbor = function (base) { - return new DequeReverseIterator(base); - }; - Object.defineProperty(DequeReverseIterator.prototype, "value", { - /* --------------------------------------------------------- - ACCESSORS - --------------------------------------------------------- */ - /** - * @inheritdoc - */ - get: function () { - return this.base_.value; - }, - /** - * Set value of the iterator is pointing to. - * - * @param val Value to set. - */ - set: function (val) { - this.base_.value = val; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(DequeReverseIterator.prototype, "index", { - /** - * Get index. - */ - get: function () { - return this.base_.index; - }, - enumerable: true, - configurable: true - }); - return DequeReverseIterator; - }(std.ReverseIterator)); - std.DequeReverseIterator = DequeReverseIterator; + return RangeError; + }(RuntimeError)); + std.RangeError = RangeError; + /** + * @hidden + */ + var terminate_handler = null; })(std || (std = {})); /// -// Standard exceptions +// Standard Template Library: Function objects +// Function objects are objects specifically designed to be used with a syntax similar to that of functions. // -// This header defines the base class for all exceptions thrown by the elements of the standard library: -// {@link Exception}, along with several types and utilities to assist handling exceptions: +// They are typically used as arguments to functions, such as predicates or comparison functions passed to standard algorithms. // -// @reference http://www.cplusplus.com/reference/exception/ +// @reference http://www.cplusplus.com/reference/functional/ // @author Jeongho Nam var std; (function (std) { /** - *

Function handling termination on exception

+ *

Function object class for equality comparison.

* - *

Calls the current terminate handler.

+ *

Binary function object class whose call returns whether its two arguments compare equal (as returned by + * operator ==).

* - *

By default, the terminate handler calls abort. But this behavior can be redefined by calling - * {@link set_terminate}.

+ *

Generically, function objects are instances of a class with member function {@link IComparable.equal_to equal_to} + * defined. This member function allows the object to be used with the same syntax as a function call.

* - *

This function is automatically called when no catch handler can be found for a thrown exception, - * or for some other exceptional circumstance that makes impossible to continue the exception handling process.

+ * @param x First element to compare. + * @param y Second element to compare. * - *

This function is provided so that the terminate handler can be explicitly called by a program that needs to - * abnormally terminate, and works even if {@link set_terminate} has not been used to set a custom terminate handler - * (calling abort in this case).

+ * @return Whether the arguments are equal. */ - function terminate() { - if (terminate_handler != null) - terminate_handler(); - if (std.is_node() == true) - process.exit(); - else { - window.open("", "_self", ""); - window.close(); - } + function equal_to(x, y) { + if (x instanceof Object && x.equal_to != undefined) + return x.equal_to(y); + else + return x == y; } - std.terminate = terminate; + std.equal_to = equal_to; /** - *

Set terminate handler function.

+ *

Function object class for non-equality comparison.

* - *

A terminate handler function is a function automatically called when the exception handling process has - * to be abandoned for some reason. This happens when no catch handler can be found for a thrown exception, or for - * some other exceptional circumstance that makes impossible to continue the exception handling process.

+ *

Binary function object class whose call returns whether its two arguments compare not equal (as returned + * by operator operator!=).

* - *

Before this function is called by the program for the first time, the default behavior is to call abort.

+ *

Generically, function objects are instances of a class with member function {@link IComparable.equal_to equal_to} + * defined. This member function allows the object to be used with the same syntax as a function call.

* - *

A program may explicitly call the current terminate handler function by calling {@link terminate}.

+ * @param x First element to compare. + * @param y Second element to compare. * - * @param f Function that takes no parameters and returns no value (void). + * @return Whether the arguments are not equal. */ - function set_terminate(f) { - terminate_handler = f; - if (std.is_node() == true) - process.on("uncaughtException", function (error) { - terminate_handler(); - }); + function not_equal_to(x, y) { + return !std.equal_to(x, y); + } + std.not_equal_to = not_equal_to; + /** + *

Function for less-than inequality comparison.

+ * + *

Binary function returns whether the its first argument compares less than the second.

+ * + *

Generically, function objects are instances of a class with member function {@link IComparable.less less} + * defined. If an object doesn't have the method, then its own uid will be used to compare insteadly. + * This member function allows the object to be used with the same syntax as a function call.

+ * + *

Objects of this class can be used on standard algorithms such as {@link sort sort()}, + * {@link merge merge()} or {@link TreeMap.lower_bound lower_bound()}.

+ * + * @param Type of arguments to compare by the function call. The type shall supporrt the operation + * operator<() or method {@link IComparable.less less}. + * + * @param x First element, the standard of comparison. + * @param y Second element compare with the first. + * + * @return Whether the first parameter is less than the second. + */ + function less(x, y) { + if (x instanceof Object) + if (x.less != undefined) + return x.less(y); + else + return x.__get_m_iUID() < y.__get_m_iUID(); else - window.onerror = - function (message, filename, lineno, colno, error) { - terminate_handler(); - }; + return x < y; } - std.set_terminate = set_terminate; + std.less = less; /** - *

Get terminate handler function.

+ *

Function object class for less-than-or-equal-to comparison.

* - *

The terminate handler function is automatically called when no catch handler can be found - * for a thrown exception, or for some other exceptional circumstance that makes impossible to continue the exception - * handling process.

+ *

Binary function object class whose call returns whether the its first argument compares {@link less less than} or + * {@link equal_to equal to} the second (as returned by operator <=).

* - *

If no such function has been set by a previous call to {@link set_terminate}, the function returns a - * null-pointer.

+ *

Generically, function objects are instances of a class with member function {@link IComparable.less less} + * and {@link IComparable.equal_to equal_to} defined. This member function allows the object to be used with the same + * syntax as a function call.

* - * @return If {@link set_terminate} has previously been called by the program, the function returns the current - * terminate handler function. Otherwise, it returns a null-pointer. + * @param x First element, the standard of comparison. + * @param y Second element compare with the first. + * + * @return Whether the x is {@link less less than} or {@link equal_to equal to} the y. */ - function get_terminate() { - return terminate_handler; + function less_equal(x, y) { + return std.less(x, y) || std.equal_to(x, y); } - std.get_terminate = get_terminate; - /* ========================================================= - + EXCEPTION - + LOGIC_ERROR - - DOMAIN_ERROR - - INVALID_ARGUMENT - - LENGTH_ERROR - - OUT_OF_RANGE - + RUNTIME_ERROR - - OVERFLOW_ERROR - - RANGE_ERROR - - SYSTEM_ERROR - - UNDERFLOW_ERROR - ========================================================= */ + std.less_equal = less_equal; /** - *

Standard exception class.

+ *

Function for greater-than inequality comparison.

* - *

Base class for standard exceptions.

+ *

Binary function returns whether the its first argument compares greater than the second.

* - *

All objects thrown by components of the standard library are derived from this class. - * Therefore, all standard exceptions can be caught by catching this type by reference.

+ *

Generically, function objects are instances of a class with member function {@link less} and + * {@link equal_to equal_to()} defined. If an object doesn't have those methods, then its own uid will be used + * to compare insteadly. This member function allows the object to be used with the same syntax as a function + * call.

* - *

- *

+ *

Objects of this class can be used on standard algorithms such as {@link sort sort()}, + * {@link merge merge()} or {@link TreeMap.lower_bound lower_bound()}.

* - * @reference http://www.cplusplus.com/reference/exception/exception - * @author Jeongho Nam + * @param Type of arguments to compare by the function call. The type shall supporrt the operation + * operator>() or method {@link IComparable.greater greater}. + * + * @return Whether the x is greater than the y. */ - var Exception = (function (_super) { - __extends(Exception, _super); - function Exception(message) { - if (message === void 0) { message = ""; } - _super.call(this); - this.description = message; - } - /** - *

Get string identifying exception.

- *

Returns a string that may be used to identify the exception.

- * - *

The particular representation pointed by the returned value is implementation-defined. - * As a virtual function, derived classes may redefine this function so that specify value are - * returned.

- */ - Exception.prototype.what = function () { - return this.description; - }; - Object.defineProperty(Exception.prototype, "message", { - /** - * @inheritdoc - */ - get: function () { - return this.description; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Exception.prototype, "name", { - /** - * @inheritdoc - */ - get: function () { - return this.constructor["name"]; - }, - enumerable: true, - configurable: true - }); - return Exception; - }(Error)); - std.Exception = Exception; - /* ========================================================= - + LOGIC_ERROR - - DOMAIN_ERROR - - INVALID_ARGUMENT - - LENGTH_ERROR - - OUT_OF_RANGE - ========================================================= */ + function greater(x, y) { + return !std.less_equal(x, y); + } + std.greater = greater; + /** + *

Function object class for greater-than-or-equal-to comparison.

+ * + *

Binary function object class whose call returns whether the its first argument compares + * {@link greater greater than} or {@link equal_to equal to} the second (as returned by operator >=).

+ * + *

Generically, function objects are instances of a class with member function {@link IComparable.less less} + * defined. If an object doesn't have the method, then its own uid will be used to compare insteadly. + * This member function allows the object to be used with the same syntax as a function call.

+ * + * @param x First element, the standard of comparison. + * @param y Second element compare with the first. + * + * @return Whether the x is {@link greater greater than} or {@link equal_to equal to} the y. + */ + function greater_equal(x, y) { + return !std.less(x, y); + } + std.greater_equal = greater_equal; + /** + *

Logical AND function object class.

+ * + *

Binary function object class whose call returns the result of the logical "and" operation between its two + * arguments (as returned by operator &&).

+ * + *

Generically, function objects are instances of a class with member function operator() defined. This member + * function allows the object to be used with the same syntax as a function call.

+ * + * @param x First element. + * @param y Second element. + * + * @return Result of logical AND operation. + */ + function logical_and(x, y) { + return x && y; + } + std.logical_and = logical_and; + /** + *

Logical OR function object class.

+ * + *

Binary function object class whose call returns the result of the logical "or" operation between its two + * arguments (as returned by operator ||).

+ * + *

Generically, function objects are instances of a class with member function operator() defined. This member + * function allows the object to be used with the same syntax as a function call.

+ * + * @param x First element. + * @param y Second element. + * + * @return Result of logical OR operation. + */ + function logical_or(x, y) { + return x || y; + } + std.logical_or = logical_or; /** - *

Logic error exception.

+ *

Logical NOT function object class.

* - *

This class defines the type of objects thrown as exceptions to report errors in the internal - * logical of the program, such as violation of logical preconditions or class invariants.

+ *

Unary function object class whose call returns the result of the logical "not" operation on its argument + * (as returned by operator !).

* - *

These errors are presumably detectable before the program executes.

+ *

Generically, function objects are instances of a class with member function operator() defined. This member + * function allows the object to be used with the same syntax as a function call.

* - *

It is used as a base class for several logical error exceptions.

+ * @param x Target element. * - *

- *

+ * @return Result of logical NOT operation. + */ + function logical_not(x) { + return !x; + } + std.logical_not = logical_not; + /** + *

Bitwise AND function object class.

* - * @reference http://www.cplusplus.com/reference/stdexcept/logic_error - * @author Jeongho Nam + *

Binary function object class whose call returns the result of applying the bitwise "and" operation between + * its two arguments (as returned by operator &).

+ * + * @param x First element. + * @param y Second element. + * + * @return Result of bitwise AND operation. */ - var LogicError = (function (_super) { - __extends(LogicError, _super); - /** - *

Construct from a message.

- * - * @param message A message representing specification about the Exception. - */ - function LogicError(message) { - _super.call(this, message); - } - return LogicError; - }(Exception)); - std.LogicError = LogicError; + function bit_and(x, y) { + return x & y; + } + std.bit_and = bit_and; /** - *

Domain error exception.

+ *

Bitwise OR function object class.

* - *

This class defines the type of objects thrown as exceptions to report domain errors.

+ *

Binary function object class whose call returns the result of applying the bitwise "and" operation between + * its two arguments (as returned by operator &).

* - *

Generally, the domain of a mathematical function is the subset of values that it is defined for. - * For example, the square root function is only defined for non-negative numbers. Thus, a negative number - * for such a function would qualify as a domain error.

+ * @param x First element. + * @param y Second element. * - *

No component of the standard library throws exceptions of this type. It is designed as a standard - * exception to be thrown by programs.

+ * @return Result of bitwise OR operation. + */ + function bit_or(x, y) { + return x | y; + } + std.bit_or = bit_or; + /** + *

Bitwise XOR function object class.

* - *

- *

+ *

Binary function object class whose call returns the result of applying the bitwise "exclusive or" + * operation between its two arguments (as returned by operator ^).

* - * @reference http://www.cplusplus.com/reference/stdexcept/domain_error - * @author Jeongho Nam + * @param x First element. + * @param y Second element. + * + * @return Result of bitwise XOR operation. */ - var DomainError = (function (_super) { - __extends(DomainError, _super); + function bit_xor(x, y) { + return x ^ y; + } + std.bit_xor = bit_xor; + function hash(par) { + var type = typeof par; + if (type == "number") + return hash_of_number(par); + else if (type == "string") + return hash_of_string(par); + else + return hash_of_object(par); + } + std.hash = hash; + /** + * @hidden + */ + function hash_of_number(val) { + // ------------------------------------------ + // IN C++ + // CONSIDER A NUMBER AS A STRING + // HASH((CHAR*)&VAL, 8) + // ------------------------------------------ + // CONSTRUCT BUFFER AND BYTE_ARRAY + var buffer = new ArrayBuffer(8); + var byteArray = new Int8Array(buffer); + var valueArray = new Float64Array(buffer); + valueArray[0] = val; + var code = 2166136261; + for (var i = 0; i < byteArray.length; i++) { + var byte = (byteArray[i] < 0) ? byteArray[i] + 256 : byteArray[i]; + code ^= byte; + code *= 16777619; + } + return Math.abs(code); + } + /** + * @hidden + */ + function hash_of_string(str) { + var code = 2166136261; + for (var i = 0; i < str.length; i++) { + code ^= str.charCodeAt(i); + code *= 16777619; + } + return Math.abs(code); + } + /** + * @hidden + */ + function hash_of_object(obj) { + if (obj.hash != undefined) + return obj.hash(); + else + return hash_of_number(obj.__get_m_iUID()); + } + /* --------------------------------------------------------- + UNIQUE ID FOR OBJECTS + --------------------------------------------------------- */ + // Incremental sequence of unique id for objects. + /** + * @hidden + */ + var __s_iUID; + if (__s_iUID == undefined) + __s_iUID = 0; + if (Object.prototype.hasOwnProperty("__get_m_iUID") == false) { + Object.defineProperties(Object.prototype, { + "__get_m_iUID": { + value: function () { + if (this.hasOwnProperty("__m_iUID") == false) { + var uid = ++__s_iUID; + Object.defineProperty(this, "__m_iUID", { + "get": function () { + return uid; + } + }); + } + return this.__m_iUID; + } + } + }); + } + function swap(left, right) { + left.swap(right); + } + std.swap = swap; +})(std || (std = {})); +var std; +(function (std) { + function bind(fn) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + var this_arg = null; + var parameters = []; + var placeholder_count = 0; + for (var i = 0; i < args.length; i++) { + if (i == 0 && args[0] instanceof Object && args[0] instanceof std.placeholders.PlaceHolder == false) { + // retrieve the object; items[0] + for (var key in args[0]) + if (args[0][key] == fn) { + // found the this_arg + this_arg = args[0]; + break; + } + if (this_arg != null) + continue; + } + // the placeholder also fills parameters + if (args[i] instanceof std.placeholders.PlaceHolder) + placeholder_count++; + parameters.push(args[i]); + } + //////////////////// + // FUNCTION TO BE RETURNED + //////////////////// + var ret = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i - 0] = arguments[_i]; + } + if (args.length == 0) + return fn.apply(this_arg, parameters); + var thisArg = this_arg; + var argArray = parameters.slice(); + // 1st argument is thisArg? + if (thisArg == null && (parameters.length == 0 || parameters[0] instanceof std.placeholders.PlaceHolder) && args[0] instanceof Object) + for (var key in args[0]) + if (args[0][key] == fn) { + thisArg = args[0]; + argArray.splice(0, 1); + //lastIndex++; + break; + } + // fill argArray from placeholders + for (var i = 0; i < argArray.length; i++) + if (argArray[i] instanceof std.placeholders.PlaceHolder) + argArray[i] = args[argArray[i].index - 1]; + // arguments are over the placeholder_count + if (args.length > placeholder_count) + for (var i = placeholder_count; i < args.length; i++) + if (i == 0 && (this_arg == null && thisArg != null)) + continue; // thisArg + else + argArray.push(args[i]); + return fn.apply(thisArg, argArray); + }; + return ret; + } + std.bind = bind; +})(std || (std = {})); +/** + *

Bind argument placeholders.

+ * + *

This namespace declares an unspecified number of objects: _1, _2, _3, ..., which are + * used to specify placeholders in calls to function {@link std.bind}.

+ * + *

When the function object returned by bind is called, an argument with placeholder {@link _1} is replaced by the + * first argument in the call, {@link _2} is replaced by the second argument in the call, and so on... For example:

+ * + * + * let vec: Vector = new Vector(); + * + * let bind = std.bind(Vector.insert, _1, vec.end(), _2, _3); + * bind.apply(vec, 5, 1); // vec.insert(vec.end(), 5, 1); + * // [1, 1, 1, 1, 1] + * + * + *

When a call to {@link bind} is used as a subexpression in another call to bind, the {@link placeholders} + * are relative to the outermost {@link bind} expression.

+ * + * @reference http://www.cplusplus.com/reference/functional/placeholders/ + * @author Jeongho Nam + */ +var std; +(function (std) { + var placeholders; + (function (placeholders) { /** - *

Construct from a message.

- * - * @param message A message representing specification about the Exception. + * @hidden */ - function DomainError(message) { - _super.call(this, message); - } - return DomainError; - }(LogicError)); - std.DomainError = DomainError; - /** - *

Invalid argument exception.

- * - *

This class defines the type of objects thrown as exceptions to report an invalid argument.

- * - *

It is a standard exception that can be thrown by programs. Some components of the standard library - * also throw exceptions of this type to signal invalid arguments.

- * - *

- *

- * - * @reference http://www.cplusplus.com/reference/stdexcept/invalid_argument - * @author Jeongho Nam - */ - var InvalidArgument = (function (_super) { - __extends(InvalidArgument, _super); + var PlaceHolder = (function () { + function PlaceHolder(index) { + this.index_ = index; + } + Object.defineProperty(PlaceHolder.prototype, "index", { + get: function () { + return this.index_; + }, + enumerable: true, + configurable: true + }); + return PlaceHolder; + }()); + placeholders.PlaceHolder = PlaceHolder; /** - *

Construct from a message.

- * - * @param message A message representing specification about the Exception. + * Replaced by the first argument in the function call. */ - function InvalidArgument(message) { - _super.call(this, message); - } - return InvalidArgument; - }(LogicError)); - std.InvalidArgument = InvalidArgument; - /** - *

Length error exception.

- * - *

This class defines the type of objects thrown as exceptions to report a length error.

- * - *

It is a standard exception that can be thrown by programs. Some components of the standard library, - * such as vector and string also throw exceptions of this type to signal errors resizing.

- * - *

- *

- * - * @reference http://www.cplusplus.com/reference/stdexcept/length_error - * @author Jeongho Nam - */ - var LengthError = (function (_super) { - __extends(LengthError, _super); + placeholders._1 = new PlaceHolder(1); /** - *

Construct from a message.

- * - * @param message A message representing specification about the Exception. + * Replaced by the second argument in the function call. */ - function LengthError(message) { - _super.call(this, message); - } - return LengthError; - }(LogicError)); - std.LengthError = LengthError; - /** - *

Out-of-range exception.

- * - *

This class defines the type of objects thrown as exceptions to report an out-of-range error.

- * - *

It is a standard exception that can be thrown by programs. Some components of the standard library, - * such as vector, deque, string and bitset also throw exceptions of this type to signal arguments - * out of range.

- * - *

- *

- * - * @reference http://www.cplusplus.com/reference/stdexcept/out_of_range - * @author Jeongho Nam - */ - var OutOfRange = (function (_super) { - __extends(OutOfRange, _super); + placeholders._2 = new PlaceHolder(2); /** - *

Construct from a message.

- * - * @param message A message representing specification about the Exception. + * Replaced by the third argument in the function call. */ - function OutOfRange(message) { - _super.call(this, message); - } - return OutOfRange; - }(LogicError)); - std.OutOfRange = OutOfRange; - /* ========================================================= - + RUNTIME_ERROR - - OVERFLOW_ERROR - - RANGE_ERROR - - SYSTEM_ERROR - - UNDERFLOW_ERROR - ========================================================= */ - /** - *

Runtime error exception.

- * - *

This class defines the type of objects thrown as exceptions to report errors that can only be - * detected during runtime.

- * - *

It is used as a base class for several runtime error exceptions.

- * - *

- *

- * - * @reference http://www.cplusplus.com/reference/stdexcept/runtime_error - * @author Jeongho Nam - */ - var RuntimeError = (function (_super) { - __extends(RuntimeError, _super); + placeholders._3 = new PlaceHolder(3); + placeholders._4 = new PlaceHolder(4); + placeholders._5 = new PlaceHolder(5); + placeholders._6 = new PlaceHolder(6); + placeholders._7 = new PlaceHolder(7); + placeholders._8 = new PlaceHolder(8); + placeholders._9 = new PlaceHolder(9); + placeholders._10 = new PlaceHolder(10); + placeholders._11 = new PlaceHolder(11); + placeholders._12 = new PlaceHolder(12); + placeholders._13 = new PlaceHolder(13); + placeholders._14 = new PlaceHolder(14); + placeholders._15 = new PlaceHolder(15); + placeholders._16 = new PlaceHolder(16); + placeholders._17 = new PlaceHolder(17); + placeholders._18 = new PlaceHolder(18); + placeholders._19 = new PlaceHolder(19); + placeholders._20 = new PlaceHolder(20); + })(placeholders = std.placeholders || (std.placeholders = {})); +})(std || (std = {})); +/// +/// +/// +var std; +(function (std) { + var base; + (function (base) { /** - *

Construct from a message.

+ *

An abstract map.

* - * @param message A message representing specification about the Exception. - */ - function RuntimeError(message) { - _super.call(this, message); - } - return RuntimeError; - }(Exception)); - std.RuntimeError = RuntimeError; - /** - *

Overflow error exception.

- * - *

This class defines the type of objects thrown as exceptions to arithmetic overflow errors.

- * - *

It is a standard exception that can be thrown by programs. Some components of the standard library - * also throw exceptions of this type to signal range errors.

- * - *

- *

- * - * @reference http://www.cplusplus.com/reference/stdexcept/overflow_error - * @author Jeongho Nam - */ - var OverflowError = (function (_super) { - __extends(OverflowError, _super); - /** - *

Construct from a message.

+ *

{@link MapContainer MapContainers} are associative containers that store elements formed by a combination + * of a key value (Key) and a mapped value (T), and which allows for fast retrieval + * of individual elements based on their keys.

* - * @param message A message representing specification about the Exception. - */ - function OverflowError(message) { - _super.call(this, message); - } - return OverflowError; - }(RuntimeError)); - std.OverflowError = OverflowError; - /** - *

Underflow error exception.

- * - *

This class defines the type of objects thrown as exceptions to arithmetic underflow errors.

- * - *

No component of the standard library throws exceptions of this type. It is designed as a standard - * exception to be thrown by programs.

- * - *

- *

- * - * @reference http://www.cplusplus.com/reference/stdexcept/underflow_error - * @author Jeongho Nam - */ - var UnderflowError = (function (_super) { - __extends(UnderflowError, _super); - /** - *

Construct from a message.

+ *

In a {@link MapContainer}, the key values are generally used to identify the elements, while the + * mapped values store the content associated to this key. The types of key and + * mapped value may differ, and are grouped together in member type value_type, which is a + * {@link Pair} type combining both:

* - * @param message A message representing specification about the Exception. - */ - function UnderflowError(message) { - _super.call(this, message); - } - return UnderflowError; - }(RuntimeError)); - std.UnderflowError = UnderflowError; - /** - *

Range error exception.

- * - *

This class defines the type of objects thrown as exceptions to report range errors in internal - * computations.

- * - *

It is a standard exception that can be thrown by programs. Some components of the standard library - * also throw exceptions of this type to signal range errors.

- * - *

- *

- * - * @reference http://www.cplusplus.com/reference/stdexcept/range_error - * @author Jeongho Nam - */ - var RangeError = (function (_super) { - __extends(RangeError, _super); - /** - *

Construct from a message.

+ *

typedef pair value_type;

+ * + *

{@link MapContainer} stores elements, keeps sequence and enables indexing by inserting elements into a + * {@link List} and registering {@link ListIterator iterators} of the {@link data_ list container} to an index + * table like {@link RBTree tree} or {@link HashBuckets hash-table}.

* - * @param message A message representing specification about the Exception. + *

+ *

+ * + *

Container properties

+ *
+ *
Associative
+ *
+ * Elements in associative containers are referenced by their key and not by their absolute position + * in the container. + *
+ * + *
Map
+ *
+ * Each element associates a key to a mapped value: + * Keys are meant to identify the elements whose main content is the mapped value. + *
+ *
+ * + * @param Type of the keys. Each element in a map is identified by its key value. + * @param Type of the mapped value. Each element in a map stores some data as its mapped value. + * + * @author Jeongho Nam */ - function RangeError(message) { - _super.call(this, message); - } - return RangeError; - }(RuntimeError)); - std.RangeError = RangeError; - /** - * @hidden - */ - var terminate_handler = null; + var MapContainer = (function (_super) { + __extends(MapContainer, _super); + /* --------------------------------------------------------- + CONSTURCTORS + --------------------------------------------------------- */ + /** + * Default Constructor. + */ + function MapContainer() { + _super.call(this); + this.data_ = new std.List(); + } + /** + * @inheritdoc + */ + MapContainer.prototype.assign = function (first, last) { + // INSERT + this.clear(); + this.insert(first, last); + }; + /** + * @inheritdoc + */ + MapContainer.prototype.clear = function () { + // TO BE ABSTRACT + this.data_.clear(); + }; + /** + *

Return iterator to beginning.

+ * + *

Returns an iterator referring the first element in the

+ * + *

Note

+ *

If the container is {@link empty}, the returned iterator is same with {@link end end()}.

+ * + * @return An iterator to the first element in the The iterator containes the first element's value. + */ + MapContainer.prototype.begin = function () { + return new std.MapIterator(this, this.data_.begin()); + }; + /** + *

Return iterator to end.

+ *

Returns an iterator referring to the past-the-end element in the

+ * + *

The past-the-end element is the theoretical element that would follow the last element in the + * It does not point to any element, and thus shall not be dereferenced.

+ * + *

Because the ranges used by functions of the container do not include the element reference by their + * closing iterator, this function is often used in combination with {@link MapContainer}.{@link begin} to + * specify a range including all the elements in the

+ * + *

Note

+ *

Returned iterator from {@link MapContainer}.{@link end} does not refer any element. Trying to accessing + * element by the iterator will cause throwing exception ({@link OutOfRange}).

+ * + *

If the container is {@link empty}, this function returns the same as {@link begin}.

+ * + * @return An iterator to the end element in the + */ + MapContainer.prototype.end = function () { + return new std.MapIterator(this, this.data_.end()); + }; + /** + *

Return {@link MapReverseIterator reverse iterator} to reverse beginning.

+ * + *

Returns a {@link MapReverseIterator reverse iterator} pointing to the last element in the container + * (i.e., its reverse beginning).

+ * + * {@link MapReverseIterator Reverse iterators} iterate backwards: increasing them moves them towards the + * beginning of the container.

+ * + *

{@link rbegin} points to the element preceding the one that would be pointed to by member {@link end}. + *

+ * + * @return A {@link MapReverseIterator reverse iterator} to the reverse beginning of the sequence + * + */ + MapContainer.prototype.rbegin = function () { + return new std.MapReverseIterator(this.end()); + }; + /** + *

Return {@link MapReverseIterator reverse iterator} to reverse end.

+ * + *

Returns a {@link MapReverseIterator reverse iterator} pointing to the theoretical element right before + * the first element in the {@link MapContainer map container} (which is considered its reverse end). + *

+ * + *

The range between {@link MapContainer}.{@link rbegin} and {@link MapContainer}.{@link rend} contains + * all the elements of the container (in reverse order).

+ * + * @return A {@link MapReverseIterator reverse iterator} to the reverse end of the sequence + */ + MapContainer.prototype.rend = function () { + return new std.MapReverseIterator(this.begin()); + }; + /* --------------------------------------------------------- + ELEMENTS + --------------------------------------------------------- */ + /** + *

Whether have the item or not.

+ * + *

Indicates whether a map has an item having the specified identifier.

+ * + * @param key Key value of the element whose mapped value is accessed. + * + * @return Whether the map has an item having the specified identifier. + */ + MapContainer.prototype.has = function (key) { + return !this.find(key).equal_to(this.end()); + }; + /** + * Return the number of elements in the map. + */ + MapContainer.prototype.size = function () { + return this.data_.size(); + }; + MapContainer.prototype.push = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i - 0] = arguments[_i]; + } + // TO BE ABSTRACT + for (var i = 0; i < args.length; i++) + if (args[i] instanceof std.Pair) + this._Insert_by_pair(args[i]); + else if (args[i] instanceof Array) + this.insert_by_tuple(args[i]); + return this.size(); + }; + MapContainer.prototype.emplace_hint = function (hint) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + if (args.length == 1) + return this.insert(hint, args[0]); + else + return this.insert(hint, std.make_pair(args[0], args[1])); + }; + MapContainer.prototype.insert = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i - 0] = arguments[_i]; + } + if (args.length == 1 && args[0] instanceof std.Pair) { + return this._Insert_by_pair(args[0]); + } + else if (args.length == 1 && args[0] instanceof Array) { + return this.insert_by_tuple(args[0]); + } + else if (args.length == 2 && args[0] instanceof std.Iterator && args[1] instanceof std.Iterator) { + return this._Insert_by_range(args[0], args[1]); + } + else { + var ret = void 0; + var is_reverse_iterator = false; + // REVERSE_ITERATOR TO ITERATOR + if (args[0] instanceof std.MapReverseIterator) { + is_reverse_iterator = true; + args[0] = args[0].base().prev(); + } + // INSERT AN ELEMENT + if (args[1] instanceof std.Pair) + ret = this._Insert_by_hint(args[0], args[1]); + else + ret = this.insert_by_hint_with_tuple(args[0], args[1]); + // RETURN BRANCHES + if (is_reverse_iterator == true) + return new std.MapReverseIterator(ret.next()); + else + return ret; + } + }; + /** + * @hidden + */ + MapContainer.prototype.insert_by_tuple = function (tuple) { + return this._Insert_by_pair(new std.Pair(tuple[0], tuple[1])); + }; + /** + * @hidden + */ + MapContainer.prototype.insert_by_hint_with_tuple = function (hint, tuple) { + return this._Insert_by_hint(hint, std.make_pair(tuple[0], tuple[1])); + }; + MapContainer.prototype.erase = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i - 0] = arguments[_i]; + } + if (args.length == 1 && (args[0] instanceof std.Iterator == false || args[0].get_source() != this)) + return this.erase_by_key(args[0]); + else if (args.length == 1) + return this.erase_by_iterator(args[0]); + else + return this.erase_by_iterator(args[0], args[1]); + }; + /** + * @hidden + */ + MapContainer.prototype.erase_by_key = function (key) { + var it = this.find(key); + if (it.equal_to(this.end()) == true) + return 0; + this.erase_by_iterator(it); + return 1; + }; + /** + * @hidden + */ + MapContainer.prototype.erase_by_iterator = function (first, last) { + if (last === void 0) { last = first.next(); } + var ret; + var is_reverse_iterator = false; + // REVERSE ITERATOR TO ITERATOR + if (first instanceof std.MapReverseIterator) { + is_reverse_iterator = true; + var first_it = last.base(); + var last_it = first.base(); + first = first_it; + last = last_it; + } + // ERASE ELEMENTS + ret = this.erase_by_range(first, last); + // RETURN BRANCHES + if (is_reverse_iterator == true) + return new std.MapReverseIterator(ret.next()); + else + return ret; + }; + /** + * @hidden + */ + MapContainer.prototype.erase_by_range = function (begin, end) { + // ERASE + var listIterator = this.data_.erase(begin.get_list_iterator(), end.get_list_iterator()); + // POST-PROCESS + this._Handle_erase(begin, end); + return new std.MapIterator(this, listIterator); + }; + /* --------------------------------------------------------- + SWAP + --------------------------------------------------------- */ + /** + * @hidden + */ + MapContainer.prototype._Swap = function (obj) { + _a = [obj.data_, this.data_], this.data_ = _a[0], obj.data_ = _a[1]; + var _a; + }; + return MapContainer; + }(base.Container)); + base.MapContainer = MapContainer; + })(base = std.base || (std.base = {})); })(std || (std = {})); -/// -// Standard Template Library: Function objects -// Function objects are objects specifically designed to be used with a syntax similar to that of functions. -// -// They are typically used as arguments to functions, such as predicates or comparison functions passed to standard algorithms. -// -// @reference http://www.cplusplus.com/reference/functional/ -// @author Jeongho Nam var std; (function (std) { - /** - *

Function object class for equality comparison.

- * - *

Binary function object class whose call returns whether its two arguments compare equal (as returned by - * operator ==).

- * - *

Generically, function objects are instances of a class with member function {@link IComparable.equal_to equal_to} - * defined. This member function allows the object to be used with the same syntax as a function call.

- * - * @param x First element to compare. - * @param y Second element to compare. - * - * @return Whether the arguments are equal. - */ - function equal_to(x, y) { - if (x instanceof Object && x.equal_to != undefined) - return x.equal_to(y); - else - return x == y; - } - std.equal_to = equal_to; - /** - *

Function object class for non-equality comparison.

- * - *

Binary function object class whose call returns whether its two arguments compare not equal (as returned - * by operator operator!=).

- * - *

Generically, function objects are instances of a class with member function {@link IComparable.equal_to equal_to} - * defined. This member function allows the object to be used with the same syntax as a function call.

- * - * @param x First element to compare. - * @param y Second element to compare. - * - * @return Whether the arguments are not equal. - */ - function not_equal_to(x, y) { - return !std.equal_to(x, y); - } - std.not_equal_to = not_equal_to; - /** - *

Function for less-than inequality comparison.

- * - *

Binary function returns whether the its first argument compares less than the second.

- * - *

Generically, function objects are instances of a class with member function {@link IComparable.less less} - * defined. If an object doesn't have the method, then its own uid will be used to compare insteadly. - * This member function allows the object to be used with the same syntax as a function call.

- * - *

Objects of this class can be used on standard algorithms such as {@link sort sort()}, - * {@link merge merge()} or {@link TreeMap.lower_bound lower_bound()}.

- * - * @param Type of arguments to compare by the function call. The type shall supporrt the operation - * operator<() or method {@link IComparable.less less}. - * - * @param x First element, the standard of comparison. - * @param y Second element compare with the first. - * - * @return Whether the first parameter is less than the second. - */ - function less(x, y) { - if (x instanceof Object) - if (x.less != undefined) - return x.less(y); - else - return x.__get_m_iUID() < y.__get_m_iUID(); - else - return x < y; - } - std.less = less; - /** - *

Function object class for less-than-or-equal-to comparison.

- * - *

Binary function object class whose call returns whether the its first argument compares {@link less less than} or - * {@link equal_to equal to} the second (as returned by operator <=).

- * - *

Generically, function objects are instances of a class with member function {@link IComparable.less less} - * and {@link IComparable.equal_to equal_to} defined. This member function allows the object to be used with the same - * syntax as a function call.

- * - * @param x First element, the standard of comparison. - * @param y Second element compare with the first. - * - * @return Whether the x is {@link less less than} or {@link equal_to equal to} the y. - */ - function less_equal(x, y) { - return std.less(x, y) || std.equal_to(x, y); - } - std.less_equal = less_equal; - /** - *

Function for greater-than inequality comparison.

- * - *

Binary function returns whether the its first argument compares greater than the second.

- * - *

Generically, function objects are instances of a class with member function {@link less} and - * {@link equal_to equal_to()} defined. If an object doesn't have those methods, then its own uid will be used - * to compare insteadly. This member function allows the object to be used with the same syntax as a function - * call.

- * - *

Objects of this class can be used on standard algorithms such as {@link sort sort()}, - * {@link merge merge()} or {@link TreeMap.lower_bound lower_bound()}.

- * - * @param Type of arguments to compare by the function call. The type shall supporrt the operation - * operator>() or method {@link IComparable.greater greater}. - * - * @return Whether the x is greater than the y. - */ - function greater(x, y) { - return !std.less_equal(x, y); - } - std.greater = greater; - /** - *

Function object class for greater-than-or-equal-to comparison.

- * - *

Binary function object class whose call returns whether the its first argument compares - * {@link greater greater than} or {@link equal_to equal to} the second (as returned by operator >=).

- * - *

Generically, function objects are instances of a class with member function {@link IComparable.less less} - * defined. If an object doesn't have the method, then its own uid will be used to compare insteadly. - * This member function allows the object to be used with the same syntax as a function call.

- * - * @param x First element, the standard of comparison. - * @param y Second element compare with the first. - * - * @return Whether the x is {@link greater greater than} or {@link equal_to equal to} the y. - */ - function greater_equal(x, y) { - return !std.less(x, y); - } - std.greater_equal = greater_equal; - /** - *

Logical AND function object class.

- * - *

Binary function object class whose call returns the result of the logical "and" operation between its two - * arguments (as returned by operator &&).

- * - *

Generically, function objects are instances of a class with member function operator() defined. This member - * function allows the object to be used with the same syntax as a function call.

- * - * @param x First element. - * @param y Second element. - * - * @return Result of logical AND operation. - */ - function logical_and(x, y) { - return x && y; - } - std.logical_and = logical_and; - /** - *

Logical OR function object class.

- * - *

Binary function object class whose call returns the result of the logical "or" operation between its two - * arguments (as returned by operator ||).

- * - *

Generically, function objects are instances of a class with member function operator() defined. This member - * function allows the object to be used with the same syntax as a function call.

- * - * @param x First element. - * @param y Second element. - * - * @return Result of logical OR operation. - */ - function logical_or(x, y) { - return x || y; - } - std.logical_or = logical_or; - /** - *

Logical NOT function object class.

- * - *

Unary function object class whose call returns the result of the logical "not" operation on its argument - * (as returned by operator !).

- * - *

Generically, function objects are instances of a class with member function operator() defined. This member - * function allows the object to be used with the same syntax as a function call.

- * - * @param x Target element. - * - * @return Result of logical NOT operation. - */ - function logical_not(x) { - return !x; - } - std.logical_not = logical_not; - /** - *

Bitwise AND function object class.

- * - *

Binary function object class whose call returns the result of applying the bitwise "and" operation between - * its two arguments (as returned by operator &).

- * - * @param x First element. - * @param y Second element. - * - * @return Result of bitwise AND operation. - */ - function bit_and(x, y) { - return x & y; - } - std.bit_and = bit_and; - /** - *

Bitwise OR function object class.

- * - *

Binary function object class whose call returns the result of applying the bitwise "and" operation between - * its two arguments (as returned by operator &).

- * - * @param x First element. - * @param y Second element. - * - * @return Result of bitwise OR operation. - */ - function bit_or(x, y) { - return x | y; - } - std.bit_or = bit_or; - /** - *

Bitwise XOR function object class.

- * - *

Binary function object class whose call returns the result of applying the bitwise "exclusive or" - * operation between its two arguments (as returned by operator ^).

+ /** + *

An iterator of {@link MapContainer map container}.

* - * @param x First element. - * @param y Second element. + *

+ *

* - * @return Result of bitwise XOR operation. - */ - function bit_xor(x, y) { - return x ^ y; - } - std.bit_xor = bit_xor; - function hash(par) { - var type = typeof par; - if (type == "number") - return hash_of_number(par); - else if (type == "string") - return hash_of_string(par); - else - return hash_of_object(par); - } - std.hash = hash; - /** - * @hidden + * @author Jeongho Nam */ - function hash_of_number(val) { - // ------------------------------------------ - // IN C++ - // CONSIDER A NUMBER AS A STRING - // HASH((CHAR*)&VAL, 8) - // ------------------------------------------ - // CONSTRUCT BUFFER AND BYTE_ARRAY - var buffer = new ArrayBuffer(8); - var byteArray = new Int8Array(buffer); - var valueArray = new Float64Array(buffer); - valueArray[0] = val; - var code = 2166136261; - for (var i = 0; i < byteArray.length; i++) { - var byte = (byteArray[i] < 0) ? byteArray[i] + 256 : byteArray[i]; - code ^= byte; - code *= 16777619; + var MapIterator = (function (_super) { + __extends(MapIterator, _super); + /* --------------------------------------------------------- + CONSTRUCTORS + --------------------------------------------------------- */ + /** + * Construct from the {@link MapContainer source map} and {@link ListIterator list iterator}. + * + * @param source The source {@link MapContainer}. + * @param list_iterator A {@link ListIterator} pointing {@link Pair} of key and value. + */ + function MapIterator(source, list_iterator) { + _super.call(this, source); + this.list_iterator_ = list_iterator; } - return Math.abs(code); - } + /* --------------------------------------------------------- + MOVERS + --------------------------------------------------------- */ + /** + * Get iterator to previous element. + */ + MapIterator.prototype.prev = function () { + return new MapIterator(this.map, this.list_iterator_.prev()); + }; + /** + * Get iterator to next element. + */ + MapIterator.prototype.next = function () { + return new MapIterator(this.map, this.list_iterator_.next()); + }; + /** + * Advances the Iterator by n element positions. + * + * @param step Number of element positions to advance. + * @return An advanced Iterator. + */ + MapIterator.prototype.advance = function (step) { + return new MapIterator(this.map, this.list_iterator_.advance(step)); + }; + Object.defineProperty(MapIterator.prototype, "map", { + /* --------------------------------------------------------- + ACCESSORS + --------------------------------------------------------- */ + /** + * @hidden + */ + get: function () { + return this.source_; + }, + enumerable: true, + configurable: true + }); + /** + * Get ListIterator. + */ + MapIterator.prototype.get_list_iterator = function () { + return this.list_iterator_; + }; + Object.defineProperty(MapIterator.prototype, "value", { + /** + * @inheritdoc + */ + get: function () { + return this.list_iterator_.value; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(MapIterator.prototype, "first", { + /** + * Get first, key element. + */ + get: function () { + return this.list_iterator_.value.first; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(MapIterator.prototype, "second", { + /** + * Get second, value element. + */ + get: function () { + return this.list_iterator_.value.second; + }, + /** + * Set second value. + */ + set: function (val) { + this.list_iterator_.value.second = val; + }, + enumerable: true, + configurable: true + }); + /* --------------------------------------------------------- + COMPARISONS + --------------------------------------------------------- */ + /** + *

Whether an iterator is equal with the iterator.

+ * + *

Compare two iterators and returns whether they are equal or not.

+ * + * @param obj An iterator to compare + * @return Indicates whether equal or not. + */ + MapIterator.prototype.equal_to = function (obj) { + return this.source_ == obj.source_ && this.list_iterator_.equal_to(obj.list_iterator_); + }; + MapIterator.prototype.less = function (obj) { + return std.less(this.first, obj.first); + }; + MapIterator.prototype.hash = function () { + return std.hash(this.first); + }; + MapIterator.prototype.swap = function (obj) { + this.list_iterator_.swap(obj.list_iterator_); + }; + return MapIterator; + }(std.Iterator)); + std.MapIterator = MapIterator; /** - * @hidden + *

A reverse-iterator of {@link MapContainer map container}.

+ * + *

+ *

+ * + * @author Jeongho Nam */ - function hash_of_string(str) { - var code = 2166136261; - for (var i = 0; i < str.length; i++) { - code ^= str.charCodeAt(i); - code *= 16777619; + var MapReverseIterator = (function (_super) { + __extends(MapReverseIterator, _super); + /* --------------------------------------------------------- + CONSTRUCTORS + --------------------------------------------------------- */ + /** + * Construct from base iterator. + * + * @param base A reference of the base iterator, which iterates in the opposite direction. + */ + function MapReverseIterator(base) { + _super.call(this, base); } - return Math.abs(code); - } - /** - * @hidden - */ - function hash_of_object(obj) { - if (obj.hash != undefined) - return obj.hash(); - else - return hash_of_number(obj.__get_m_iUID()); - } - /* --------------------------------------------------------- - UNIQUE ID FOR OBJECTS - --------------------------------------------------------- */ - // Incremental sequence of unique id for objects. - /** - * @hidden - */ - var __s_iUID; - if (__s_iUID == undefined) - __s_iUID = 0; - if (Object.prototype.hasOwnProperty("__get_m_iUID") == false) { - Object.defineProperties(Object.prototype, { - "__get_m_iUID": { - value: function () { - if (this.hasOwnProperty("__m_iUID") == false) { - var uid = ++__s_iUID; - Object.defineProperty(this, "__m_iUID", { - "get": function () { - return uid; - } - }); + /** + * @hidden + */ + MapReverseIterator.prototype.create_neighbor = function (base) { + return new MapReverseIterator(base); + }; + Object.defineProperty(MapReverseIterator.prototype, "first", { + /* --------------------------------------------------------- + ACCESSORS + --------------------------------------------------------- */ + /** + * Get first, key element. + */ + get: function () { + return this.base_.first; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(MapReverseIterator.prototype, "second", { + /** + * Get second, value element. + */ + get: function () { + return this.base_.second; + }, + /** + * Set second value. + */ + set: function (val) { + this.base_.second = val; + }, + enumerable: true, + configurable: true + }); + return MapReverseIterator; + }(std.ReverseIterator)); + std.MapReverseIterator = MapReverseIterator; +})(std || (std = {})); +/// +/// +var std; +(function (std) { + var base; + (function (base) { + /** + *

An abstract unique-map.

+ * + *

{@link UniqueMap UniqueMaps} are associative containers that store elements formed by a combination of a + * key value (Key) and a mapped value (T), and which allows for fast retrieval of + * individual elements based on their keys.

+ * + *

In a {@link MapContainer}, the key values are generally used to uniquely identify the elements, + * while the mapped values store the content associated to this key. The types of key and + * mapped value may differ, and are grouped together in member type value_type, which is a + * {@link Pair} type combining both:

+ * + *

typedef pair value_type;

+ * + *

{@link UniqueMap} stores elements, keeps sequence and enables indexing by inserting elements into a + * {@link List} and registering {@link ListIterator iterators} of the {@link data_ list container} to an index + * table like {@link RBTree tree} or {@link HashBuckets hash-table}.

+ * + *

+ *

+ * + *

Container properties

+ *
+ *
Associative
+ *
+ * Elements in associative containers are referenced by their key and not by their absolute position + * in the container. + *
+ * + *
Map
+ *
+ * Each element associates a key to a mapped value: + * Keys are meant to identify the elements whose main content is the mapped value. + *
+ * + *
Unique keys
+ *
No two elements in the container can have equivalent keys.
+ *
+ * + * @param Type of the keys. Each element in a map is uniquely identified by its key value. + * @param Type of the mapped value. Each element in a map stores some data as its mapped value. + * + * @author Jeongho Nam + */ + var UniqueMap = (function (_super) { + __extends(UniqueMap, _super); + function UniqueMap() { + _super.apply(this, arguments); + } + /* --------------------------------------------------------- + ACCESSORS + --------------------------------------------------------- */ + /** + * @inheritdoc + */ + UniqueMap.prototype.count = function (key) { + return this.find(key).equal_to(this.end()) ? 0 : 1; + }; + /** + *

Get an element

+ * + *

Returns a reference to the mapped value of the element identified with key.

+ * + * @param key Key value of the element whose mapped value is accessed. + * + * @throw exception out of range + * + * @return A reference object of the mapped value (_Ty) + */ + UniqueMap.prototype.get = function (key) { + var it = this.find(key); + if (it.equal_to(this.end()) == true) + throw new std.OutOfRange("unable to find the matched key."); + return it.second; + }; + /** + *

Set an item as the specified identifier.

+ * + *

If the identifier is already in map, change value of the identifier. If not, then insert the object + * with the identifier.

+ * + * @param key Key value of the element whose mapped value is accessed. + * @param val Value, the item. + */ + UniqueMap.prototype.set = function (key, val) { + this.insert_or_assign(key, val); + }; + UniqueMap.prototype.extract = function (param) { + if (param instanceof std.MapIterator) + return this.extract_by_iterator(param); + else if (param instanceof std.MapReverseIterator) + return this.extract_by_reverse_iterator(param); + else + return this.extract_by_key(param); + }; + /** + * @hidden + */ + UniqueMap.prototype.extract_by_key = function (key) { + var it = this.find(key); + if (it.equal_to(this.end()) == true) + throw new std.OutOfRange("No such key exists."); + var ret = it.value; + this.erase(it); + return ret; + }; + /** + * @hidden + */ + UniqueMap.prototype.extract_by_iterator = function (it) { + if (it.equal_to(this.end()) == true || this.has(it.first) == false) + return this.end(); + this.erase(it); + return it; + }; + /** + * @hidden + */ + UniqueMap.prototype.extract_by_reverse_iterator = function (it) { + this.extract_by_iterator(it.base().next()); + return it; + }; + UniqueMap.prototype.emplace = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i - 0] = arguments[_i]; + } + if (args.length == 1) + return this._Insert_by_pair(args[0]); + else + return this._Insert_by_pair(std.make_pair(args[0], args[1])); + }; + UniqueMap.prototype.insert = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i - 0] = arguments[_i]; + } + return _super.prototype.insert.apply(this, args); + }; + UniqueMap.prototype.insert_or_assign = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i - 0] = arguments[_i]; + } + if (args.length == 2) { + return this.insert_or_assign_with_key_value(args[0], args[1]); + } + else if (args.length == 3) { + var ret = void 0; + var is_reverse_iterator = false; + // REVERSE_ITERATOR TO ITERATOR + if (args[0] instanceof std.MapReverseIterator) { + is_reverse_iterator = true; + args[0] = args[0].base().prev(); } - return this.__m_iUID; + // INSERT OR ASSIGN AN ELEMENT + ret = this.insert_or_assign_with_hint(args[0], args[1], args[2]); + // RETURN BRANCHES + if (is_reverse_iterator == true) + return new std.MapReverseIterator(ret.next()); + else + return ret; + } + }; + /** + * @hidden + */ + UniqueMap.prototype.insert_or_assign_with_key_value = function (key, value) { + var it = this.find(key); + if (it.equal_to(this.end()) == true) + return this._Insert_by_pair(std.make_pair(key, value)); + else { + it.second = value; + return std.make_pair(it, false); + } + }; + /** + * @hidden + */ + UniqueMap.prototype.insert_or_assign_with_hint = function (hint, key, value) { + return this.insert_or_assign_with_key_value(key, value).first; + }; + return UniqueMap; + }(base.MapContainer)); + base.UniqueMap = UniqueMap; + })(base = std.base || (std.base = {})); +})(std || (std = {})); +/// +/// +var std; +(function (std) { + var base; + (function (base) { + /** + *

An abstract multi-map.

+ * + *

{@link MultiMap MultiMaps} are associative containers that store elements formed by a combination of a + * key value (Key) and a mapped value (T), and which allows for fast retrieval of + * individual elements based on their keys.

+ * + *

In a {@link MapContainer}, the key values are generally used to identify the elements, while the + * mapped values store the content associated to this key. The types of key and + * mapped value may differ, and are grouped together in member type value_type, which is a + * {@link Pair} type combining both:

+ * + *

typedef pair value_type;

+ * + *

{@link UniqueMap} stores elements, keeps sequence and enables indexing by inserting elements into a + * {@link List} and registering {@link ListIterator iterators} of the {@link data_ list container} to an index + * table like {@link RBTree tree} or {@link HashBuckets hash-table}.

+ * + *

+ *

+ * + *

Container properties

+ *
+ *
Associative
+ *
+ * Elements in associative containers are referenced by their key and not by their absolute position + * in the container. + *
+ * + *
Map
+ *
+ * Each element associates a key to a mapped value: + * Keys are meant to identify the elements whose main content is the mapped value. + *
+ * + *
Multiple equivalent keys
+ *
Multiple elements in the container can have equivalent keys.
+ *
+ * + * @param Type of the keys. Each element in a map is identified by its key value. + * @param Type of the mapped value. Each element in a map stores some data as its mapped value. + * + * @author Jeongho Nam + */ + var MultiMap = (function (_super) { + __extends(MultiMap, _super); + function MultiMap() { + _super.apply(this, arguments); + } + MultiMap.prototype.emplace = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i - 0] = arguments[_i]; + } + if (args.length == 1) + return this._Insert_by_pair(args[0]); + else + return this._Insert_by_pair(std.make_pair(args[0], args[1])); + }; + MultiMap.prototype.insert = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i - 0] = arguments[_i]; } - } - }); - } - function swap(left, right) { - left.swap(right); - } - std.swap = swap; + return _super.prototype.insert.apply(this, args); + }; + return MultiMap; + }(base.MapContainer)); + base.MultiMap = MultiMap; + })(base = std.base || (std.base = {})); })(std || (std = {})); +/// +/// +/// var std; (function (std) { - function bind(fn) { - var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; - } - var this_arg = null; - var parameters = []; - var placeholder_count = 0; - for (var i = 0; i < args.length; i++) { - if (i == 0 && args[0] instanceof Object && args[0] instanceof std.placeholders.PlaceHolder == false) { - // retrieve the object; items[0] - for (var key in args[0]) - if (args[0][key] == fn) { - // found the this_arg - this_arg = args[0]; - break; - } - if (this_arg != null) - continue; - } - // the placeholder also fills parameters - if (args[i] instanceof std.placeholders.PlaceHolder) - placeholder_count++; - parameters.push(args[i]); - } - //////////////////// - // FUNCTION TO BE RETURNED - //////////////////// - var ret = function () { + /** + *

Hashed, unordered map.

+ * + *

{@link HashMap}s are associative containers that store elements formed by the combination of a key value + * and a mapped value, and which allows for fast retrieval of individual elements based on their keys. + *

+ * + *

In an {@link HashMap}, the key value is generally used to uniquely identify the element, while the + * mapped value is an object with the content associated to this key. Types of key and + * mapped value may differ.

+ * + *

Internally, the elements in the {@link HashMap} are not sorted in any particular order with respect to either + * their key or mapped values, but organized into buckets depending on their hash values to allow + * for fast access to individual elements directly by their key values (with a constant average time complexity + * on average).

+ * + *

{@link HashMap} containers are faster than {@link TreeMap} containers to access individual elements by their + * key, although they are generally less efficient for range iteration through a subset of their elements.

+ * + *

+ * + *

+ * + *

Container properties

+ *
+ *
Associative
+ *
Elements in associative containers are referenced by their key and not by their absolute + * position in the container.
+ * + *
Hashed
+ *
Hashed containers organize their elements using hash tables that allow for fast access to elements + * by their key.
+ * + *
Map
+ *
Each element associates a key to a mapped value: + * Keys are meant to identify the elements whose main content is the mapped value.
+ * + *
Unique keys
+ *
No two elements in the container can have equivalent keys.
+ *
+ * + * @param Type of the key values. + * Each element in an {@link HashMap} is uniquely identified by its key value. + * @param Type of the mapped value. + * Each element in an {@link HashMap} is used to store some data as its mapped value. + * + * @reference http://www.cplusplus.com/reference/unordered_map/unordered_map + * @author Jeongho Nam + */ + var HashMap = (function (_super) { + __extends(HashMap, _super); + function HashMap() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i - 0] = arguments[_i]; } - if (args.length == 0) - return fn.apply(this_arg, parameters); - var thisArg = this_arg; - var argArray = parameters.slice(); - // 1st argument is thisArg? - if (thisArg == null && (parameters.length == 0 || parameters[0] instanceof std.placeholders.PlaceHolder) && args[0] instanceof Object) - for (var key in args[0]) - if (args[0][key] == fn) { - thisArg = args[0]; - argArray.splice(0, 1); - //lastIndex++; - break; - } - // fill argArray from placeholders - for (var i = 0; i < argArray.length; i++) - if (argArray[i] instanceof std.placeholders.PlaceHolder) - argArray[i] = args[argArray[i].index - 1]; - // arguments are over the placeholder_count - if (args.length > placeholder_count) - for (var i = placeholder_count; i < args.length; i++) - if (i == 0 && (this_arg == null && thisArg != null)) - continue; // thisArg - else - argArray.push(args[i]); - return fn.apply(thisArg, argArray); + // INIT MEMBERS + _super.call(this); + this.hash_buckets_ = new std.base.MapHashBuckets(this); + // BRANCH - METHOD OVERLOADINGS + if (args.length == 0) { + } + else if (args.length == 1 && args[0] instanceof HashMap) { + // COPY CONSTRUCTOR + var container = args[0]; + this.assign(container.begin(), container.end()); + } + else if (args.length == 1 && args[0] instanceof Array) { + // INITIALIZER LIST CONSTRUCTOR + var items = args[0]; + this.rehash(items.length * std.base.Hash.RATIO); + this.push.apply(this, items); + } + else if (args.length == 2 && args[0] instanceof std.Iterator && args[1] instanceof std.Iterator) { + // RANGE CONSTRUCTOR + var first = args[0]; + var last = args[1]; + this.assign(first, last); + } + } + /* --------------------------------------------------------- + ASSIGN & CLEAR + --------------------------------------------------------- */ + /** + * @inheritdoc + */ + HashMap.prototype.clear = function () { + this.hash_buckets_.clear(); + _super.prototype.clear.call(this); + }; + /* ========================================================= + ACCESSORS + - MEMBER + - HASH + ============================================================ + MEMBER + --------------------------------------------------------- */ + /** + * @inheritdoc + */ + HashMap.prototype.find = function (key) { + return this.hash_buckets_.find(key); + }; + HashMap.prototype.begin = function (index) { + if (index === void 0) { index = -1; } + if (index == -1) + return _super.prototype.begin.call(this); + else + return this.hash_buckets_.at(index).front(); + }; + HashMap.prototype.end = function (index) { + if (index === void 0) { index = -1; } + if (index == -1) + return _super.prototype.end.call(this); + else + return this.hash_buckets_.at(index).back().next(); + }; + HashMap.prototype.rbegin = function (index) { + if (index === void 0) { index = -1; } + if (index == -1) + return _super.prototype.rbegin.call(this); + else + return new std.MapReverseIterator(this.end(index)); + }; + HashMap.prototype.rend = function (index) { + if (index === void 0) { index = -1; } + if (index == -1) + return _super.prototype.rend.call(this); + else + return new std.MapReverseIterator(this.begin(index)); + }; + /* --------------------------------------------------------- + HASH + --------------------------------------------------------- */ + /** + * @inheritdoc + */ + HashMap.prototype.bucket_count = function () { + return this.hash_buckets_.size(); + }; + /** + * @inheritdoc + */ + HashMap.prototype.bucket_size = function (index) { + return this.hash_buckets_.at(index).size(); + }; + HashMap.prototype.max_load_factor = function (z) { + if (z === void 0) { z = -1; } + if (z == -1) + return this.size() / this.bucket_count(); + else + this.rehash(Math.ceil(this.bucket_count() / z)); + }; + /** + * @inheritdoc + */ + HashMap.prototype.bucket = function (key) { + return std.hash(key) % this.hash_buckets_.size(); + }; + /** + * @inheritdoc + */ + HashMap.prototype.reserve = function (n) { + this.hash_buckets_.rehash(Math.ceil(n * this.max_load_factor())); + }; + /** + * @inheritdoc + */ + HashMap.prototype.rehash = function (n) { + if (n <= this.bucket_count()) + return; + this.hash_buckets_.rehash(n); + }; + /* ========================================================= + ELEMENTS I/O + - INSERT + - POST-PROCESS + - SWAP + ============================================================ + INSERT + --------------------------------------------------------- */ + /** + * @hidden + */ + HashMap.prototype._Insert_by_pair = function (pair) { + // TEST WHETHER EXIST + var it = this.find(pair.first); + if (it.equal_to(this.end()) == false) + return std.make_pair(it, false); + // INSERT + this["data_"].push_back(pair); + it = it.prev(); + // POST-PROCESS + this._Handle_insert(it, it.next()); + return std.make_pair(it, true); }; - return ret; - } - std.bind = bind; -})(std || (std = {})); -/** - *

Bind argument placeholders.

- * - *

This namespace declares an unspecified number of objects: _1, _2, _3, ..., which are - * used to specify placeholders in calls to function {@link std.bind}.

- * - *

When the function object returned by bind is called, an argument with placeholder {@link _1} is replaced by the - * first argument in the call, {@link _2} is replaced by the second argument in the call, and so on... For example:

- * - * - * let vec: Vector = new Vector(); - * - * let bind = std.bind(Vector.insert, _1, vec.end(), _2, _3); - * bind.apply(vec, 5, 1); // vec.insert(vec.end(), 5, 1); - * // [1, 1, 1, 1, 1] - * - * - *

When a call to {@link bind} is used as a subexpression in another call to bind, the {@link placeholders} - * are relative to the outermost {@link bind} expression.

- * - * @reference http://www.cplusplus.com/reference/functional/placeholders/ - * @author Jeongho Nam - */ -var std; -(function (std) { - var placeholders; - (function (placeholders) { /** * @hidden */ - var PlaceHolder = (function () { - function PlaceHolder(index) { - this.index_ = index; + HashMap.prototype._Insert_by_hint = function (hint, pair) { + // FIND KEY + if (this.has(pair.first) == true) + return this.end(); + // INSERT + var list_it = this["data_"].insert(hint.get_list_iterator(), pair); + // POST-PROCESS + var it = new std.MapIterator(this, list_it); + this._Handle_insert(it, it.next()); + return it; + }; + /** + * @hidden + */ + HashMap.prototype._Insert_by_range = function (first, last) { + var my_first = this.end().prev(); + var size = 0; + // INSERT ELEMENTS + for (; !first.equal_to(last); first = first.next()) { + // TEST WHETER EXIST + if (this.has(first.value.first)) + continue; + // INSERTS + this["data_"].push_back(std.make_pair(first.value.first, first.value.second)); + size++; } - Object.defineProperty(PlaceHolder.prototype, "index", { - get: function () { - return this.index_; - }, - enumerable: true, - configurable: true - }); - return PlaceHolder; - }()); - placeholders.PlaceHolder = PlaceHolder; + my_first = my_first.next(); + // IF NEEDED, HASH_BUCKET TO HAVE SUITABLE SIZE + if (this.size() + size > this.hash_buckets_.size() * std.base.Hash.MAX_RATIO) + this.hash_buckets_.rehash((this.size() + size) * std.base.Hash.RATIO); + // POST-PROCESS + this._Handle_insert(my_first, this.end()); + }; + /* --------------------------------------------------------- + POST-PROCESS + --------------------------------------------------------- */ /** - * Replaced by the first argument in the function call. + * @inheritdoc */ - placeholders._1 = new PlaceHolder(1); + HashMap.prototype._Handle_insert = function (first, last) { + for (; !first.equal_to(last); first = first.next()) + this.hash_buckets_.insert(first); + }; /** - * Replaced by the second argument in the function call. + * @inheritdoc */ - placeholders._2 = new PlaceHolder(2); + HashMap.prototype._Handle_erase = function (first, last) { + for (; !first.equal_to(last); first = first.next()) + this.hash_buckets_.erase(first); + }; /** - * Replaced by the third argument in the function call. + * @inheritdoc */ - placeholders._3 = new PlaceHolder(3); - placeholders._4 = new PlaceHolder(4); - placeholders._5 = new PlaceHolder(5); - placeholders._6 = new PlaceHolder(6); - placeholders._7 = new PlaceHolder(7); - placeholders._8 = new PlaceHolder(8); - placeholders._9 = new PlaceHolder(9); - placeholders._10 = new PlaceHolder(10); - placeholders._11 = new PlaceHolder(11); - placeholders._12 = new PlaceHolder(12); - placeholders._13 = new PlaceHolder(13); - placeholders._14 = new PlaceHolder(14); - placeholders._15 = new PlaceHolder(15); - placeholders._16 = new PlaceHolder(16); - placeholders._17 = new PlaceHolder(17); - placeholders._18 = new PlaceHolder(18); - placeholders._19 = new PlaceHolder(19); - placeholders._20 = new PlaceHolder(20); - })(placeholders = std.placeholders || (std.placeholders = {})); + HashMap.prototype.swap = function (obj) { + if (obj instanceof HashMap) { + this._Swap(obj); + _a = [obj.hash_buckets_, this.hash_buckets_], this.hash_buckets_ = _a[0], obj.hash_buckets_ = _a[1]; + } + else + _super.prototype.swap.call(this, obj); + var _a; + }; + return HashMap; + }(std.base.UniqueMap)); + std.HashMap = HashMap; })(std || (std = {})); /// -/// /// var std; (function (std) { /** - *

Hashed, unordered map.

+ *

Hashed, unordered Multimap.

* - *

{@link HashMap}s are associative containers that store elements formed by the combination of a key value - * and a mapped value, and which allows for fast retrieval of individual elements based on their keys. - *

+ *

{@link HashMultiMap}s are associative containers that store elements formed by the combination of + * a key value and a mapped value, much like {@link HashMultiMap} containers, but allowing + * different elements to have equivalent keys.

* - *

In an {@link HashMap}, the key value is generally used to uniquely identify the element, while the - * mapped value is an object with the content associated to this key. Types of key and - * mapped value may differ.

+ *

In an {@link HashMultiMap}, the key value is generally used to uniquely identify the + * element, while the mapped value is an object with the content associated to this key. + * Types of key and mapped value may differ.

* - *

Internally, the elements in the {@link HashMap} are not sorted in any particular order with respect to either - * their key or mapped values, but organized into buckets depending on their hash values to allow - * for fast access to individual elements directly by their key values (with a constant average time complexity - * on average).

+ *

Internally, the elements in the {@link HashMultiMap} are not sorted in any particular order with + * respect to either their key or mapped values, but organized into buckets depending on + * their hash values to allow for fast access to individual elements directly by their key values + * (with a constant average time complexity on average).

* - *

{@link HashMap} containers are faster than {@link TreeMap} containers to access individual elements by their - * key, although they are generally less efficient for range iteration through a subset of their elements.

+ *

Elements with equivalent keys are grouped together in the same bucket and in such a way that + * an iterator can iterate through all of them. Iterators in the container are doubly linked iterators.

* - *

- * + *

+ * *

* *

Container properties

*
- *
Associative
- *
Elements in associative containers are referenced by their key and not by their absolute + *
Associative
+ *
Elements in associative containers are referenced by their key and not by their absolute * position in the container.
* - *
Hashed
- *
Hashed containers organize their elements using hash tables that allow for fast access to elements + *
Hashed
+ *
Hashed containers organize their elements using hash tables that allow for fast access to elements * by their key.
* - *
Map
- *
Each element associates a key to a mapped value: + *
Map
+ *
Each element associates a key to a mapped value: * Keys are meant to identify the elements whose main content is the mapped value.
* - *
Unique keys
- *
No two elements in the container can have equivalent keys.
+ *
Multiple equivalent keys
+ *
The container can hold multiple elements with equivalent keys.
*
* * @param Type of the key values. - * Each element in an {@link HashMap} is uniquely identified by its key value. + * Each element in an {@link HashMultiMap} is identified by a key value. * @param Type of the mapped value. - * Each element in an {@link HashMap} is used to store some data as its mapped value. + * Each element in an {@link HashMultiMap} is used to store some data as its mapped value. * - * @reference http://www.cplusplus.com/reference/unordered_map/unordered_map + * @reference http://www.cplusplus.com/reference/unordered_map/unordered_multimap * @author Jeongho Nam */ - var HashMap = (function (_super) { - __extends(HashMap, _super); - function HashMap() { + var HashMultiMap = (function (_super) { + __extends(HashMultiMap, _super); + function HashMultiMap() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i - 0] = arguments[_i]; @@ -6947,7 +4974,7 @@ var std; // BRANCH - METHOD OVERLOADINGS if (args.length == 0) { } - else if (args.length == 1 && args[0] instanceof HashMap) { + else if (args.length == 1 && args[0] instanceof HashMultiMap) { // COPY CONSTRUCTOR var container = args[0]; this.assign(container.begin(), container.end()); @@ -6971,7 +4998,7 @@ var std; /** * @inheritdoc */ - HashMap.prototype.clear = function () { + HashMultiMap.prototype.clear = function () { this.hash_buckets_.clear(); _super.prototype.clear.call(this); }; @@ -6985,36 +5012,44 @@ var std; /** * @inheritdoc */ - HashMap.prototype.find = function (key) { + HashMultiMap.prototype.find = function (key) { return this.hash_buckets_.find(key); }; - HashMap.prototype.begin = function (index) { + /** + * @inheritdoc + */ + HashMultiMap.prototype.count = function (key) { + // FIND MATCHED BUCKET + var index = std.hash(key) % this.hash_buckets_.item_size(); + var bucket = this.hash_buckets_.at(index); + // ITERATE THE BUCKET + var cnt = 0; + for (var i = 0; i < bucket.length; i++) + if (std.equal_to(bucket[i].first, key)) + cnt++; + return cnt; + }; + HashMultiMap.prototype.begin = function (index) { if (index === void 0) { index = -1; } if (index == -1) return _super.prototype.begin.call(this); else return this.hash_buckets_.at(index).front(); }; - HashMap.prototype.end = function (index) { + HashMultiMap.prototype.end = function (index) { if (index === void 0) { index = -1; } if (index == -1) return _super.prototype.end.call(this); else return this.hash_buckets_.at(index).back().next(); }; - HashMap.prototype.rbegin = function (index) { + HashMultiMap.prototype.rbegin = function (index) { if (index === void 0) { index = -1; } - if (index == -1) - return _super.prototype.rbegin.call(this); - else - return new std.MapReverseIterator(this.end(index)); + return new std.MapReverseIterator(this.end(index)); }; - HashMap.prototype.rend = function (index) { + HashMultiMap.prototype.rend = function (index) { if (index === void 0) { index = -1; } - if (index == -1) - return _super.prototype.rend.call(this); - else - return new std.MapReverseIterator(this.begin(index)); + return new std.MapReverseIterator(this.begin(index)); }; /* --------------------------------------------------------- HASH @@ -7022,16 +5057,16 @@ var std; /** * @inheritdoc */ - HashMap.prototype.bucket_count = function () { + HashMultiMap.prototype.bucket_count = function () { return this.hash_buckets_.size(); }; /** * @inheritdoc */ - HashMap.prototype.bucket_size = function (index) { - return this.hash_buckets_.at(index).size(); + HashMultiMap.prototype.bucket_size = function (n) { + return this.hash_buckets_.at(n).size(); }; - HashMap.prototype.max_load_factor = function (z) { + HashMultiMap.prototype.max_load_factor = function (z) { if (z === void 0) { z = -1; } if (z == -1) return this.size() / this.bucket_count(); @@ -7041,19 +5076,19 @@ var std; /** * @inheritdoc */ - HashMap.prototype.bucket = function (key) { + HashMultiMap.prototype.bucket = function (key) { return std.hash(key) % this.hash_buckets_.size(); }; /** * @inheritdoc */ - HashMap.prototype.reserve = function (n) { + HashMultiMap.prototype.reserve = function (n) { this.hash_buckets_.rehash(Math.ceil(n * this.max_load_factor())); }; /** * @inheritdoc */ - HashMap.prototype.rehash = function (n) { + HashMultiMap.prototype.rehash = function (n) { if (n <= this.bucket_count()) return; this.hash_buckets_.rehash(n); @@ -7067,27 +5102,18 @@ var std; INSERT --------------------------------------------------------- */ /** - * @hidden - */ - HashMap.prototype._Insert_by_pair = function (pair) { - // TEST WHETHER EXIST - var it = this.find(pair.first); - if (it.equal_to(this.end()) == false) - return std.make_pair(it, false); + * @hidden + */ + HashMultiMap.prototype._Insert_by_pair = function (pair) { // INSERT - this["data_"].push_back(pair); - it = it.prev(); - // POST-PROCESS - this._Handle_insert(it, it.next()); - return std.make_pair(it, true); + var it = new std.MapIterator(this, this["data_"].insert(this["data_"].end(), pair)); + this._Handle_insert(it, it.next()); // POST-PROCESS + return it; }; /** * @hidden */ - HashMap.prototype._Insert_by_hint = function (hint, pair) { - // FIND KEY - if (this.has(pair.first) == true) - return this.end(); + HashMultiMap.prototype._Insert_by_hint = function (hint, pair) { // INSERT var list_it = this["data_"].insert(hint.get_list_iterator(), pair); // POST-PROCESS @@ -7098,22 +5124,13 @@ var std; /** * @hidden */ - HashMap.prototype._Insert_by_range = function (first, last) { - var my_first = this.end().prev(); - var size = 0; + HashMultiMap.prototype._Insert_by_range = function (first, last) { // INSERT ELEMENTS - for (; !first.equal_to(last); first = first.next()) { - // TEST WHETER EXIST - if (this.has(first.value.first)) - continue; - // INSERTS - this["data_"].push_back(std.make_pair(first.value.first, first.value.second)); - size++; - } - my_first = my_first.next(); + var list_iterator = this["data_"].insert(this["data_"].end(), first, last); + var my_first = new std.MapIterator(this, list_iterator); // IF NEEDED, HASH_BUCKET TO HAVE SUITABLE SIZE - if (this.size() + size > this.hash_buckets_.size() * std.base.Hash.MAX_RATIO) - this.hash_buckets_.rehash((this.size() + size) * std.base.Hash.RATIO); + if (this.size() > this.hash_buckets_.item_size() * std.base.Hash.MAX_RATIO) + this.hash_buckets_.rehash(this.size() * std.base.Hash.RATIO); // POST-PROCESS this._Handle_insert(my_first, this.end()); }; @@ -7123,22 +5140,22 @@ var std; /** * @inheritdoc */ - HashMap.prototype._Handle_insert = function (first, last) { + HashMultiMap.prototype._Handle_insert = function (first, last) { for (; !first.equal_to(last); first = first.next()) this.hash_buckets_.insert(first); }; /** * @inheritdoc */ - HashMap.prototype._Handle_erase = function (first, last) { + HashMultiMap.prototype._Handle_erase = function (first, last) { for (; !first.equal_to(last); first = first.next()) this.hash_buckets_.erase(first); }; /** * @inheritdoc */ - HashMap.prototype.swap = function (obj) { - if (obj instanceof HashMap) { + HashMultiMap.prototype.swap = function (obj) { + if (obj instanceof HashMultiMap) { this._Swap(obj); _a = [obj.hash_buckets_, this.hash_buckets_], this.hash_buckets_ = _a[0], obj.hash_buckets_ = _a[1]; } @@ -7146,268 +5163,450 @@ var std; _super.prototype.swap.call(this, obj); var _a; }; - return HashMap; - }(std.base.UniqueMap)); - std.HashMap = HashMap; + return HashMultiMap; + }(std.base.MultiMap)); + std.HashMultiMap = HashMultiMap; +})(std || (std = {})); +/// +/// +/// +var std; +(function (std) { + var base; + (function (base) { + /** + *

An abstract set.

+ * + *

{@link SetContainer SetContainers} are containers that store elements allowing fast retrieval of + * individual elements based on their value.

+ * + *

In an {@link SetContainer}, the value of an element is at the same time its key, used to + * identify it. Keys are immutable, therefore, the elements in an {@link SetContainer} cannot be + * modified once in the container - they can be inserted and removed, though.

+ * + *

{@link SetContainer} stores elements, keeps sequence and enables indexing by inserting elements into a + * {@link List} and registering {@link ListIterator iterators} of the {@link data_ list container} to an index + * table like {@link RBTree tree} or {@link HashBuckets hash-table}.

+ * + *

+ *

+ * + *

Container properties

+ *
+ *
Associative
+ *
+ * Elements in associative containers are referenced by their key and not by their absolute + * position in the container. + *
+ * + *
Set
+ *
The value of an element is also the key used to identify it.
+ *
+ * + * @param Type of the elements. Each element in a {@link SetContainer} container is also identified + * by this value (each value is itself also the element's key). + * + * @author Jeongho Nam + */ + var SetContainer = (function (_super) { + __extends(SetContainer, _super); + /* --------------------------------------------------------- + CONSTURCTORS + --------------------------------------------------------- */ + /** + * Default Constructor. + */ + function SetContainer() { + _super.call(this); + this.data_ = new std.List(); + } + /** + * @inheritdoc + */ + SetContainer.prototype.assign = function (begin, end) { + // INSERT + this.clear(); + this.insert(begin, end); + }; + /** + * @inheritdoc + */ + SetContainer.prototype.clear = function () { + // TO BE ABSTRACT + this.data_.clear(); + }; + /** + * @inheritdoc + */ + SetContainer.prototype.begin = function () { + return new std.SetIterator(this, this.data_.begin()); + }; + /** + * @inheritdoc + */ + SetContainer.prototype.end = function () { + return new std.SetIterator(this, this.data_.end()); + }; + /** + * @inheritdoc + */ + SetContainer.prototype.rbegin = function () { + return new std.SetReverseIterator(this.end()); + }; + /** + * @inheritdoc + */ + SetContainer.prototype.rend = function () { + return new std.SetReverseIterator(this.begin()); + }; + /* --------------------------------------------------------- + ELEMENTS + --------------------------------------------------------- */ + /** + *

Whether have the item or not.

+ * + *

Indicates whether a set has an item having the specified identifier.

+ * + * @param key Key value of the element whose mapped value is accessed. + * + * @return Whether the set has an item having the specified identifier. + */ + SetContainer.prototype.has = function (val) { + return !this.find(val).equal_to(this.end()); + }; + /** + * @inheritdoc + */ + SetContainer.prototype.size = function () { + return this.data_.size(); + }; + ///** + // * @hidden + // */ + //protected _Get_data(): List + //{ + // return this.data_; + //} + /* ========================================================= + ELEMENTS I/O + - INSERT + - ERASE + - POST-PROCESS + - SWAP + ============================================================ + INSERT + --------------------------------------------------------- */ + /** + * @inheritdoc + */ + SetContainer.prototype.push = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i - 0] = arguments[_i]; + } + // TO BE ABSTRACT + for (var i = 0; i < args.length; i++) + this._Insert_by_val(args[i]); + return this.size(); + }; + SetContainer.prototype.insert = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i - 0] = arguments[_i]; + } + if (args.length == 1) + return this._Insert_by_val(args[0]); + else if (args.length == 2 && args[0] instanceof std.Iterator) { + if (args[1] instanceof std.Iterator && args[0].get_source() != this && args[1].get_source() != this) { + // IT DOESN'T CONTAIN POSITION + // RANGES TO INSERT ONLY + return this._Insert_by_range(args[0], args[1]); + } + else { + var ret = void 0; + var is_reverse_iterator = false; + // REVERSE_ITERATOR TO ITERATOR + if (args[0] instanceof std.SetReverseIterator) { + is_reverse_iterator = true; + args[0] = args[0].base().prev(); + } + // INSERT AN ELEMENT + ret = this._Insert_by_hint(args[0], args[1]); + // RETURN BRANCHES + if (is_reverse_iterator == true) + return new std.SetReverseIterator(ret.next()); + else + return ret; + } + } + }; + SetContainer.prototype.erase = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i - 0] = arguments[_i]; + } + if (args.length == 1 && (args[0] instanceof std.Iterator == false || args[0].get_source() != this)) + return this.erase_by_val(args[0]); + else if (args.length == 1) + return this.erase_by_iterator(args[0]); + else + return this.erase_by_iterator(args[0], args[1]); + }; + /** + * @hidden + */ + SetContainer.prototype.erase_by_iterator = function (first, last) { + if (last === void 0) { last = first.next(); } + var ret; + var is_reverse_iterator = false; + // REVERSE ITERATOR TO ITERATOR + if (first instanceof std.SetReverseIterator) { + is_reverse_iterator = true; + var first_it = last.base(); + var last_it = first.base(); + first = first_it; + last = last_it; + } + // ERASE ELEMENTS + ret = this.erase_by_range(first, last); + // RETURN BRANCHES + if (is_reverse_iterator == true) + return new std.SetReverseIterator(ret.next()); + else + return ret; + }; + /** + * @hidden + */ + SetContainer.prototype.erase_by_val = function (val) { + // TEST WHETHER EXISTS + var it = this.find(val); + if (it.equal_to(this.end()) == true) + return 0; + // ERASE + this.erase_by_iterator(it); + return 1; + }; + /** + * @hidden + */ + SetContainer.prototype.erase_by_range = function (begin, end) { + // ERASE + var list_iterator = this.data_.erase(begin.get_list_iterator(), end.get_list_iterator()); + // POST-PROCESS + this._Handle_erase(begin, end); + return new std.SetIterator(this, list_iterator); //begin.prev(); + }; + /* --------------------------------------------------------- + SWAP + --------------------------------------------------------- */ + /** + * @hidden + */ + SetContainer.prototype._Swap = function (obj) { + _a = [obj.data_, this.data_], this.data_ = _a[0], obj.data_ = _a[1]; + var _a; + }; + return SetContainer; + }(base.Container)); + base.SetContainer = SetContainer; + })(base = std.base || (std.base = {})); })(std || (std = {})); -/// -/// var std; (function (std) { /** - *

Hashed, unordered Multimap.

- * - *

{@link HashMultiMap}s are associative containers that store elements formed by the combination of - * a key value and a mapped value, much like {@link HashMultiMap} containers, but allowing - * different elements to have equivalent keys.

- * - *

In an {@link HashMultiMap}, the key value is generally used to uniquely identify the - * element, while the mapped value is an object with the content associated to this key. - * Types of key and mapped value may differ.

- * - *

Internally, the elements in the {@link HashMultiMap} are not sorted in any particular order with - * respect to either their key or mapped values, but organized into buckets depending on - * their hash values to allow for fast access to individual elements directly by their key values - * (with a constant average time complexity on average).

- * - *

Elements with equivalent keys are grouped together in the same bucket and in such a way that - * an iterator can iterate through all of them. Iterators in the container are doubly linked iterators.

- * - *

- * - *

- * - *

Container properties

- *
- *
Associative
- *
Elements in associative containers are referenced by their key and not by their absolute - * position in the container.
- * - *
Hashed
- *
Hashed containers organize their elements using hash tables that allow for fast access to elements - * by their key.
- * - *
Map
- *
Each element associates a key to a mapped value: - * Keys are meant to identify the elements whose main content is the mapped value.
- * - *
Multiple equivalent keys
- *
The container can hold multiple elements with equivalent keys.
- *
+ *

An iterator of a Set.

* - * @param Type of the key values. - * Each element in an {@link HashMultiMap} is identified by a key value. - * @param Type of the mapped value. - * Each element in an {@link HashMultiMap} is used to store some data as its mapped value. + *

+ *

* - * @reference http://www.cplusplus.com/reference/unordered_map/unordered_multimap * @author Jeongho Nam */ - var HashMultiMap = (function (_super) { - __extends(HashMultiMap, _super); - function HashMultiMap() { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i - 0] = arguments[_i]; - } - // INIT MEMBERS - _super.call(this); - this.hash_buckets_ = new std.base.MapHashBuckets(this); - // BRANCH - METHOD OVERLOADINGS - if (args.length == 0) { - } - else if (args.length == 1 && args[0] instanceof HashMultiMap) { - // COPY CONSTRUCTOR - var container = args[0]; - this.assign(container.begin(), container.end()); - } - else if (args.length == 1 && args[0] instanceof Array) { - // INITIALIZER LIST CONSTRUCTOR - var items = args[0]; - this.rehash(items.length * std.base.Hash.RATIO); - this.push.apply(this, items); - } - else if (args.length == 2 && args[0] instanceof std.Iterator && args[1] instanceof std.Iterator) { - // RANGE CONSTRUCTOR - var first = args[0]; - var last = args[1]; - this.assign(first, last); - } + var SetIterator = (function (_super) { + __extends(SetIterator, _super); + /** + *

Construct from source and index number.

+ * + *

Note

+ *

Do not create iterator directly.

+ *

Use begin(), find() or end() in Map instead.

+ * + * @param map The source Set to reference. + * @param index Sequence number of the element in the source Set. + */ + function SetIterator(source, it) { + _super.call(this, source); + this.list_iterator_ = it; } /* --------------------------------------------------------- - ASSIGN & CLEAR + MOVERS --------------------------------------------------------- */ /** * @inheritdoc */ - HashMultiMap.prototype.clear = function () { - this.hash_buckets_.clear(); - _super.prototype.clear.call(this); + SetIterator.prototype.prev = function () { + return new SetIterator(this.set, this.list_iterator_.prev()); }; - /* ========================================================= - ACCESSORS - - MEMBER - - HASH - ============================================================ - MEMBER - --------------------------------------------------------- */ /** * @inheritdoc */ - HashMultiMap.prototype.find = function (key) { - return this.hash_buckets_.find(key); + SetIterator.prototype.next = function () { + return new SetIterator(this.set, this.list_iterator_.next()); }; /** * @inheritdoc */ - HashMultiMap.prototype.count = function (key) { - // FIND MATCHED BUCKET - var index = std.hash(key) % this.hash_buckets_.item_size(); - var bucket = this.hash_buckets_.at(index); - // ITERATE THE BUCKET - var cnt = 0; - for (var i = 0; i < bucket.length; i++) - if (std.equal_to(bucket[i].first, key)) - cnt++; - return cnt; - }; - HashMultiMap.prototype.begin = function (index) { - if (index === void 0) { index = -1; } - if (index == -1) - return _super.prototype.begin.call(this); - else - return this.hash_buckets_.at(index).front(); - }; - HashMultiMap.prototype.end = function (index) { - if (index === void 0) { index = -1; } - if (index == -1) - return _super.prototype.end.call(this); - else - return this.hash_buckets_.at(index).back().next(); - }; - HashMultiMap.prototype.rbegin = function (index) { - if (index === void 0) { index = -1; } - return new std.MapReverseIterator(this.end(index)); + SetIterator.prototype.advance = function (size) { + return new SetIterator(this.set, this.list_iterator_.advance(size)); }; - HashMultiMap.prototype.rend = function (index) { - if (index === void 0) { index = -1; } - return new std.MapReverseIterator(this.begin(index)); + Object.defineProperty(SetIterator.prototype, "set", { + /* --------------------------------------------------------- + ACCESSORS + --------------------------------------------------------- */ + /** + * @hidden + */ + get: function () { + return this.source_; + }, + enumerable: true, + configurable: true + }); + SetIterator.prototype.get_list_iterator = function () { + return this.list_iterator_; }; + Object.defineProperty(SetIterator.prototype, "value", { + /** + * @inheritdoc + */ + get: function () { + return this.list_iterator_.value; + }, + enumerable: true, + configurable: true + }); /* --------------------------------------------------------- - HASH + COMPARISONS --------------------------------------------------------- */ /** * @inheritdoc */ - HashMultiMap.prototype.bucket_count = function () { - return this.hash_buckets_.size(); - }; - /** - * @inheritdoc - */ - HashMultiMap.prototype.bucket_size = function (n) { - return this.hash_buckets_.at(n).size(); - }; - HashMultiMap.prototype.max_load_factor = function (z) { - if (z === void 0) { z = -1; } - if (z == -1) - return this.size() / this.bucket_count(); - else - this.rehash(Math.ceil(this.bucket_count() / z)); - }; - /** - * @inheritdoc - */ - HashMultiMap.prototype.bucket = function (key) { - return std.hash(key) % this.hash_buckets_.size(); - }; - /** - * @inheritdoc - */ - HashMultiMap.prototype.reserve = function (n) { - this.hash_buckets_.rehash(Math.ceil(n * this.max_load_factor())); - }; - /** - * @inheritdoc - */ - HashMultiMap.prototype.rehash = function (n) { - if (n <= this.bucket_count()) - return; - this.hash_buckets_.rehash(n); - }; - /* ========================================================= - ELEMENTS I/O - - INSERT - - POST-PROCESS - - SWAP - ============================================================ - INSERT - --------------------------------------------------------- */ + SetIterator.prototype.equal_to = function (obj) { + return _super.prototype.equal_to.call(this, obj) && this.list_iterator_ == obj.list_iterator_; + }; /** - * @hidden + * @inheritdoc */ - HashMultiMap.prototype._Insert_by_pair = function (pair) { - // INSERT - var it = new std.MapIterator(this, this["data_"].insert(this["data_"].end(), pair)); - this._Handle_insert(it, it.next()); // POST-PROCESS - return it; + SetIterator.prototype.less = function (obj) { + return std.less(this.value, obj.value); }; /** - * @hidden + * @inheritdoc */ - HashMultiMap.prototype._Insert_by_hint = function (hint, pair) { - // INSERT - var list_it = this["data_"].insert(hint.get_list_iterator(), pair); - // POST-PROCESS - var it = new std.MapIterator(this, list_it); - this._Handle_insert(it, it.next()); - return it; + SetIterator.prototype.hash = function () { + return std.hash(this.value); }; /** - * @hidden + * @inheritdoc */ - HashMultiMap.prototype._Insert_by_range = function (first, last) { - // INSERT ELEMENTS - var list_iterator = this["data_"].insert(this["data_"].end(), first, last); - var my_first = new std.MapIterator(this, list_iterator); - // IF NEEDED, HASH_BUCKET TO HAVE SUITABLE SIZE - if (this.size() > this.hash_buckets_.item_size() * std.base.Hash.MAX_RATIO) - this.hash_buckets_.rehash(this.size() * std.base.Hash.RATIO); - // POST-PROCESS - this._Handle_insert(my_first, this.end()); + SetIterator.prototype.swap = function (obj) { + this.list_iterator_.swap(obj.list_iterator_); }; + return SetIterator; + }(std.Iterator)); + std.SetIterator = SetIterator; + /** + *

A reverse-iterator of Set.

+ * + *

+ *

+ * + * @param Type of the elements. + * + * @author Jeongho Nam + */ + var SetReverseIterator = (function (_super) { + __extends(SetReverseIterator, _super); /* --------------------------------------------------------- - POST-PROCESS + CONSTRUCTORS --------------------------------------------------------- */ /** - * @inheritdoc + * Construct from base iterator. + * + * @param base A reference of the base iterator, which iterates in the opposite direction. */ - HashMultiMap.prototype._Handle_insert = function (first, last) { - for (; !first.equal_to(last); first = first.next()) - this.hash_buckets_.insert(first); - }; + function SetReverseIterator(base) { + _super.call(this, base); + } /** - * @inheritdoc + * @hidden */ - HashMultiMap.prototype._Handle_erase = function (first, last) { - for (; !first.equal_to(last); first = first.next()) - this.hash_buckets_.erase(first); + SetReverseIterator.prototype.create_neighbor = function (base) { + return new SetReverseIterator(base); }; + return SetReverseIterator; + }(std.ReverseIterator)); + std.SetReverseIterator = SetReverseIterator; +})(std || (std = {})); +/// +/// +var std; +(function (std) { + var base; + (function (base) { /** - * @inheritdoc + *

An abstract set.

+ * + *

{@link SetContainer SetContainers} are containers that store elements allowing fast retrieval of + * individual elements based on their value.

+ * + *

In an {@link SetContainer}, the value of an element is at the same time its key, used to + * identify it. Keys are immutable, therefore, the elements in an {@link SetContainer} cannot be + * modified once in the container - they can be inserted and removed, though.

+ * + *

{@link SetContainer} stores elements, keeps sequence and enables indexing by inserting elements into a + * {@link List} and registering {@link ListIterator iterators} of the {@link data_ list container} to an index + * table like {@link RBTree tree} or {@link HashBuckets hash-table}.

+ * + *

+ *

+ * + *

Container properties

+ *
+ *
Associative
+ *
+ * Elements in associative containers are referenced by their key and not by their absolute + * position in the container. + *
+ * + *
Set
+ *
The value of an element is also the key used to identify it.
+ * + *
Multiple equivalent keys
+ *
Multiple elements in the container can have equivalent keys.
+ *
+ * + * @param Type of the elements. Each element in a {@link SetContainer} container is also identified + * by this value (each value is itself also the element's key). + * + * @author Jeongho Nam */ - HashMultiMap.prototype.swap = function (obj) { - if (obj instanceof HashMultiMap) { - this._Swap(obj); - _a = [obj.hash_buckets_, this.hash_buckets_], this.hash_buckets_ = _a[0], obj.hash_buckets_ = _a[1]; + var MultiSet = (function (_super) { + __extends(MultiSet, _super); + function MultiSet() { + _super.apply(this, arguments); } - else - _super.prototype.swap.call(this, obj); - var _a; - }; - return HashMultiMap; - }(std.base.MultiMap)); - std.HashMultiMap = HashMultiMap; + MultiSet.prototype.insert = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i - 0] = arguments[_i]; + } + return _super.prototype.insert.apply(this, args); + }; + return MultiSet; + }(base.SetContainer)); + base.MultiSet = MultiSet; + })(base = std.base || (std.base = {})); })(std || (std = {})); /// /// @@ -7670,6 +5869,109 @@ var std; }(std.base.MultiSet)); std.HashMultiSet = HashMultiSet; })(std || (std = {})); +/// +/// +var std; +(function (std) { + var base; + (function (base) { + /** + *

An abstract set.

+ * + *

{@link SetContainer SetContainers} are containers that store elements allowing fast retrieval of + * individual elements based on their value.

+ * + *

In an {@link SetContainer}, the value of an element is at the same time its key, used to uniquely + * identify it. Keys are immutable, therefore, the elements in an {@link SetContainer} cannot be modified + * once in the container - they can be inserted and removed, though.

+ * + *

{@link SetContainer} stores elements, keeps sequence and enables indexing by inserting elements into a + * {@link List} and registering {@link ListIterator iterators} of the {@link data_ list container} to an index + * table like {@link RBTree tree} or {@link HashBuckets hash-table}.

+ * + *

+ *

+ * + *

Container properties

+ *
+ *
Associative
+ *
+ * Elements in associative containers are referenced by their key and not by their absolute + * position in the container. + *
+ * + *
Set
+ *
The value of an element is also the key used to identify it.
+ * + *
Unique keys
+ *
No two elements in the container can have equivalent keys.
+ *
+ * + * @param Type of the elements. Each element in a {@link SetContainer} container is also identified + * by this value (each value is itself also the element's key). + * + * @author Jeongho Nam + */ + var UniqueSet = (function (_super) { + __extends(UniqueSet, _super); + function UniqueSet() { + _super.apply(this, arguments); + } + /* --------------------------------------------------------- + ACCESSOR + --------------------------------------------------------- */ + /** + * @inheritdoc + */ + UniqueSet.prototype.count = function (key) { + return this.find(key).equal_to(this.end()) ? 0 : 1; + }; + UniqueSet.prototype.extract = function (param) { + if (param instanceof std.SetIterator) + return this.extract_by_iterator(param); + else if (param instanceof std.SetReverseIterator) + return this.extract_by_reverse_iterator(param); + else + return this.extract_by_key(param); + }; + /** + * @hidden + */ + UniqueSet.prototype.extract_by_key = function (val) { + var it = this.find(val); + if (it.equal_to(this.end()) == true) + throw new std.OutOfRange("No such key exists."); + this.erase(val); + return val; + }; + /** + * @hidden + */ + UniqueSet.prototype.extract_by_iterator = function (it) { + if (it.equal_to(this.end()) == true || this.has(it.value) == false) + return this.end(); + this.erase(it); + return it; + }; + /** + * @hidden + */ + UniqueSet.prototype.extract_by_reverse_iterator = function (it) { + this.extract_by_iterator(it.base().next()); + return it; + }; + UniqueSet.prototype.insert = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i - 0] = arguments[_i]; + } + return _super.prototype.insert.apply(this, args); + }; + return UniqueSet; + }(base.SetContainer)); + base.UniqueSet = UniqueSet; + })(base = std.base || (std.base = {})); +})(std || (std = {})); /// /// var std; @@ -8587,870 +6889,1072 @@ var std; std.ListReverseIterator = ListReverseIterator; })(std || (std = {})); /// -/// -var std; -(function (std) { - /** - *

Vector, the dynamic array.

- * - *

{@link Vector}s are sequence containers representing arrays that can change in size.

- * - *

Just like arrays, {@link Vector}s use contiguous storage locations for their elements, which means that - * their elements can also be accessed using offsets on regular pointers to its elements, and just as efficiently - * as in arrays. But unlike arrays, their size can change dynamically, with their storage being handled - * automatically by the

+var std; +(function (std) { + /** + *

Priority queue.

* - *

Internally, {@link Vector}s use a dynamically allocated array to store their elements. This array may need - * to be reallocated in order to grow in size when new elements are inserted, which implies allocating a new - * array and moving all elements to it. This is a relatively expensive task in terms of processing time, and - * thus, {@link Vector}s do not reallocate each time an element is added to the

+ *

{@link PriorityQueue Priority queues} are a type of container adaptors, specifically designed such that its + * first element is always the greatest of the elements it contains, according to some strict weak ordering + * criterion.

* - *

Instead, {@link Vector} containers may allocate some extra storage to accommodate for possible growth, and - * thus the container may have an actual {@link capacity} greater than the storage strictly needed to contain its - * elements (i.e., its {@link size}). Libraries can implement different strategies for growth to balance between - * memory usage and reallocations, but in any case, reallocations should only happen at logarithmically growing - * intervals of {@link size} so that the insertion of individual elements at the end of the {@link Vector} can be - * provided with amortized constant time complexity (see {@link push_back push_back()}).

+ *

This context is similar to a heap, where elements can be inserted at any moment, and only the + * max heap element can be retrieved (the one at the top in the {@link PriorityQueue priority queue}).

* - *

Therefore, compared to arrays, {@link Vector}s consume more memory in exchange for the ability to manage - * storage and grow dynamically in an efficient way.

+ *

{@link PriorityQueue Priority queues} are implemented as container adaptors, which are classes that + * use an encapsulated object of a specific container class as its {@link container_ underlying container}, + * providing a specific set of member functions to access its elements. Elements are popped from the "back" + * of the specific container, which is known as the top of the {@link PriorityQueue Priority queue}.

* - *

Compared to the other dynamic sequence containers ({@link Deque}s, {@link List}s), {@link Vector Vectors} - * are very efficient accessing its elements (just like arrays) and relatively efficient adding or removing - * elements from its end. For operations that involve inserting or removing elements at positions other than the - * end, they perform worse than the others, and have less consistent iterators and references than {@link List}s. - *

+ *

The {@link container_ underlying container} may be any of the standard container class templates or some + * other specifically designed container class. The container shall be accessible through + * {@link IArrayIterator random access iterators} and support the following operations:

* - *

- * - *

+ *
    + *
  • empty()
  • + *
  • size()
  • + *
  • front()
  • + *
  • push_back()
  • + *
  • pop_back()
  • + *
* - *

Container properties

- *
- *
Sequence
- *
- * Elements in sequence containers are ordered in a strict linear sequence. Individual elements are - * accessed by their position in this sequence. - *
+ *

The standard container classes {@link Vector} and {@link Deque} fulfill these requirements. By default, if + * no container class is specified for a particular {@link PriorityQueue} class instantiation, the standard + * container {@link Vector} is used.

* - *
Dynamic array
- *
- * Allows direct access to any element in the sequence, even through pointer arithmetics, and provides - * relatively fast addition/removal of elements at the end of the sequence. - *
- *
+ *

Support of {@link IArrayIterator random access iterators} is required to keep a heap structure internally + * at all times. This is done automatically by the container adaptor by automatically calling the algorithm + * functions make_heap, push_heap and pop_heap when needed.

* * @param Type of the elements. * - * @reference http://www.cplusplus.com/reference/vector/vector - * @author Jeongho Nam + * @reference http://www.cplusplus.com/reference/queue/priority_queue/ + * @author Jeongho Nam */ - var Vector = (function (_super) { - __extends(Vector, _super); - function Vector() { + var PriorityQueue = (function () { + function PriorityQueue() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i - 0] = arguments[_i]; } - _super.call(this); - if (args.length == 0) { - } - else if (args.length == 1 && args[0] instanceof Array) { - // CONSTRUCT FROM AN ARRAY OF ITEMS - var array = args[0]; - _super.prototype.push.apply(this, array); + // INIT MEMBER + this.container_ = new std.TreeMultiSet(); + if (args.length >= 1 && args[0] instanceof std.base.Container) { + // COPY CONSTRUCTOR + var container = args[0]; // PARAMETER + if (args.length == 2) + this.container_["tree_"]["compare_"] = (args[1]); + this.container_.assign(container.begin(), container.end()); } - else if (args.length == 1 && typeof args[0] == "number") { - // CONSTRUCT FROM SIZE - var size = args[0]; - this.length = size; + else if (args.length >= 1 && args[0] instanceof Array) { + // INITIALIZER LIST CONSTRUCTOR + var items = args[0]; // PARAMETER + if (args.length == 2) + this.container_["tree_"]["compare_"] = (args[1]); + (_a = this.container_).push.apply(_a, items); } - else if (args.length == 2 && typeof args[0] == "number") { - // CONSTRUCT FROM SIZE AND REPEATING VALUE - var size = args[0]; - var val = args[1]; - this.assign(size, val); + else if (args.length >= 2 && args[0] instanceof std.Iterator && args[1] instanceof std.Iterator) { + // RANGE CONSTRUCTOR + var first = args[0]; // PARAMETER 1 + var last = args[1]; // PARAMETER 2 + if (args.length == 2) + this.container_["tree_"]["compare_"] = (args[2]); + this.container_.assign(first, last); } - else if (args.length == 2 && args[0] instanceof std.Iterator && args[1] instanceof std.Iterator) { - // CONSTRUCT FROM INPUT ITERATORS - var begin_5 = args[0]; - var end_4 = args[1]; - this.assign(begin_5, end_4); + else if (args.length == 1) { + // DEFAULT CONSTRUCTOR WITH SPECIFIED COMPARISON FUNCTION + this.container_["tree_"]["compare_"] = (args[0]); } + var _a; } - Vector.prototype.assign = function (first, second) { - this.clear(); - this.insert(this.end(), first, second); - }; - /** - * @inheritdoc - */ - Vector.prototype.reserve = function (size) { - // NOTHING TO DO ESPECIALLY - }; - /** - * @inheritdoc - */ - Vector.prototype.clear = function () { - this.erase(this.begin(), this.end()); - }; - /* ========================================================= + /* --------------------------------------------------------- ACCESSORS - ========================================================= */ - /** - * @inheritdoc - */ - Vector.prototype.begin = function () { - if (this.empty() == true) - return this.end(); - else - return new std.VectorIterator(this, 0); - }; - /** - * @inheritdoc - */ - Vector.prototype.end = function () { - return new std.VectorIterator(this, -1); - }; - /** - * @inheritdoc - */ - Vector.prototype.rbegin = function () { - return new std.VectorReverseIterator(this.end()); - }; - /** - * @inheritdoc - */ - Vector.prototype.rend = function () { - return new std.VectorReverseIterator(this.begin()); - }; - /** - * @inheritdoc - */ - Vector.prototype.size = function () { - return this.length; - }; + --------------------------------------------------------- */ /** - * @inheritdoc + *

Return size.

+ * + *

Returns the number of elements in the {@link PriorityQueue}.

+ * + *

This member function effectively calls member {@link IArray.size size} of the + * {@link container_ underlying container} object.

+ * + * @return The number of elements in the underlying */ - Vector.prototype.capacity = function () { - return this.length; + PriorityQueue.prototype.size = function () { + return this.container_.size(); }; /** - * @inheritdoc + *

Test whether container is empty.

+ * + *

Returns whether the {@link PriorityQueue} is empty: i.e. whether its {@link size} is zero.

+ * + *

This member function effectively calls member {@link IARray.empty empty} of the + * {@link container_ underlying container} object.

*/ - Vector.prototype.empty = function () { - return this.length == 0; + PriorityQueue.prototype.empty = function () { + return this.container_.empty(); }; + /* --------------------------------------------------------- + ELEMENTS I/O + --------------------------------------------------------- */ /** - * @inheritdoc + *

Access top element.

+ * + *

Returns a constant reference to the top element in the {@link PriorityQueue}.

+ * + *

The top element is the element that compares higher in the {@link PriorityQueue}, and the next that is + * removed from the container when {@link PriorityQueue.pop} is called.

+ * + *

This member function effectively calls member {@link IArray.front front} of the + * {@link container_ underlying container} object.

+ * + * @return A reference to the top element in the {@link PriorityQueue}. */ - Vector.prototype.at = function (index) { - if (index < this.size()) - return this[index]; - else - throw new std.OutOfRange("Target index is greater than Vector's size."); + PriorityQueue.prototype.top = function () { + return this.container_.begin().value; }; /** - * @inheritdoc + *

Insert element.

+ * + *

Inserts a new element in the {@link PriorityQueue}. The content of this new element is initialized to + * val. + * + *

This member function effectively calls the member function {@link IArray.push_back push_back} of the + * {@link container_ underlying container} object, and then reorders it to its location in the heap by calling + * the push_heap algorithm on the range that includes all the elements of the

+ * + * @param val Value to which the inserted element is initialized. */ - Vector.prototype.set = function (index, val) { - if (index > this.length) - throw new std.OutOfRange("Target index is greater than Vector's size."); - var prev = this[index]; - this[index] = val; - return prev; + PriorityQueue.prototype.push = function (val) { + this.container_.insert(val); }; /** - * @inheritdoc + *

Remove top element.

+ * + *

Removes the element on top of the {@link PriorityQueue}, effectively reducing its {@link size} by one. + * The element removed is the one with the highest (or lowest) value.

+ * + *

The value of this element can be retrieved before being popped by calling member + * {@link PriorityQueue.top}.

+ * + *

This member function effectively calls the pop_heap algorithm to keep the heap property of + * {@link PriorityQueue PriorityQueues} and then calls the member function {@link IArray.pop_back pop_back} of + * the {@link container_ underlying container} object to remove the element.

*/ - Vector.prototype.front = function () { - return this.at(0); + PriorityQueue.prototype.pop = function () { + this.container_.erase(this.container_.begin()); }; /** - * @inheritdoc + *

Swap contents.

+ * + *

Exchanges the contents of the container adaptor by those of obj, swapping both the + * {@link container_ underlying container} value and their comparison function using the corresponding + * {@link std.swap swap} non-member functions (unqualified).

+ * + *

This member function has a noexcept specifier that matches the combined noexcept of the + * {@link IArray.swap swap} operations on the {@link container_ underlying container} and the comparison + * functions.

+ * + * @param obj {@link PriorityQueue} container adaptor of the same type (i.e., instantiated with the same + * template parameters, T). Sizes may differ. */ - Vector.prototype.back = function () { - return this.at(this.length - 1); + PriorityQueue.prototype.swap = function (obj) { + this.container_.swap(obj.container_); }; - /* ========================================================= - ELEMENTS I/O - - INSERT - - ERASE - - SWAP - ============================================================ - INSERT + return PriorityQueue; + }()); + std.PriorityQueue = PriorityQueue; +})(std || (std = {})); +/// +var std; +(function (std) { + /** + *

FIFO queue.

+ * + *

{@link Queue}s are a type of container adaptor, specifically designed to operate in a FIFO context + * (first-in first-out), where elements are inserted into one end of the container and extracted from the other. + *

+ * + *

{@link Queue}s are implemented as containers adaptors, which are classes that use an encapsulated object of + * a specific container class as its underlying container, providing a specific set of member functions to access + * its elements. Elements are pushed into the {@link IDeque.back back()} of the specific container and popped from + * its {@link IDeque.front front()}.

+ * + *

{@link container_ The underlying container} may be one of the standard container class template or some + * other specifically designed container class. This underlying container shall support at least the following + * operations:

+ * + *
    + *
  • empty
  • + *
  • size
  • + *
  • front
  • + *
  • back
  • + *
  • push_back
  • + *
  • pop_front
  • + *
+ * + *

The standard container classes {@link Deque} and {@link List} fulfill these requirements. + * By default, if no container class is specified for a particular {@link Queue} class instantiation, the standard + * container {@link List} is used.

+ * + *

+ * + *

+ * + * @param Type of elements. + * + * @reference http://www.cplusplus.com/reference/queue/queue + * @author Jeongho Nam + */ + var Queue = (function () { + function Queue(queue) { + if (queue === void 0) { queue = null; } + this.container_ = new std.List(); + if (queue != null) + this.container_.assign(queue.container_.begin(), queue.container_.end()); + } + /* --------------------------------------------------------- + ACCESSORS --------------------------------------------------------- */ /** - * @inheritdoc + *

Return size.

+ *

Returns the number of elements in the {@link Queue}.

+ * + *

This member function effectively calls member {@link IDeque.size size()} of the + * {@link container_ underlying container} object.

+ * + * @return The number of elements in the {@link container_ underlying container}. */ - Vector.prototype.push_back = function (val) { - _super.prototype.push.call(this, val); - }; - Vector.prototype.insert = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i - 0] = arguments[_i]; - } - // REVERSE_ITERATOR TO ITERATOR - var ret; - var is_reverse_iterator = false; - if (args[0] instanceof std.VectorReverseIterator) { - is_reverse_iterator = true; - args[0] = args[0].base().prev(); - } - // BRANCHES - if (args.length == 2) - ret = this.insert_by_val(args[0], args[1]); - else if (args.length == 3 && typeof args[1] == "number") - ret = this._Insert_by_repeating_val(args[0], args[1], args[2]); - else - ret = this._Insert_by_range(args[0], args[1], args[2]); - // RETURNS - if (is_reverse_iterator == true) - return new std.VectorReverseIterator(ret.next()); - else - return ret; + Queue.prototype.size = function () { + return this.container_.size(); }; /** - * @hidden + *

Test whether container is empty.

+ *

returns whether the {@link Queue} is empty: i.e. whether its size is zero.

+ * + *

This member function efeectively calls member {@link IDeque.empty empty()} of the + * {@link container_ underlying container} object.

+ * + * @return true if the {@link container_ underlying container}'s size is 0, + * false otherwise.

*/ - Vector.prototype.insert_by_val = function (position, val) { - return this._Insert_by_repeating_val(position, 1, val); + Queue.prototype.empty = function () { + return this.container_.empty(); }; /** - * @hidden + *

Access next element.

+ *

Returns a value of the next element in the {@link Queue}.

+ * + *

The next element is the "oldest" element in the {@link Queue} and the same element that is popped out + * from the queue when {@link pop Queue.pop()} is called.

+ * + *

This member function effectively calls member {@link IDeque.front front()} of the + * {@link container_ underlying container} object.

+ * + * @return A value of the next element in the {@link Queue}. */ - Vector.prototype._Insert_by_repeating_val = function (position, n, val) { - if (position.index == -1) { - // WHEN INSERT TO THE LAST - for (var i = 0; i < n; i++) - _super.prototype.push.call(this, val); - return this.begin(); - } - else { - /////// - // INSERT TO THE MIDDLE POSITION - /////// - // CUT RIGHT SIDE - var spliced_array = _super.prototype.splice.call(this, position.index); - var insert_size = 0; - // INSERT ELEMENTS - for (var i = 0; i < n; i++) { - _super.prototype.push.call(this, val); - insert_size++; - } - _super.prototype.push.apply(this, spliced_array); // CONCAT THE SPLICEDS - return position; - } + Queue.prototype.front = function () { + return this.container_.front(); }; /** - * @hidden + *

Access last element.

+ * + *

Returns a vaue of the last element in the queue. This is the "newest" element in the queue (i.e. the + * last element pushed into the queue).

+ * + *

This member function effectively calls the member function {@link IDeque.back back()} of the + * {@link container_ underlying container} object.

+ * + * @return A value of the last element in the {@link Queue}. */ - Vector.prototype._Insert_by_range = function (position, first, last) { - if (position.index == -1) { - // WHEN INSERT TO THE LAST - for (; !first.equal_to(last); first = first.next()) - _super.prototype.push.call(this, first.value); - return this.begin(); - } - else { - /////// - // INSERT TO THE MIDDLE POSITION - /////// - // CUT RIGHT SIDE - var spliced_array = _super.prototype.splice.call(this, position.index); - var insert_size = 0; - // INSERT ELEMENTS - for (; !first.equal_to(last); first = first.next()) { - _super.prototype.push.call(this, first.value); - insert_size++; - } - _super.prototype.push.apply(this, spliced_array); // CONCAT THE SPLICEDS - return position; - } + Queue.prototype.back = function () { + return this.container_.back(); }; /* --------------------------------------------------------- - ERASE + ELEMENTS I/O --------------------------------------------------------- */ /** - * @inheritdoc + *

Insert element.

+ * + *

Inserts a new element at the end of the {@link Queue}, after its current last element. + * The content of this new element is initialized to val.

+ * + *

This member function effectively calls the member function {@link IDeque.push_back push_back()} of the + * {@link container_ underlying container} object.

+ * + * @param val Value to which the inserted element is initialized. */ - Vector.prototype.pop_back = function () { - this.erase(this.end().prev()); - }; - Vector.prototype.erase = function (first, last) { - if (last === void 0) { last = first.next(); } - var ret; - var is_reverse_iterator = false; - // REVERSE_ITERATOR TO ITERATOR - if (first instanceof std.VectorReverseIterator) { - is_reverse_iterator = true; - var first_it = last.base(); - var last_it = first.base(); - first = first_it; - last = last_it; - } - // ERASE ELEMENTS - ret = this._Erase_by_range(first, last); - // RETURN BRANCHES - if (is_reverse_iterator == true) - return new std.VectorReverseIterator(ret.next()); - else - return ret; + Queue.prototype.push = function (val) { + this.container_.push_back(val); }; /** - * @hidden + *

Remove next element.

+ * + *

Removes the next element in the {@link Queue}, effectively reducing its size by one.

+ * + *

The element removed is the "oldest" element in the {@link Queue} whose value can be retrieved by calling + * member {@link front Queue.front()}

. + * + *

This member function effectively calls the member function {@link IDeque.pop_front pop_front()} of the + * {@link container_ underlying container} object.

*/ - Vector.prototype._Erase_by_range = function (first, last) { - if (first.index == -1) - return first; - // ERASE ELEMENTS - if (last.index == -1) { - _super.prototype.splice.call(this, first.index); - return this.end(); - } - else - _super.prototype.splice.call(this, first.index, last.index - first.index); - return first; + Queue.prototype.pop = function () { + this.container_.pop_front(); }; - Vector.prototype.swap = function (obj) { - var supplement = new Vector(this.begin(), this.end()); - this.assign(obj.begin(), obj.end()); - obj.assign(supplement.begin(), supplement.end()); + /** + *

Swap contents.

+ * + *

Exchanges the contents of the container adaptor (this) by those of obj.

+ * + *

This member function calls the non-member function {@link IContainer.swap swap} (unqualified) to swap + * the {@link container_ underlying containers}.

+ * + * @param obj Another {@link Queue} container adaptor of the same type (i.e., instantiated with the same + * template parameter, T). Sizes may differ.

+ */ + Queue.prototype.swap = function (obj) { + this.container_.swap(obj.container_); }; - return Vector; - }(Array)); - std.Vector = Vector; + return Queue; + }()); + std.Queue = Queue; })(std || (std = {})); +/// var std; (function (std) { /** - *

An iterator of Vector.

+ *

LIFO stack.

* - *

- * + *

{@link Stack}s are a type of container adaptor, specifically designed to operate in a LIFO context + * (last-in first-out), where elements are inserted and extracted only from one end of the

+ * + *

{@link Stack}s are implemented as containers adaptors, which are classes that use an encapsulated object of + * a specific container class as its underlying container, providing a specific set of member functions to + * access its elements. Elements are pushed/popped from the {@link ILinearContainer.back back()} of the + * {@link ILinearContainer specific container}, which is known as the top of the {@link Stack}.

+ * + *

{@link container_ The underlying container} may be any of the standard container class templates or some + * other specifically designed container class. The container shall support the following operations:

+ * + *
    + *
  • empty
  • + *
  • size
  • + *
  • front
  • + *
  • back
  • + *
  • push_back
  • + *
  • pop_back
  • + *
+ * + *

The standard container classes {@link Vector}, {@link Deque} and {@link List} fulfill these requirements. + * By default, if no container class is specified for a particular {@link Stack} class instantiation, the standard + * container {@link List} is used.

+ * + *

+ * *

* - * @param Type of the elements. + * @param Type of elements. * + * @reference http://www.cplusplus.com/reference/stack/stack * @author Jeongho Nam */ - var VectorIterator = (function (_super) { - __extends(VectorIterator, _super); + var Stack = (function () { + function Stack(stack) { + if (stack === void 0) { stack = null; } + this.container_ = new std.List(); + if (stack != null) + this.container_.assign(stack.container_.begin(), stack.container_.end()); + } /* --------------------------------------------------------- - CONSTRUCTORS + ACCESSORS --------------------------------------------------------- */ /** - *

Construct from the source {@link Vector container}.

+ *

Return size.

* - *

Note

- *

Do not create the iterator directly, by yourself.

- *

Use {@link Vector.begin begin()}, {@link Vector.end end()} in {@link Vector container} instead.

+ *

Returns the number of elements in the {@link Stack}.

* - * @param source The source {@link Vector container} to reference. - * @param index Sequence number of the element in the source {@link Vector}. - */ - function VectorIterator(source, index) { - _super.call(this, source); - this.index_ = index; - } - Object.defineProperty(VectorIterator.prototype, "vector", { - /* --------------------------------------------------------- - ACCESSORS - --------------------------------------------------------- */ - /** - * @hidden - */ - get: function () { - return this.source_; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(VectorIterator.prototype, "value", { - /** - * @inheritdoc - */ - get: function () { - return this.vector.at(this.index_); - }, - /** - * Set value of the iterator is pointing to. - * - * @param val Value to set. - */ - set: function (val) { - this.vector.set(this.index_, val); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(VectorIterator.prototype, "index", { - /** - * Get index. - */ - get: function () { - return this.index_; - }, - enumerable: true, - configurable: true - }); - /* --------------------------------------------------------- - MOVERS - --------------------------------------------------------- */ - /** - * @inheritdoc + *

This member function effectively calls member {@link ILinearContainer.size size()} of the + * {@link container_ underlying container} object.

+ * + * @return The number of elements in the {@link container_ underlying container}. */ - VectorIterator.prototype.prev = function () { - if (this.index_ == -1) - return new VectorIterator(this.vector, this.vector.size() - 1); - else if (this.index_ - 1 < 0) - return this.vector.end(); - else - return new VectorIterator(this.vector, this.index_ - 1); + Stack.prototype.size = function () { + return this.container_.size(); }; /** - * @inheritdoc + *

Test whether container is empty.

+ * + *

returns whether the {@link Stack} is empty: i.e. whether its size is zero.

+ * + *

This member function effectively calls member {@link ILinearContainer.empty empty()} of the + * {@link container_ underlying container} object.

+ * + * @return true if the underlying container's size is 0, + * false otherwise.

*/ - VectorIterator.prototype.next = function () { - if (this.index_ >= this.source_.size() - 1) - return this.vector.end(); - else - return new VectorIterator(this.vector, this.index_ + 1); + Stack.prototype.empty = function () { + return this.container_.empty(); }; /** - * @inheritdoc + *

Access next element.

+ * + *

Returns a value of the top element in the {@link Stack}

. + * + *

Since {@link Stack}s are last-in first-out containers, the top element is the last element inserted into + * the {@link Stack}.

+ * + *

This member function effectively calls member {@link ILinearContainer.back back()} of the + * {@link container_ underlying container} object.

+ * + * @return A value of the top element in the {@link Stack}. */ - VectorIterator.prototype.advance = function (n) { - var new_index; - if (n < 0 && this.index_ == -1) - new_index = this.vector.size() + n; - else - new_index = this.index_ + n; - if (new_index < 0 || new_index >= this.vector.size()) - return this.vector.end(); - else - return new VectorIterator(this.vector, new_index); + Stack.prototype.top = function () { + return this.container_.back(); }; /* --------------------------------------------------------- - COMPARES + ELEMENTS I/O --------------------------------------------------------- */ /** - *

Whether an iterator is equal with the iterator.

+ *

Insert element.

* - *

Compare two iterators and returns whether they are equal or not.

+ *

Inserts a new element at the top of the {@link Stack}, above its current top element.

* - *

Note

- *

Iterator's equal_to() only compare souce container and index number.

+ *

This member function effectively calls the member function + * {@link ILinearContainer.push_back push_back()} of the {@link container_ underlying container} object.

* - *

Although elements in a pair, key and value are equal_to, if the source map or - * index number is different, then the {@link equal_to equal_to()} will return false. If you want to - * compare the elements of a pair, compare them directly by yourself.

+ * @param val Value to which the inserted element is initialized. + */ + Stack.prototype.push = function (val) { + this.container_.push_back(val); + }; + /** + *

Remove top element.

* - * @param obj An iterator to compare - * @return Indicates whether equal or not. + *

Removes the element on top of the {@link Stack}, effectively reducing its size by one.

+ * + *

The element removed is the latest element inserted into the {@link Stack}, whose value can be retrieved + * by calling member {@link top Stack.top()}

. + * + *

This member function effectively calls the member function {@link ILinearContainer.pop_back pop_back()} + * of the {@link container_ underlying container} object.

*/ - VectorIterator.prototype.equal_to = function (obj) { - return _super.prototype.equal_to.call(this, obj) && this.index_ == obj.index_; + Stack.prototype.pop = function () { + this.container_.pop_back(); }; /** - * @inheritdoc + *

Swap contents.

+ * + *

Exchanges the contents of the container adaptor (this) by those of obj.

+ * + *

This member function calls the non-member function {@link IContainer.swap swap} (unqualified) to swap + * the {@link container_ underlying containers}.

+ * + * @param obj Another {@link Stack} container adaptor of the same type (i.e., instantiated with the same + * template parameter, T). Sizes may differ.

*/ - VectorIterator.prototype.swap = function (obj) { - _a = [obj.value, this.value], this.value = _a[0], obj.value = _a[1]; - var _a; + Stack.prototype.swap = function (obj) { + this.container_.swap(obj.container_); }; - return VectorIterator; - }(std.Iterator)); - std.VectorIterator = VectorIterator; + return Stack; + }()); + std.Stack = Stack; })(std || (std = {})); +/// var std; (function (std) { - /** - *

A reverse-iterator of Vector.

- * - *

- * - *

- * - * @param Type of the elements. - * - * @author Jeongho Nam - */ - var VectorReverseIterator = (function (_super) { - __extends(VectorReverseIterator, _super); - /* --------------------------------------------------------- - CONSTRUCTORS - --------------------------------------------------------- */ + var base; + (function (base) { /** - * Construct from base iterator. + *

An abstract error instance.

+ * + *

{@link ErrorInstance} is an abstract class of {@link ErrorCode} and {@link ErrorCondition} + * holding an error instance's identifier {@link value}, associated with a {@link category}.

+ * + *

The operating system and other low-level applications and libraries generate numerical error codes to + * represent possible results. These numerical values may carry essential information for a specific platform, + * but be non-portable from one platform to another.

* - * @param base A reference of the base iterator, which iterates in the opposite direction. - */ - function VectorReverseIterator(base) { - _super.call(this, base); - } - /** - * @hidden + *

Objects of this class associate such numerical codes to {@link ErrorCategory error categories}, + * so that they can be interpreted when needed as more abstract (and portable) + * {@link ErrorCondition error conditions}.

+ * + *

+ *

+ * + * @author Jeongho Nam */ - VectorReverseIterator.prototype.create_neighbor = function (base) { - return new VectorReverseIterator(base); - }; - Object.defineProperty(VectorReverseIterator.prototype, "value", { + var ErrorInstance = (function () { + function ErrorInstance(val, category) { + if (val === void 0) { val = 0; } + if (category === void 0) { category = null; } + this.assign(val, category); + } + /** + *

Assign error instance.

+ * + *

Assigns the {@link ErrorCode} object a value of val associated with the {@link ErrorCategory}.

+ * + * @param val A numerical value identifying an error instance. + * @param category A reference to an {@link ErrorCategory} object. + */ + ErrorInstance.prototype.assign = function (val, category) { + this.category_ = category; + this.value_ = val; + }; + /** + *

Clear error instance.

+ * + *

Clears the value in the {@link ErrorCode} object so that it is set to a value of 0 of the + * {@link ErrorCategory.systemCategory ErrorCategory.systemCategory()} (indicating no error).

+ */ + ErrorInstance.prototype.clear = function () { + this.value_ = 0; + }; /* --------------------------------------------------------- ACCESSORS --------------------------------------------------------- */ /** - * @inheritdoc + *

Get category.

+ * + *

Returns a reference to the {@link ErrorCategory} associated with the {@link ErrorCode} object.

+ * + * @return A reference to a non-copyable object of a type derived from {@link ErrorCategory}. */ - get: function () { - return this.base_.value; - }, + ErrorInstance.prototype.category = function () { + return this.category_; + }; /** - * Set value of the iterator is pointing to. + *

Error value.

* - * @param val Value to set. + *

Returns the error value associated with the {@link ErrorCode} object.

+ * + * @return The error value. */ - set: function (val) { - this.base_.value = val; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(VectorReverseIterator.prototype, "index", { + ErrorInstance.prototype.value = function () { + return this.value_; + }; /** - * Get index. + *

Get message.

+ * + *

Returns the message associated with the error instance.

+ * + *

Error messages are defined by the {@link category} the error instance belongs to.

+ * + *

This function returns the same as if the following member was called:

+ * + *

category().message(value())

+ * + * @return A string object with the message associated with the {@link ErrorCode}. */ - get: function () { - return this.base_.index; - }, - enumerable: true, - configurable: true - }); - return VectorReverseIterator; - }(std.ReverseIterator)); - std.VectorReverseIterator = VectorReverseIterator; + ErrorInstance.prototype.message = function () { + if (this.category_ == null || this.value_ == 0) + return ""; + else + return this.category_.message(this.value_); + }; + /** + *

Default error condition.

+ * + *

Returns the default {@link ErrorCondition}object associated with the {@link ErrorCode} object.

+ * + *

This function returns the same as if the following member was called:

+ * + *

category().default_error_condition(value())

+ * + *

{@link ErrorCategory.default_error_condition ErrorCategory.default_error_condition()} + * is a virtual member function, that can operate differently for each category.

+ * + * @return An {@link ErrorCondition}object that corresponds to the {@link ErrorCode} object. + */ + ErrorInstance.prototype.default_error_condition = function () { + if (this.category_ == null || this.value_ == 0) + return null; + else + return this.category_.default_error_condition(this.value_); + }; + /* --------------------------------------------------------- + OPERATORS + --------------------------------------------------------- */ + /** + *

Convert to bool.

+ * + *

Returns whether the error instance has a numerical {@link value} other than 0.

+ * + *

If it is zero (which is generally used to represent no error), the function returns false, otherwise it returns true.

+ * + * @return true if the error's numerical value is not zero. + * false otherwise. + */ + ErrorInstance.prototype.to_bool = function () { + return this.value_ != 0; + }; + return ErrorInstance; + }()); + base.ErrorInstance = ErrorInstance; + })(base = std.base || (std.base = {})); })(std || (std = {})); /// +/// +/// var std; (function (std) { /** - *

FIFO queue.

- * - *

{@link Queue}s are a type of container adaptor, specifically designed to operate in a FIFO context - * (first-in first-out), where elements are inserted into one end of the container and extracted from the other. - *

- * - *

{@link Queue}s are implemented as containers adaptors, which are classes that use an encapsulated object of - * a specific container class as its underlying container, providing a specific set of member functions to access - * its elements. Elements are pushed into the {@link IDeque.back back()} of the specific container and popped from - * its {@link IDeque.front front()}.

- * - *

{@link container_ The underlying container} may be one of the standard container class template or some - * other specifically designed container class. This underlying container shall support at least the following - * operations:

- * - *
    - *
  • empty
  • - *
  • size
  • - *
  • front
  • - *
  • back
  • - *
  • push_back
  • - *
  • pop_front
  • - *
+ *

System error exception.

* - *

The standard container classes {@link Deque} and {@link List} fulfill these requirements. - * By default, if no container class is specified for a particular {@link Queue} class instantiation, the standard - * container {@link List} is used.

+ *

This class defines the type of objects thrown as exceptions to report conditions originating during + * runtime from the operating system or other low-level application program interfaces which have an + * associated {@link ErrorCode}.

* - *

- * - *

+ *

The class inherits from {@link RuntimeError}, to which it adds an {@link ErrorCode} as + * member code (and defines a specialized what member).

* - * @param Type of elements. + *

+ *

* - * @reference http://www.cplusplus.com/reference/queue/queue + * @reference http://www.cplusplus.com/reference/system_error/system_error * @author Jeongho Nam */ - var Queue = (function () { - function Queue(queue) { - if (queue === void 0) { queue = null; } - this.container_ = new std.List(); - if (queue != null) - this.container_.assign(queue.container_.begin(), queue.container_.end()); + var SystemError = (function (_super) { + __extends(SystemError, _super); + function SystemError() { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i - 0] = arguments[_i]; + } + _super.call(this, ""); } /* --------------------------------------------------------- ACCESSORS --------------------------------------------------------- */ /** - *

Return size.

- *

Returns the number of elements in the {@link Queue}.

- * - *

This member function effectively calls member {@link IDeque.size size()} of the - * {@link container_ underlying container} object.

- * - * @return The number of elements in the {@link container_ underlying container}. - */ - Queue.prototype.size = function () { - return this.container_.size(); - }; - /** - *

Test whether container is empty.

- *

returns whether the {@link Queue} is empty: i.e. whether its size is zero.

- * - *

This member function efeectively calls member {@link IDeque.empty empty()} of the - * {@link container_ underlying container} object.

- * - * @return true if the {@link container_ underlying container}'s size is 0, - * false otherwise.

- */ - Queue.prototype.empty = function () { - return this.container_.empty(); - }; - /** - *

Access next element.

- *

Returns a value of the next element in the {@link Queue}.

+ *

Get error code.

* - *

The next element is the "oldest" element in the {@link Queue} and the same element that is popped out - * from the queue when {@link pop Queue.pop()} is called.

+ *

Returns the {@link ErrorCode} object associated with the exception.

* - *

This member function effectively calls member {@link IDeque.front front()} of the - * {@link container_ underlying container} object.

+ *

This value is either the {@link ErrorCode} passed to the construction or its equivalent + * (if constructed with a value and a {@link category}.

* - * @return A value of the next element in the {@link Queue}. + * @return The {@link ErrorCode} associated with the object. */ - Queue.prototype.front = function () { - return this.container_.front(); + SystemError.prototype.code = function () { + return this.code_; }; + return SystemError; + }(std.RuntimeError)); + std.SystemError = SystemError; +})(std || (std = {})); +var std; +(function (std) { + /** + *

Error category.

+ * + *

This type serves as a base class for specific category types.

+ * + *

Category types are used to identify the source of an error. They also define the relation between + * {@link ErrorCode} and {@link ErrorCondition}objects of its category, as well as the message set for {@link ErrorCode} + * objects. + * + *

Objects of these types have no distinct values and are not-copyable and not-assignable, and thus can only be + * passed by reference. As such, only one object of each of these types shall exist, each uniquely identifying its own + * category: all error codes and conditions of a same category shall return a reference to same object.

+ * + *

+ *

+ * + * @reference http://www.cplusplus.com/reference/system_error/error_category + * @author Jeongho Nam + */ + var ErrorCategory = (function () { + /* --------------------------------------------------------- + CONSTRUCTORS + --------------------------------------------------------- */ /** - *

Access last element.

- * - *

Returns a vaue of the last element in the queue. This is the "newest" element in the queue (i.e. the - * last element pushed into the queue).

- * - *

This member function effectively calls the member function {@link IDeque.back back()} of the - * {@link container_ underlying container} object.

- * - * @return A value of the last element in the {@link Queue}. + * Default Constructor. */ - Queue.prototype.back = function () { - return this.container_.back(); - }; + function ErrorCategory() { + } /* --------------------------------------------------------- - ELEMENTS I/O + OPERATORS --------------------------------------------------------- */ /** - *

Insert element.

- * - *

Inserts a new element at the end of the {@link Queue}, after its current last element. - * The content of this new element is initialized to val.

- * - *

This member function effectively calls the member function {@link IDeque.push_back push_back()} of the - * {@link container_ underlying container} object.

+ *

Default error condition.

* - * @param val Value to which the inserted element is initialized. - */ - Queue.prototype.push = function (val) { - this.container_.push_back(val); - }; - /** - *

Remove next element.

+ *

Returns the default {@link ErrorCondition}object of this category that is associated with the + * {@link ErrorCode} identified by a value of val.

* - *

Removes the next element in the {@link Queue}, effectively reducing its size by one.

+ *

Its definition in the base class {@link ErrorCategory} returns the same as constructing an + * {@link ErrorCondition} object with: * - *

The element removed is the "oldest" element in the {@link Queue} whose value can be retrieved by calling - * member {@link front Queue.front()}

. + *

new ErrorCondition(val, *this);

* - *

This member function effectively calls the member function {@link IDeque.pop_front pop_front()} of the - * {@link container_ underlying container} object.

- */ - Queue.prototype.pop = function () { - this.container_.pop_front(); - }; - /** - *

Swap contents.

+ *

As a virtual member function, this behavior can be overriden in derived classes.

* - *

Exchanges the contents of the container adaptor (this) by those of obj.

+ *

This function is called by the default definition of member {@link equivalent equivalent()}, which is used to + * compare {@link ErrorCondition error conditions} with error codes.

* - *

This member function calls the non-member function {@link IContainer.swap swap} (unqualified) to swap - * the {@link container_ underlying containers}.

+ * @param val A numerical value identifying an error condition. * - * @param obj Another {@link Queue} container adaptor of the same type (i.e., instantiated with the same - * template parameter, T). Sizes may differ.

+ * @return The default {@link ErrorCondition}object associated with condition value val for this category. */ - Queue.prototype.swap = function (obj) { - this.container_.swap(obj.container_); + ErrorCategory.prototype.default_error_condition = function (val) { + return new std.ErrorCondition(val, this); }; - return Queue; + ErrorCategory.prototype.equivalent = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i - 0] = arguments[_i]; + } + if (args[1] instanceof std.ErrorCondition) { + var val_code = args[0]; + var cond = args[1]; + return std.equal_to(this.default_error_condition(val_code), cond); + } + else { + var code = args[0]; + var valcond = args[1]; + return std.equal_to(this, code.category()) && code.value() == valcond; + } + }; + return ErrorCategory; }()); - std.Queue = Queue; + std.ErrorCategory = ErrorCategory; +})(std || (std = {})); +var std; +(function (std) { + /** + *

Error condition.

+ * + *

Objects of this type hold a condition {@link value} associated with a {@link category}.

+ * + *

Objects of this type describe errors in a generic way so that they may be portable across different + * systems. This is in contrast with {@link ErrorCode} objects, that may contain system-specific + * information.

+ * + *

Because {@link ErrorCondition}objects can be compared with error_code objects directly by using + * relational operators, {@link ErrorCondition}objects are generally used to check whether + * a particular {@link ErrorCode} obtained from the system matches a specific error condition no matter + * the system.

+ * + *

The {@link ErrorCategory categories} associated with the {@link ErrorCondition} and the + * {@link ErrorCode} define the equivalences between them.

+ * + *

+ *

+ * + * @reference http://www.cplusplus.com/reference/system_error/error_condition + * @author Jeongho Nam + */ + var ErrorCondition = (function (_super) { + __extends(ErrorCondition, _super); + function ErrorCondition(val, category) { + if (val === void 0) { val = 0; } + if (category === void 0) { category = null; } + _super.call(this, val, category); + } + return ErrorCondition; + }(std.base.ErrorInstance)); + std.ErrorCondition = ErrorCondition; +})(std || (std = {})); +var std; +(function (std) { + /** + *

Error code.

+ * + *

Objects of this type hold an error code {@link value} associated with a {@link category}.

+ * + *

The operating system and other low-level applications and libraries generate numerical error codes to + * represent possible results. These numerical values may carry essential information for a specific platform, + * but be non-portable from one platform to another.

+ * + *

Objects of this class associate such numerical codes to {@link ErrorCategory error categories}, so that they + * can be interpreted when needed as more abstract (and portable) {@link ErrorCondition error conditions}.

+ * + *

+ *

+ * + * @reference http://www.cplusplus.com/reference/system_error/error_code + * @author Jeongho Nam + */ + var ErrorCode = (function (_super) { + __extends(ErrorCode, _super); + function ErrorCode(val, category) { + if (val === void 0) { val = 0; } + if (category === void 0) { category = null; } + _super.call(this, val, category); + } + return ErrorCode; + }(std.base.ErrorInstance)); + std.ErrorCode = ErrorCode; })(std || (std = {})); /// +/// var std; (function (std) { /** - *

LIFO stack.

+ *

Tree-structured map, std::map of STL.

* - *

{@link Stack}s are a type of container adaptor, specifically designed to operate in a LIFO context - * (last-in first-out), where elements are inserted and extracted only from one end of the

+ *

{@link TreeMap TreeMaps} are associative containers that store elements formed by a combination of a + * key value (Key) and a mapped value (T), following order.

* - *

{@link Stack}s are implemented as containers adaptors, which are classes that use an encapsulated object of - * a specific container class as its underlying container, providing a specific set of member functions to - * access its elements. Elements are pushed/popped from the {@link ILinearContainer.back back()} of the - * {@link ILinearContainer specific container}, which is known as the top of the {@link Stack}.

+ *

In a {@link TreeMap}, the key values are generally used to sort and uniquely identify the elements, + * while the mapped values store the content associated to this key. The types of key and + * mapped value may differ, and are grouped together in member type value_type, which is a {@link Pair} + * type combining both:

* - *

{@link container_ The underlying container} may be any of the standard container class templates or some - * other specifically designed container class. The container shall support the following operations:

+ *

typedef Pair value_type;

* - *
    - *
  • empty
  • - *
  • size
  • - *
  • front
  • - *
  • back
  • - *
  • push_back
  • - *
  • pop_back
  • - *
+ *

Internally, the elements in a {@link TreeMap} are always sorted by its key following a + * strict weak ordering criterion indicated by its internal comparison method {@link less}. * - *

The standard container classes {@link Vector}, {@link Deque} and {@link List} fulfill these requirements. - * By default, if no container class is specified for a particular {@link Stack} class instantiation, the standard - * container {@link List} is used.

+ *

{@link TreeMap} containers are generally slower than {@link HashMap HashMap} containers to access individual + * elements by their key, but they allow the direct iteration on subsets based on their order.

* - *

- * - *

+ *

{@link TreeMap}s are typically implemented as binary search trees.

* - * @param Type of elements. + *

+ *

* - * @reference http://www.cplusplus.com/reference/stack/stack + *

Container properties

+ *
+ *
Associative
+ *
Elements in associative containers are referenced by their key and not by their absolute + * position in the container.
+ * + *
Ordered
+ *
The elements in the container follow a strict order at all times. All inserted elements are + * given a position in this order.
+ * + *
Map
+ *
Each element associates a key to a mapped value: + * Keys are meant to identify the elements whose main content is the mapped value.
+ * + *
Unique keys
+ *
No two elements in the container can have equivalent keys.
+ *
+ * + * @param Type of the keys. Each element in a map is uniquely identified by its key value. + * @param Type of the mapped value. Each element in a map stores some data as its mapped value. + * + * @reference http://www.cplusplus.com/reference/map/map * @author Jeongho Nam */ - var Stack = (function () { - function Stack(stack) { - if (stack === void 0) { stack = null; } - this.container_ = new std.List(); - if (stack != null) - this.container_.assign(stack.container_.begin(), stack.container_.end()); + var TreeMap = (function (_super) { + __extends(TreeMap, _super); + function TreeMap() { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i - 0] = arguments[_i]; + } + // INIT MEMBERS + _super.call(this); + this.tree_ = new std.base.PairTree(this); + if (args.length >= 1 && args[0] instanceof TreeMap) { + // COPY CONSTRUCTOR + var container = args[0]; // PARAMETER + if (args.length == 2) + this.tree_["compare_"] = (args[1]); + this.assign(container.begin(), container.end()); + } + else if (args.length >= 1 && args[0] instanceof Array) { + // INITIALIZER LIST CONSTRUCTOR + var items = args[0]; // PARAMETER + if (args.length == 2) + this.tree_["compare_"] = (args[1]); + this.push.apply(this, items); + } + else if (args.length >= 2 && args[0] instanceof std.Iterator && args[1] instanceof std.Iterator) { + // RANGE CONSTRUCTOR + var first = args[0]; // PARAMETER 1 + var last = args[1]; // PARAMETER 2 + if (args.length == 2) + this.tree_["compare_"] = (args[2]); + this.assign(first, last); + } + else if (args.length == 1) { + // DEFAULT CONSTRUCTOR WITH SPECIFIED COMPARISON FUNCTION + this.tree_["compare_"] = (args[0]); + } } /* --------------------------------------------------------- + ASSIGN & CLEAR + --------------------------------------------------------- */ + /** + * @inheritdoc + */ + TreeMap.prototype.clear = function () { + _super.prototype.clear.call(this); + this.tree_.clear(); + }; + /* ========================================================= ACCESSORS + ========================================================= */ + /** + * @inheritdoc + */ + TreeMap.prototype.find = function (key) { + var node = this.tree_.find(key); + if (node == null || std.equal_to(node.value.first, key) == false) + return this.end(); + else + return node.value; + }; + /** + * @inheritdoc + */ + TreeMap.prototype.key_comp = function () { + return this.tree_.key_comp(); + }; + /** + * @inheritdoc + */ + TreeMap.prototype.value_comp = function () { + return this.tree_.value_comp(); + }; + /** + * @inheritdoc + */ + TreeMap.prototype.lower_bound = function (key) { + return this.tree_.lower_bound(key); + }; + /** + * @inheritdoc + */ + TreeMap.prototype.upper_bound = function (key) { + return this.tree_.upper_bound(key); + }; + /** + * @inheritdoc + */ + TreeMap.prototype.equal_range = function (key) { + return this.tree_.equal_range(key); + }; + /* ========================================================= + ELEMENTS I/O + - INSERT + - POST-PROCESS + - SWAP + ============================================================ + INSERT --------------------------------------------------------- */ /** - *

Return size.

- * - *

Returns the number of elements in the {@link Stack}.

- * - *

This member function effectively calls member {@link ILinearContainer.size size()} of the - * {@link container_ underlying container} object.

- * - * @return The number of elements in the {@link container_ underlying container}. + * @hidden */ - Stack.prototype.size = function () { - return this.container_.size(); + TreeMap.prototype._Insert_by_pair = function (pair) { + var node = this.tree_.find(pair.first); + // IF EQUALS, THEN RETURN FALSE + if (node != null && std.equal_to(node.value.first, pair.first) == true) + return std.make_pair(node.value, false); + // INSERTS + var it; + if (node == null) + it = this.end(); + else if (this.key_comp()(node.value.first, pair.first) == true) + it = node.value.next(); + else + it = node.value; + // ITERATOR TO RETURN + it = new std.MapIterator(this, this["data_"].insert(it.get_list_iterator(), pair)); + this._Handle_insert(it, it.next()); // POST-PROCESS + return std.make_pair(it, true); }; /** - *

Test whether container is empty.

- * - *

returns whether the {@link Stack} is empty: i.e. whether its size is zero.

- * - *

This member function effectively calls member {@link ILinearContainer.empty empty()} of the - * {@link container_ underlying container} object.

- * - * @return true if the underlying container's size is 0, - * false otherwise.

+ * @hidden */ - Stack.prototype.empty = function () { - return this.container_.empty(); + TreeMap.prototype._Insert_by_hint = function (hint, pair) { + // FIND KEY + if (this.has(pair.first) == true) + return this.end(); + // VALIDATE HINT + var ret; + var compare = this.key_comp(); + // hint < current && current < next + if (compare(hint.first, pair.first) == true + && (hint.next().equal_to(this.end()) || compare(pair.first, hint.next().first) == true)) { + /////// + // RIGHT HINT + /////// + // INSERT + ret = new std.MapIterator(this, this["data_"].insert(hint.get_list_iterator(), pair)); + // POST-PROCESS + this._Handle_insert(ret, ret.next()); + } + else { + /////// + // WRONG HINT + /////// + // INSERT BY AUTOMATIC NODE FINDING + ret = this._Insert_by_pair(pair).first; + } + return ret; }; /** - *

Access next element.

- * - *

Returns a value of the top element in the {@link Stack}

. - * - *

Since {@link Stack}s are last-in first-out containers, the top element is the last element inserted into - * the {@link Stack}.

- * - *

This member function effectively calls member {@link ILinearContainer.back back()} of the - * {@link container_ underlying container} object.

- * - * @return A value of the top element in the {@link Stack}. + * @hidden */ - Stack.prototype.top = function () { - return this.container_.back(); + TreeMap.prototype._Insert_by_range = function (first, last) { + for (; !first.equal_to(last); first = first.next()) + this._Insert_by_pair(std.make_pair(first.value.first, first.value.second)); }; /* --------------------------------------------------------- - ELEMENTS I/O + POST-PROCESS --------------------------------------------------------- */ /** - *

Insert element.

- * - *

Inserts a new element at the top of the {@link Stack}, above its current top element.

- * - *

This member function effectively calls the member function - * {@link ILinearContainer.push_back push_back()} of the {@link container_ underlying container} object.

- * - * @param val Value to which the inserted element is initialized. + * @inheritdoc */ - Stack.prototype.push = function (val) { - this.container_.push_back(val); + TreeMap.prototype._Handle_insert = function (first, last) { + this.tree_.insert(first); }; /** - *

Remove top element.

- * - *

Removes the element on top of the {@link Stack}, effectively reducing its size by one.

- * - *

The element removed is the latest element inserted into the {@link Stack}, whose value can be retrieved - * by calling member {@link top Stack.top()}

. - * - *

This member function effectively calls the member function {@link ILinearContainer.pop_back pop_back()} - * of the {@link container_ underlying container} object.

+ * @inheritdoc */ - Stack.prototype.pop = function () { - this.container_.pop_back(); + TreeMap.prototype._Handle_erase = function (first, last) { + for (; !first.equal_to(last); first = first.next()) + this.tree_.erase(last); }; /** - *

Swap contents.

- * - *

Exchanges the contents of the container adaptor (this) by those of obj.

- * - *

This member function calls the non-member function {@link IContainer.swap swap} (unqualified) to swap - * the {@link container_ underlying containers}.

- * - * @param obj Another {@link Stack} container adaptor of the same type (i.e., instantiated with the same - * template parameter, T). Sizes may differ.

+ * @inheritdoc */ - Stack.prototype.swap = function (obj) { - this.container_.swap(obj.container_); + TreeMap.prototype.swap = function (obj) { + if (obj instanceof TreeMap && this.key_comp() == obj.key_comp()) { + this._Swap(obj); + _a = [obj.tree_, this.tree_], this.tree_ = _a[0], obj.tree_ = _a[1]; + } + else + _super.prototype.swap.call(this, obj); + var _a; }; - return Stack; - }()); - std.Stack = Stack; + return TreeMap; + }(std.base.UniqueMap)); + std.TreeMap = TreeMap; })(std || (std = {})); /// -/// +/// var std; (function (std) { /** - *

Tree-structured set, std::set of STL.

+ *

Tree-structured multiple-key map.

* - *

{@link TreeSet}s are containers that store unique elements following a specific order.

+ *

{@link TreeMultiMap TreeMultiMaps} are associative containers that store elements formed by a combination of + * a key value and a mapped value, following a specific order, and where multiple elements can + * have equivalent keys.

* - *

In a {@link TreeSet}, the value of an element also identifies it (the value is itself the - * key, of type T), and each value must be unique. The value of the elements in a - * {@link TreeSet} cannot be modified once in the container (the elements are always const), but they - * can be inserted or removed from the

+ *

In a {@link TreeMultiMap}, the key values are generally used to sort and uniquely identify + * the elements, while the mapped values store the content associated to this key. The types of + * key and mapped value may differ, and are grouped together in member type + * value_type, which is a {@link Pair} type combining both:

* - *

Internally, the elements in a {@link TreeSet} are always sorted following a specific strict weak - * ordering criterion indicated by its internal comparison method (of {@link less}).

+ *

typedef Pair value_type;

* - *

{@link TreeSet} containers are generally slower than {@link HashSet} containers to access - * individual elements by their key, but they allow the direct iteration on subsets based on their - * order.

+ *

Internally, the elements in a {@link TreeMultiMap}are always sorted by its key following a + * strict weak ordering criterion indicated by its internal comparison method (of {@link less}).

* - *

{@link TreeSet}s are typically implemented as binary search trees.

+ *

{@link TreeMultiMap}containers are generally slower than {@link HashMap} containers + * to access individual elements by their key, but they allow the direct iteration on subsets based + * on their order.

* - *

- *

+ *

{@link TreeMultiMap TreeMultiMaps} are typically implemented as binary search trees.

+ * + *

< + * img src="http://samchon.github.io/typescript-stl/images/design/class_diagram/map_containers.png" style="max-width: 100%" />

* *

Container properties

*
@@ -9466,30 +7970,33 @@ var std; * given a position in this order. * * - *
Set
- *
The value of an element is also the key used to identify it.
+ *
Map
+ *
+ * Each element associates a key to a mapped value: + * Keys are meant to identify the elements whose main content is the mapped value. + *
* - *
Unique keys
- *
No two elements in the container can have equivalent keys.
+ *
Multiple equivalent keys
+ *
Multiple elements in the container can have equivalent keys.
*
* - * @param Type of the elements. - * Each element in an {@link TreeSet} is also uniquely identified by this value. + * @param Type of the keys. Each element in a map is uniquely identified by its key value. + * @param Type of the mapped value. Each element in a map stores some data as its mapped value. * - * @reference http://www.cplusplus.com/reference/set/set + * @reference http://www.cplusplus.com/reference/map/multimap * @author Jeongho Nam */ - var TreeSet = (function (_super) { - __extends(TreeSet, _super); - function TreeSet() { + var TreeMultiMap = (function (_super) { + __extends(TreeMultiMap, _super); + function TreeMultiMap() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i - 0] = arguments[_i]; } // INIT MEMBERS _super.call(this); - this.tree_ = new std.base.AtomicTree(this); - if (args.length >= 1 && args[0] instanceof TreeSet) { + this.tree_ = new std.base.PairTree(this); + if (args.length >= 1 && args[0] instanceof TreeMultiMap) { // COPY CONSTRUCTOR var container = args[0]; // PARAMETER if (args.length == 2) @@ -9522,7 +8029,7 @@ var std; /** * @inheritdoc */ - TreeSet.prototype.clear = function () { + TreeMultiMap.prototype.clear = function () { _super.prototype.clear.call(this); this.tree_.clear(); }; @@ -9532,9 +8039,9 @@ var std; /** * @inheritdoc */ - TreeSet.prototype.find = function (val) { - var node = this.tree_.find(val); - if (node == null || std.equal_to(node.value.value, val) == false) + TreeMultiMap.prototype.find = function (key) { + var node = this.tree_.find(key); + if (node == null || std.equal_to(node.value.first, key) == false) return this.end(); else return node.value; @@ -9542,32 +8049,42 @@ var std; /** * @inheritdoc */ - TreeSet.prototype.key_comp = function () { - return this.tree_.key_comp(); + TreeMultiMap.prototype.count = function (key) { + var it = this.find(key); + var cnt = 0; + for (; !it.equal_to(this.end()) && std.equal_to(it.first, key); it = it.next()) + cnt++; + return cnt; }; /** * @inheritdoc */ - TreeSet.prototype.value_comp = function () { + TreeMultiMap.prototype.key_comp = function () { return this.tree_.key_comp(); }; /** * @inheritdoc */ - TreeSet.prototype.lower_bound = function (val) { - return this.tree_.lower_bound(val); + TreeMultiMap.prototype.value_comp = function () { + return this.tree_.value_comp(); }; /** * @inheritdoc */ - TreeSet.prototype.upper_bound = function (val) { - return this.tree_.upper_bound(val); + TreeMultiMap.prototype.lower_bound = function (key) { + return this.tree_.lower_bound(key); }; /** * @inheritdoc */ - TreeSet.prototype.equal_range = function (val) { - return this.tree_.equal_range(val); + TreeMultiMap.prototype.upper_bound = function (key) { + return this.tree_.upper_bound(key); + }; + /** + * @inheritdoc + */ + TreeMultiMap.prototype.equal_range = function (key) { + return this.tree_.equal_range(key); }; /* ========================================================= ELEMENTS I/O @@ -9580,41 +8097,45 @@ var std; /** * @hidden */ - TreeSet.prototype._Insert_by_val = function (val) { - var node = this.tree_.find(val); - // IF EQUALS, THEN RETURN FALSE - if (node != null && std.equal_to(node.value.value, val) == true) - return std.make_pair(node.value, false); - // FIND NODE + TreeMultiMap.prototype._Insert_by_pair = function (pair) { + var node = this.tree_.find(pair.first); var it; - if (node == null) + if (node == null) { it = this.end(); - else if (this.key_comp()(node.value.value, val) == true) + } + else if (std.equal_to(node.value.first, pair.first) == true) { + it = node.value.next(); + } + else if (this.key_comp()(node.value.first, pair.first) == true) { it = node.value.next(); + while (it.equal_to(this.end()) == false && this.key_comp()(it.first, pair.first)) + it = it.next(); + } else it = node.value; - ///// - // INSERTS - ///// - it = new std.SetIterator(this, this["data_"].insert(it.get_list_iterator(), val)); + // ITERATOR TO RETURN + it = new std.MapIterator(this, this["data_"].insert(it.get_list_iterator(), pair)); this._Handle_insert(it, it.next()); // POST-PROCESS - return std.make_pair(it, true); + return it; }; - TreeSet.prototype._Insert_by_hint = function (hint, val) { + /** + * @hidden + */ + TreeMultiMap.prototype._Insert_by_hint = function (hint, pair) { // FIND KEY - if (this.has(val) == true) + if (this.has(pair.first) == true) return this.end(); // VALIDATE HINT var ret; - var compare = this.tree_.key_comp(); - // hint < current && current < next - if (compare(hint.value, val) == true - && (hint.next().equal_to(this.end()) || compare(val, hint.next().value) == true)) { + var compare = this.key_comp(); + // hint <= current && current <= next + if ((compare(hint.first, pair.first) || std.equal_to(hint.first, pair.first)) + && (hint.next().equal_to(this.end()) || (compare(pair.first, hint.next().first) || std.equal_to(pair.first, hint.next().first)))) { /////// // RIGHT HINT /////// // INSERT - ret = new std.SetIterator(this, this["data_"].insert(hint.get_list_iterator(), val)); + ret = new std.MapIterator(this, this["data_"].insert(hint.get_list_iterator(), pair)); // POST-PROCESS this._Handle_insert(ret, ret.next()); } @@ -9623,16 +8144,16 @@ var std; // WRONG HINT /////// // INSERT BY AUTOMATIC NODE FINDING - ret = this._Insert_by_val(val).first; + ret = this._Insert_by_pair(pair); } return ret; }; /** * @hidden */ - TreeSet.prototype._Insert_by_range = function (first, last) { + TreeMultiMap.prototype._Insert_by_range = function (first, last) { for (; !first.equal_to(last); first = first.next()) - this._Insert_by_val(first.value); + this._Insert_by_pair(std.make_pair(first.value.first, first.value.second)); }; /* --------------------------------------------------------- POST-PROCESS @@ -9640,18 +8161,21 @@ var std; /** * @inheritdoc */ - TreeSet.prototype._Handle_insert = function (first, last) { + TreeMultiMap.prototype._Handle_insert = function (first, last) { this.tree_.insert(first); }; /** * @inheritdoc */ - TreeSet.prototype._Handle_erase = function (first, last) { + TreeMultiMap.prototype._Handle_erase = function (first, last) { for (; !first.equal_to(last); first = first.next()) this.tree_.erase(last); }; - TreeSet.prototype.swap = function (obj) { - if (obj instanceof TreeSet && this.key_comp() == obj.key_comp()) { + /** + * @inheritdoc + */ + TreeMultiMap.prototype.swap = function (obj) { + if (obj instanceof TreeMultiMap && this.key_comp() == obj.key_comp()) { this._Swap(obj); _a = [obj.tree_, this.tree_], this.tree_ = _a[0], obj.tree_ = _a[1]; } @@ -9659,73 +8183,75 @@ var std; _super.prototype.swap.call(this, obj); var _a; }; - return TreeSet; - }(std.base.UniqueSet)); - std.TreeSet = TreeSet; + return TreeMultiMap; + }(std.base.MultiMap)); + std.TreeMultiMap = TreeMultiMap; })(std || (std = {})); /// -/// +/// var std; (function (std) { /** - *

Tree-structured map, std::map of STL.

- * - *

{@link TreeMap TreeMaps} are associative containers that store elements formed by a combination of a - * key value (Key) and a mapped value (T), following order.

+ *

Tree-structured multiple-key set.

* - *

In a {@link TreeMap}, the key values are generally used to sort and uniquely identify the elements, - * while the mapped values store the content associated to this key. The types of key and - * mapped value may differ, and are grouped together in member type value_type, which is a {@link Pair} - * type combining both:

+ *

{@link TreeMultiSet TreeMultiSets} are containers that store elements following a specific order, and + * where multiple elements can have equivalent values.

* - *

typedef Pair value_type;

+ *

In a {@link TreeMultiSet}, the value of an element also identifies it (the value is itself + * the key, of type T). The value of the elements in a {@link TreeMultiSet} cannot + * be modified once in the container (the elements are always const), but they can be inserted or removed + * from the

* - *

Internally, the elements in a {@link TreeMap} are always sorted by its key following a - * strict weak ordering criterion indicated by its internal comparison method {@link less}. + *

Internally, the elements in a {@link TreeMultiSet TreeMultiSets} are always sorted following a strict + * weak ordering criterion indicated by its internal comparison method (of {@link IComparable.less less}).

* - *

{@link TreeMap} containers are generally slower than {@link HashMap HashMap} containers to access individual - * elements by their key, but they allow the direct iteration on subsets based on their order.

+ *

{@link TreeMultiSet} containers are generally slower than {@link HashMultiSet} containers + * to access individual elements by their key, but they allow the direct iteration on subsets based on + * their order.

* - *

{@link TreeMap}s are typically implemented as binary search trees.

+ *

{@link TreeMultiSet TreeMultiSets} are typically implemented as binary search trees.

* - *

- *

+ *

+ *

* *

Container properties

*
*
Associative
- *
Elements in associative containers are referenced by their key and not by their absolute - * position in the container.
+ *
+ * Elements in associative containers are referenced by their key and not by their absolute + * position in the container. + *
* *
Ordered
- *
The elements in the container follow a strict order at all times. All inserted elements are - * given a position in this order.
+ *
+ * The elements in the container follow a strict order at all times. All inserted elements are + * given a position in this order. + *
* - *
Map
- *
Each element associates a key to a mapped value: - * Keys are meant to identify the elements whose main content is the mapped value.
+ *
Set
+ *
The value of an element is also the key used to identify it.
* - *
Unique keys
- *
No two elements in the container can have equivalent keys.
+ *
Multiple equivalent keys
+ *
Multiple elements in the container can have equivalent keys.
*
* - * @param Type of the keys. Each element in a map is uniquely identified by its key value. - * @param Type of the mapped value. Each element in a map stores some data as its mapped value. + * @param Type of the elements. Each element in a {@link TreeMultiSet} container is also identified + * by this value (each value is itself also the element's key). * - * @reference http://www.cplusplus.com/reference/map/map + * @reference http://www.cplusplus.com/reference/set/multiset * @author Jeongho Nam */ - var TreeMap = (function (_super) { - __extends(TreeMap, _super); - function TreeMap() { + var TreeMultiSet = (function (_super) { + __extends(TreeMultiSet, _super); + function TreeMultiSet() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i - 0] = arguments[_i]; } // INIT MEMBERS _super.call(this); - this.tree_ = new std.base.PairTree(this); - if (args.length >= 1 && args[0] instanceof TreeMap) { + this.tree_ = new std.base.AtomicTree(this); + if (args.length >= 1 && args[0] instanceof TreeMultiSet) { // COPY CONSTRUCTOR var container = args[0]; // PARAMETER if (args.length == 2) @@ -9758,7 +8284,7 @@ var std; /** * @inheritdoc */ - TreeMap.prototype.clear = function () { + TreeMultiSet.prototype.clear = function () { _super.prototype.clear.call(this); this.tree_.clear(); }; @@ -9768,9 +8294,9 @@ var std; /** * @inheritdoc */ - TreeMap.prototype.find = function (key) { - var node = this.tree_.find(key); - if (node == null || std.equal_to(node.value.first, key) == false) + TreeMultiSet.prototype.find = function (val) { + var node = this.tree_.find(val); + if (node == null || std.equal_to(val, node.value.value) == false) return this.end(); else return node.value; @@ -9778,33 +8304,50 @@ var std; /** * @inheritdoc */ - TreeMap.prototype.key_comp = function () { + TreeMultiSet.prototype.count = function (val) { + var it = this.find(val); + var cnt = 0; + for (; !it.equal_to(this.end()) && std.equal_to(it.value, val); it = it.next()) + cnt++; + return cnt; + }; + /** + * @inheritdoc + */ + TreeMultiSet.prototype.key_comp = function () { return this.tree_.key_comp(); }; /** * @inheritdoc */ - TreeMap.prototype.value_comp = function () { - return this.tree_.value_comp(); + TreeMultiSet.prototype.value_comp = function () { + return this.tree_.key_comp(); }; /** * @inheritdoc */ - TreeMap.prototype.lower_bound = function (key) { - return this.tree_.lower_bound(key); + TreeMultiSet.prototype.lower_bound = function (val) { + return this.tree_.lower_bound(val); }; /** * @inheritdoc */ - TreeMap.prototype.upper_bound = function (key) { - return this.tree_.upper_bound(key); + TreeMultiSet.prototype.upper_bound = function (val) { + return this.tree_.upper_bound(val); }; /** * @inheritdoc */ - TreeMap.prototype.equal_range = function (key) { - return this.tree_.equal_range(key); + TreeMultiSet.prototype.equal_range = function (val) { + return this.tree_.equal_range(val); }; + ///** + // * @hidden + // */ + //public _Get_tree(): base.AtomicTree + //{ + // return this.tree_; + //} /* ========================================================= ELEMENTS I/O - INSERT @@ -9816,42 +8359,46 @@ var std; /** * @hidden */ - TreeMap.prototype._Insert_by_pair = function (pair) { - var node = this.tree_.find(pair.first); - // IF EQUALS, THEN RETURN FALSE - if (node != null && std.equal_to(node.value.first, pair.first) == true) - return std.make_pair(node.value, false); - // INSERTS + TreeMultiSet.prototype._Insert_by_val = function (val) { + var node = this.tree_.find(val); var it; - if (node == null) + // FIND NODE + if (node == null) { it = this.end(); - else if (this.key_comp()(node.value.first, pair.first) == true) + } + else if (std.equal_to(node.value.value, val) == true) { it = node.value.next(); - else + } + else if (this.key_comp()(node.value.value, val) == true) { + it = node.value.next(); + while (it.equal_to(this.end()) == false && this.key_comp()(it.value, val)) + it = it.next(); + } + else { it = node.value; - // ITERATOR TO RETURN - it = new std.MapIterator(this, this["data_"].insert(it.get_list_iterator(), pair)); + } + ///// + // INSERTS + ///// + it = new std.SetIterator(this, this["data_"].insert(it.get_list_iterator(), val)); this._Handle_insert(it, it.next()); // POST-PROCESS - return std.make_pair(it, true); + return it; }; /** * @hidden */ - TreeMap.prototype._Insert_by_hint = function (hint, pair) { - // FIND KEY - if (this.has(pair.first) == true) - return this.end(); + TreeMultiSet.prototype._Insert_by_hint = function (hint, val) { // VALIDATE HINT var ret; - var compare = this.key_comp(); - // hint < current && current < next - if (compare(hint.first, pair.first) == true - && (hint.next().equal_to(this.end()) || compare(pair.first, hint.next().first) == true)) { + var compare = this.tree_.key_comp(); + // hint <= current && current <= next + if ((compare(hint.value, val) || std.equal_to(hint.value, val)) + && (hint.next().equal_to(this.end()) || (compare(val, hint.next().value) || std.equal_to(val, hint.next().value)))) { /////// // RIGHT HINT /////// // INSERT - ret = new std.MapIterator(this, this["data_"].insert(hint.get_list_iterator(), pair)); + ret = new std.SetIterator(this, this["data_"].insert(hint.get_list_iterator(), val)); // POST-PROCESS this._Handle_insert(ret, ret.next()); } @@ -9860,16 +8407,16 @@ var std; // WRONG HINT /////// // INSERT BY AUTOMATIC NODE FINDING - ret = this._Insert_by_pair(pair).first; + ret = this._Insert_by_val(val); } return ret; }; /** * @hidden */ - TreeMap.prototype._Insert_by_range = function (first, last) { + TreeMultiSet.prototype._Insert_by_range = function (first, last) { for (; !first.equal_to(last); first = first.next()) - this._Insert_by_pair(std.make_pair(first.value.first, first.value.second)); + this._Insert_by_val(first.value); }; /* --------------------------------------------------------- POST-PROCESS @@ -9877,21 +8424,18 @@ var std; /** * @inheritdoc */ - TreeMap.prototype._Handle_insert = function (first, last) { + TreeMultiSet.prototype._Handle_insert = function (first, last) { this.tree_.insert(first); }; /** * @inheritdoc */ - TreeMap.prototype._Handle_erase = function (first, last) { + TreeMultiSet.prototype._Handle_erase = function (first, last) { for (; !first.equal_to(last); first = first.next()) this.tree_.erase(last); }; - /** - * @inheritdoc - */ - TreeMap.prototype.swap = function (obj) { - if (obj instanceof TreeMap && this.key_comp() == obj.key_comp()) { + TreeMultiSet.prototype.swap = function (obj) { + if (obj instanceof TreeMultiSet && this.key_comp() == obj.key_comp()) { this._Swap(obj); _a = [obj.tree_, this.tree_], this.tree_ = _a[0], obj.tree_ = _a[1]; } @@ -9899,33 +8443,32 @@ var std; _super.prototype.swap.call(this, obj); var _a; }; - return TreeMap; - }(std.base.UniqueMap)); - std.TreeMap = TreeMap; + return TreeMultiSet; + }(std.base.MultiSet)); + std.TreeMultiSet = TreeMultiSet; })(std || (std = {})); /// -/// +/// var std; (function (std) { /** - *

Tree-structured multiple-key set.

+ *

Tree-structured set, std::set of STL.

* - *

{@link TreeMultiSet TreeMultiSets} are containers that store elements following a specific order, and - * where multiple elements can have equivalent values.

+ *

{@link TreeSet}s are containers that store unique elements following a specific order.

* - *

In a {@link TreeMultiSet}, the value of an element also identifies it (the value is itself - * the key, of type T). The value of the elements in a {@link TreeMultiSet} cannot - * be modified once in the container (the elements are always const), but they can be inserted or removed - * from the

+ *

In a {@link TreeSet}, the value of an element also identifies it (the value is itself the + * key, of type T), and each value must be unique. The value of the elements in a + * {@link TreeSet} cannot be modified once in the container (the elements are always const), but they + * can be inserted or removed from the

* - *

Internally, the elements in a {@link TreeMultiSet TreeMultiSets} are always sorted following a strict - * weak ordering criterion indicated by its internal comparison method (of {@link IComparable.less less}).

+ *

Internally, the elements in a {@link TreeSet} are always sorted following a specific strict weak + * ordering criterion indicated by its internal comparison method (of {@link less}).

* - *

{@link TreeMultiSet} containers are generally slower than {@link HashMultiSet} containers - * to access individual elements by their key, but they allow the direct iteration on subsets based on - * their order.

+ *

{@link TreeSet} containers are generally slower than {@link HashSet} containers to access + * individual elements by their key, but they allow the direct iteration on subsets based on their + * order.

* - *

{@link TreeMultiSet TreeMultiSets} are typically implemented as binary search trees.

+ *

{@link TreeSet}s are typically implemented as binary search trees.

* *

*

@@ -9947,19 +8490,19 @@ var std; *
Set
*
The value of an element is also the key used to identify it.
* - *
Multiple equivalent keys
- *
Multiple elements in the container can have equivalent keys.
+ *
Unique keys
+ *
No two elements in the container can have equivalent keys.
* * - * @param Type of the elements. Each element in a {@link TreeMultiSet} container is also identified - * by this value (each value is itself also the element's key). + * @param Type of the elements. + * Each element in an {@link TreeSet} is also uniquely identified by this value. * - * @reference http://www.cplusplus.com/reference/set/multiset + * @reference http://www.cplusplus.com/reference/set/set * @author Jeongho Nam */ - var TreeMultiSet = (function (_super) { - __extends(TreeMultiSet, _super); - function TreeMultiSet() { + var TreeSet = (function (_super) { + __extends(TreeSet, _super); + function TreeSet() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i - 0] = arguments[_i]; @@ -9967,7 +8510,7 @@ var std; // INIT MEMBERS _super.call(this); this.tree_ = new std.base.AtomicTree(this); - if (args.length >= 1 && args[0] instanceof TreeMultiSet) { + if (args.length >= 1 && args[0] instanceof TreeSet) { // COPY CONSTRUCTOR var container = args[0]; // PARAMETER if (args.length == 2) @@ -10000,7 +8543,7 @@ var std; /** * @inheritdoc */ - TreeMultiSet.prototype.clear = function () { + TreeSet.prototype.clear = function () { _super.prototype.clear.call(this); this.tree_.clear(); }; @@ -10010,9 +8553,9 @@ var std; /** * @inheritdoc */ - TreeMultiSet.prototype.find = function (val) { + TreeSet.prototype.find = function (val) { var node = this.tree_.find(val); - if (node == null || std.equal_to(val, node.value.value) == false) + if (node == null || std.equal_to(node.value.value, val) == false) return this.end(); else return node.value; @@ -10020,50 +8563,33 @@ var std; /** * @inheritdoc */ - TreeMultiSet.prototype.count = function (val) { - var it = this.find(val); - var cnt = 0; - for (; !it.equal_to(this.end()) && std.equal_to(it.value, val); it = it.next()) - cnt++; - return cnt; - }; - /** - * @inheritdoc - */ - TreeMultiSet.prototype.key_comp = function () { + TreeSet.prototype.key_comp = function () { return this.tree_.key_comp(); }; /** * @inheritdoc */ - TreeMultiSet.prototype.value_comp = function () { + TreeSet.prototype.value_comp = function () { return this.tree_.key_comp(); }; /** * @inheritdoc */ - TreeMultiSet.prototype.lower_bound = function (val) { + TreeSet.prototype.lower_bound = function (val) { return this.tree_.lower_bound(val); }; /** * @inheritdoc */ - TreeMultiSet.prototype.upper_bound = function (val) { + TreeSet.prototype.upper_bound = function (val) { return this.tree_.upper_bound(val); }; /** * @inheritdoc */ - TreeMultiSet.prototype.equal_range = function (val) { + TreeSet.prototype.equal_range = function (val) { return this.tree_.equal_range(val); }; - ///** - // * @hidden - // */ - //public _Get_tree(): base.AtomicTree - //{ - // return this.tree_; - //} /* ========================================================= ELEMENTS I/O - INSERT @@ -10075,41 +8601,36 @@ var std; /** * @hidden */ - TreeMultiSet.prototype._Insert_by_val = function (val) { + TreeSet.prototype._Insert_by_val = function (val) { var node = this.tree_.find(val); - var it; + // IF EQUALS, THEN RETURN FALSE + if (node != null && std.equal_to(node.value.value, val) == true) + return std.make_pair(node.value, false); // FIND NODE - if (node == null) { + var it; + if (node == null) it = this.end(); - } - else if (std.equal_to(node.value.value, val) == true) { - it = node.value.next(); - } - else if (this.key_comp()(node.value.value, val) == true) { + else if (this.key_comp()(node.value.value, val) == true) it = node.value.next(); - while (it.equal_to(this.end()) == false && this.key_comp()(it.value, val)) - it = it.next(); - } - else { + else it = node.value; - } ///// // INSERTS ///// it = new std.SetIterator(this, this["data_"].insert(it.get_list_iterator(), val)); this._Handle_insert(it, it.next()); // POST-PROCESS - return it; + return std.make_pair(it, true); }; - /** - * @hidden - */ - TreeMultiSet.prototype._Insert_by_hint = function (hint, val) { + TreeSet.prototype._Insert_by_hint = function (hint, val) { + // FIND KEY + if (this.has(val) == true) + return this.end(); // VALIDATE HINT var ret; var compare = this.tree_.key_comp(); - // hint <= current && current <= next - if ((compare(hint.value, val) || std.equal_to(hint.value, val)) - && (hint.next().equal_to(this.end()) || (compare(val, hint.next().value) || std.equal_to(val, hint.next().value)))) { + // hint < current && current < next + if (compare(hint.value, val) == true + && (hint.next().equal_to(this.end()) || compare(val, hint.next().value) == true)) { /////// // RIGHT HINT /////// @@ -10123,14 +8644,14 @@ var std; // WRONG HINT /////// // INSERT BY AUTOMATIC NODE FINDING - ret = this._Insert_by_val(val); + ret = this._Insert_by_val(val).first; } return ret; }; /** * @hidden */ - TreeMultiSet.prototype._Insert_by_range = function (first, last) { + TreeSet.prototype._Insert_by_range = function (first, last) { for (; !first.equal_to(last); first = first.next()) this._Insert_by_val(first.value); }; @@ -10140,18 +8661,18 @@ var std; /** * @inheritdoc */ - TreeMultiSet.prototype._Handle_insert = function (first, last) { + TreeSet.prototype._Handle_insert = function (first, last) { this.tree_.insert(first); }; /** * @inheritdoc */ - TreeMultiSet.prototype._Handle_erase = function (first, last) { + TreeSet.prototype._Handle_erase = function (first, last) { for (; !first.equal_to(last); first = first.next()) this.tree_.erase(last); }; - TreeMultiSet.prototype.swap = function (obj) { - if (obj instanceof TreeMultiSet && this.key_comp() == obj.key_comp()) { + TreeSet.prototype.swap = function (obj) { + if (obj instanceof TreeSet && this.key_comp() == obj.key_comp()) { this._Swap(obj); _a = [obj.tree_, this.tree_], this.tree_ = _a[0], obj.tree_ = _a[1]; } @@ -10159,116 +8680,210 @@ var std; _super.prototype.swap.call(this, obj); var _a; }; - return TreeMultiSet; - }(std.base.MultiSet)); - std.TreeMultiSet = TreeMultiSet; + return TreeSet; + }(std.base.UniqueSet)); + std.TreeSet = TreeSet; +})(std || (std = {})); +/// +var std; +(function (std) { + /** + *

Running on Node.

+ * + *

Test whether the JavaScript is running on Node.

+ * + * @references http://stackoverflow.com/questions/17575790/environment-detection-node-js-or-browser + */ + function is_node() { + if (typeof process === "object") + if (typeof process.versions === "object") + if (typeof process.versions.node !== "undefined") + return true; + return false; + } + std.is_node = is_node; + /** + *

Pair of values.

+ * + *

This class couples together a pair of values, which may be of different types (T1 and + * T2). The individual values can be accessed through its public members {@link first} and + * {@link second}.

+ * + * @param Type of member {@link first}. + * @param Type of member {@link second}. + * + * @reference http://www.cplusplus.com/reference/utility/pair + * @author Jeongho Nam + */ + var Pair = (function () { + /* --------------------------------------------------------- + CONSTRUCTORS + --------------------------------------------------------- */ + /** + *

Construct from pair values.

+ * + * @param first The first value of the Pair + * @param second The second value of the Pair + */ + function Pair(first, second) { + this.first = first; + this.second = second; + } + /* --------------------------------------------------------- + COMPARISON + --------------------------------------------------------- */ + /** + *

Whether a Pair is equal with the Pair.

+ *

Compare each first and second value of two Pair(s) and returns whether they are equal or not.

+ * + *

If stored key and value in a Pair are not number or string but an object like a class or struct, + * the comparison will be executed by a member method (SomeObject)::equal_to(). If the object does not have + * the member method equal_to(), only address of pointer will be compared.

+ * + * @param obj A Map to compare + * @return Indicates whether equal or not. + */ + Pair.prototype.equal_to = function (pair) { + return std.equal_to(this.first, pair.first) && std.equal_to(this.second, pair.second); + }; + Pair.prototype.less = function (pair) { + if (std.equal_to(this.first, pair.first) == false) + return std.less(this.first, pair.first); + else + return std.less(this.second, pair.second); + }; + return Pair; + }()); + std.Pair = Pair; + /** + *

Construct {@link Pair} object.

+ * + *

Constructs a {@link Pair} object with its {@link Pair.first first} element set to x and its + * {@link Pair.second second} element set to y.

+ * + *

The template types can be implicitly deduced from the arguments passed to {@link make_pair}.

+ * + *

{@link Pair} objects can be constructed from other {@link Pair} objects containing different types, if the + * respective types are implicitly convertible.

+ * + * @param x Value for member {@link Pair.first first}. + * @param y Value for member {@link Pair.second second}. + * + * @return A {@link Pair} object whose elements {@link Pair.first first} and {@link Pair.second second} are set to + * x and y respectivelly. + */ + function make_pair(x, y) { + return new Pair(x, y); + } + std.make_pair = make_pair; })(std || (std = {})); /// -/// +/// var std; (function (std) { /** - *

Tree-structured multiple-key map.

+ *

Vector, the dynamic array.

* - *

{@link TreeMultiMap TreeMultiMaps} are associative containers that store elements formed by a combination of - * a key value and a mapped value, following a specific order, and where multiple elements can - * have equivalent keys.

+ *

{@link Vector}s are sequence containers representing arrays that can change in size.

* - *

In a {@link TreeMultiMap}, the key values are generally used to sort and uniquely identify - * the elements, while the mapped values store the content associated to this key. The types of - * key and mapped value may differ, and are grouped together in member type - * value_type, which is a {@link Pair} type combining both:

+ *

Just like arrays, {@link Vector}s use contiguous storage locations for their elements, which means that + * their elements can also be accessed using offsets on regular pointers to its elements, and just as efficiently + * as in arrays. But unlike arrays, their size can change dynamically, with their storage being handled + * automatically by the

* - *

typedef Pair value_type;

+ *

Internally, {@link Vector}s use a dynamically allocated array to store their elements. This array may need + * to be reallocated in order to grow in size when new elements are inserted, which implies allocating a new + * array and moving all elements to it. This is a relatively expensive task in terms of processing time, and + * thus, {@link Vector}s do not reallocate each time an element is added to the

* - *

Internally, the elements in a {@link TreeMultiMap}are always sorted by its key following a - * strict weak ordering criterion indicated by its internal comparison method (of {@link less}).

+ *

Instead, {@link Vector} containers may allocate some extra storage to accommodate for possible growth, and + * thus the container may have an actual {@link capacity} greater than the storage strictly needed to contain its + * elements (i.e., its {@link size}). Libraries can implement different strategies for growth to balance between + * memory usage and reallocations, but in any case, reallocations should only happen at logarithmically growing + * intervals of {@link size} so that the insertion of individual elements at the end of the {@link Vector} can be + * provided with amortized constant time complexity (see {@link push_back push_back()}).

* - *

{@link TreeMultiMap}containers are generally slower than {@link HashMap} containers - * to access individual elements by their key, but they allow the direct iteration on subsets based - * on their order.

+ *

Therefore, compared to arrays, {@link Vector}s consume more memory in exchange for the ability to manage + * storage and grow dynamically in an efficient way.

* - *

{@link TreeMultiMap TreeMultiMaps} are typically implemented as binary search trees.

+ *

Compared to the other dynamic sequence containers ({@link Deque}s, {@link List}s), {@link Vector Vectors} + * are very efficient accessing its elements (just like arrays) and relatively efficient adding or removing + * elements from its end. For operations that involve inserting or removing elements at positions other than the + * end, they perform worse than the others, and have less consistent iterators and references than {@link List}s. + *

* - *

< - * img src="http://samchon.github.io/typescript-stl/images/design/class_diagram/map_containers.png" style="max-width: 100%" />

+ *

+ * + *

* *

Container properties

*
- *
Associative
- *
- * Elements in associative containers are referenced by their key and not by their absolute - * position in the container. - *
- * - *
Ordered
+ *
Sequence
*
- * The elements in the container follow a strict order at all times. All inserted elements are - * given a position in this order. + * Elements in sequence containers are ordered in a strict linear sequence. Individual elements are + * accessed by their position in this sequence. *
* - *
Map
+ *
Dynamic array
*
- * Each element associates a key to a mapped value: - * Keys are meant to identify the elements whose main content is the mapped value. + * Allows direct access to any element in the sequence, even through pointer arithmetics, and provides + * relatively fast addition/removal of elements at the end of the sequence. *
- * - *
Multiple equivalent keys
- *
Multiple elements in the container can have equivalent keys.
*
* - * @param Type of the keys. Each element in a map is uniquely identified by its key value. - * @param Type of the mapped value. Each element in a map stores some data as its mapped value. + * @param Type of the elements. * - * @reference http://www.cplusplus.com/reference/map/multimap + * @reference http://www.cplusplus.com/reference/vector/vector * @author Jeongho Nam */ - var TreeMultiMap = (function (_super) { - __extends(TreeMultiMap, _super); - function TreeMultiMap() { + var Vector = (function (_super) { + __extends(Vector, _super); + function Vector() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i - 0] = arguments[_i]; } - // INIT MEMBERS _super.call(this); - this.tree_ = new std.base.PairTree(this); - if (args.length >= 1 && args[0] instanceof TreeMultiMap) { - // COPY CONSTRUCTOR - var container = args[0]; // PARAMETER - if (args.length == 2) - this.tree_["compare_"] = (args[1]); - this.assign(container.begin(), container.end()); + if (args.length == 0) { } - else if (args.length >= 1 && args[0] instanceof Array) { - // INITIALIZER LIST CONSTRUCTOR - var items = args[0]; // PARAMETER - if (args.length == 2) - this.tree_["compare_"] = (args[1]); - this.push.apply(this, items); + else if (args.length == 1 && args[0] instanceof Array) { + // CONSTRUCT FROM AN ARRAY OF ITEMS + var array = args[0]; + _super.prototype.push.apply(this, array); } - else if (args.length >= 2 && args[0] instanceof std.Iterator && args[1] instanceof std.Iterator) { - // RANGE CONSTRUCTOR - var first = args[0]; // PARAMETER 1 - var last = args[1]; // PARAMETER 2 - if (args.length == 2) - this.tree_["compare_"] = (args[2]); - this.assign(first, last); + else if (args.length == 1 && typeof args[0] == "number") { + // CONSTRUCT FROM SIZE + var size = args[0]; + this.length = size; } - else if (args.length == 1) { - // DEFAULT CONSTRUCTOR WITH SPECIFIED COMPARISON FUNCTION - this.tree_["compare_"] = (args[0]); + else if (args.length == 2 && typeof args[0] == "number") { + // CONSTRUCT FROM SIZE AND REPEATING VALUE + var size = args[0]; + var val = args[1]; + this.assign(size, val); + } + else if (args.length == 2 && args[0] instanceof std.Iterator && args[1] instanceof std.Iterator) { + // CONSTRUCT FROM INPUT ITERATORS + var begin_5 = args[0]; + var end_4 = args[1]; + this.assign(begin_5, end_4); } } - /* --------------------------------------------------------- - ASSIGN & CLEAR - --------------------------------------------------------- */ + Vector.prototype.assign = function (first, second) { + this.clear(); + this.insert(this.end(), first, second); + }; /** * @inheritdoc */ - TreeMultiMap.prototype.clear = function () { - _super.prototype.clear.call(this); - this.tree_.clear(); + Vector.prototype.reserve = function (size) { + // NOTHING TO DO ESPECIALLY + }; + /** + * @inheritdoc + */ + Vector.prototype.clear = function () { + this.erase(this.begin(), this.end()); }; /* ========================================================= ACCESSORS @@ -10276,439 +8891,2001 @@ var std; /** * @inheritdoc */ - TreeMultiMap.prototype.find = function (key) { - var node = this.tree_.find(key); - if (node == null || std.equal_to(node.value.first, key) == false) + Vector.prototype.begin = function () { + if (this.empty() == true) return this.end(); else - return node.value; + return new std.VectorIterator(this, 0); }; /** * @inheritdoc */ - TreeMultiMap.prototype.count = function (key) { - var it = this.find(key); - var cnt = 0; - for (; !it.equal_to(this.end()) && std.equal_to(it.first, key); it = it.next()) - cnt++; - return cnt; + Vector.prototype.end = function () { + return new std.VectorIterator(this, -1); }; /** * @inheritdoc */ - TreeMultiMap.prototype.key_comp = function () { - return this.tree_.key_comp(); + Vector.prototype.rbegin = function () { + return new std.VectorReverseIterator(this.end()); }; /** * @inheritdoc */ - TreeMultiMap.prototype.value_comp = function () { - return this.tree_.value_comp(); + Vector.prototype.rend = function () { + return new std.VectorReverseIterator(this.begin()); }; /** * @inheritdoc */ - TreeMultiMap.prototype.lower_bound = function (key) { - return this.tree_.lower_bound(key); + Vector.prototype.size = function () { + return this.length; }; /** * @inheritdoc */ - TreeMultiMap.prototype.upper_bound = function (key) { - return this.tree_.upper_bound(key); + Vector.prototype.capacity = function () { + return this.length; + }; + /** + * @inheritdoc + */ + Vector.prototype.empty = function () { + return this.length == 0; + }; + /** + * @inheritdoc + */ + Vector.prototype.at = function (index) { + if (index < this.size()) + return this[index]; + else + throw new std.OutOfRange("Target index is greater than Vector's size."); + }; + /** + * @inheritdoc + */ + Vector.prototype.set = function (index, val) { + if (index > this.length) + throw new std.OutOfRange("Target index is greater than Vector's size."); + var prev = this[index]; + this[index] = val; + return prev; + }; + /** + * @inheritdoc + */ + Vector.prototype.front = function () { + return this.at(0); + }; + /** + * @inheritdoc + */ + Vector.prototype.back = function () { + return this.at(this.length - 1); + }; + /* ========================================================= + ELEMENTS I/O + - INSERT + - ERASE + - SWAP + ============================================================ + INSERT + --------------------------------------------------------- */ + /** + * @inheritdoc + */ + Vector.prototype.push_back = function (val) { + _super.prototype.push.call(this, val); + }; + Vector.prototype.insert = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i - 0] = arguments[_i]; + } + // REVERSE_ITERATOR TO ITERATOR + var ret; + var is_reverse_iterator = false; + if (args[0] instanceof std.VectorReverseIterator) { + is_reverse_iterator = true; + args[0] = args[0].base().prev(); + } + // BRANCHES + if (args.length == 2) + ret = this.insert_by_val(args[0], args[1]); + else if (args.length == 3 && typeof args[1] == "number") + ret = this._Insert_by_repeating_val(args[0], args[1], args[2]); + else + ret = this._Insert_by_range(args[0], args[1], args[2]); + // RETURNS + if (is_reverse_iterator == true) + return new std.VectorReverseIterator(ret.next()); + else + return ret; }; /** - * @inheritdoc + * @hidden */ - TreeMultiMap.prototype.equal_range = function (key) { - return this.tree_.equal_range(key); + Vector.prototype.insert_by_val = function (position, val) { + return this._Insert_by_repeating_val(position, 1, val); }; - /* ========================================================= - ELEMENTS I/O - - INSERT - - POST-PROCESS - - SWAP - ============================================================ - INSERT - --------------------------------------------------------- */ /** * @hidden */ - TreeMultiMap.prototype._Insert_by_pair = function (pair) { - var node = this.tree_.find(pair.first); - var it; - if (node == null) { - it = this.end(); - } - else if (std.equal_to(node.value.first, pair.first) == true) { - it = node.value.next(); + Vector.prototype._Insert_by_repeating_val = function (position, n, val) { + if (position.index == -1) { + // WHEN INSERT TO THE LAST + for (var i = 0; i < n; i++) + _super.prototype.push.call(this, val); + return this.begin(); } - else if (this.key_comp()(node.value.first, pair.first) == true) { - it = node.value.next(); - while (it.equal_to(this.end()) == false && this.key_comp()(it.first, pair.first)) - it = it.next(); + else { + /////// + // INSERT TO THE MIDDLE POSITION + /////// + // CUT RIGHT SIDE + var spliced_array = _super.prototype.splice.call(this, position.index); + var insert_size = 0; + // INSERT ELEMENTS + for (var i = 0; i < n; i++) { + _super.prototype.push.call(this, val); + insert_size++; + } + _super.prototype.push.apply(this, spliced_array); // CONCAT THE SPLICEDS + return position; } - else - it = node.value; - // ITERATOR TO RETURN - it = new std.MapIterator(this, this["data_"].insert(it.get_list_iterator(), pair)); - this._Handle_insert(it, it.next()); // POST-PROCESS - return it; }; /** * @hidden */ - TreeMultiMap.prototype._Insert_by_hint = function (hint, pair) { - // FIND KEY - if (this.has(pair.first) == true) - return this.end(); - // VALIDATE HINT - var ret; - var compare = this.key_comp(); - // hint <= current && current <= next - if ((compare(hint.first, pair.first) || std.equal_to(hint.first, pair.first)) - && (hint.next().equal_to(this.end()) || (compare(pair.first, hint.next().first) || std.equal_to(pair.first, hint.next().first)))) { - /////// - // RIGHT HINT - /////// - // INSERT - ret = new std.MapIterator(this, this["data_"].insert(hint.get_list_iterator(), pair)); - // POST-PROCESS - this._Handle_insert(ret, ret.next()); + Vector.prototype._Insert_by_range = function (position, first, last) { + if (position.index == -1) { + // WHEN INSERT TO THE LAST + for (; !first.equal_to(last); first = first.next()) + _super.prototype.push.call(this, first.value); + return this.begin(); } else { /////// - // WRONG HINT + // INSERT TO THE MIDDLE POSITION /////// - // INSERT BY AUTOMATIC NODE FINDING - ret = this._Insert_by_pair(pair); + // CUT RIGHT SIDE + var spliced_array = _super.prototype.splice.call(this, position.index); + var insert_size = 0; + // INSERT ELEMENTS + for (; !first.equal_to(last); first = first.next()) { + _super.prototype.push.call(this, first.value); + insert_size++; + } + _super.prototype.push.apply(this, spliced_array); // CONCAT THE SPLICEDS + return position; } - return ret; + }; + /* --------------------------------------------------------- + ERASE + --------------------------------------------------------- */ + /** + * @inheritdoc + */ + Vector.prototype.pop_back = function () { + this.erase(this.end().prev()); + }; + Vector.prototype.erase = function (first, last) { + if (last === void 0) { last = first.next(); } + var ret; + var is_reverse_iterator = false; + // REVERSE_ITERATOR TO ITERATOR + if (first instanceof std.VectorReverseIterator) { + is_reverse_iterator = true; + var first_it = last.base(); + var last_it = first.base(); + first = first_it; + last = last_it; + } + // ERASE ELEMENTS + ret = this._Erase_by_range(first, last); + // RETURN BRANCHES + if (is_reverse_iterator == true) + return new std.VectorReverseIterator(ret.next()); + else + return ret; }; /** * @hidden */ - TreeMultiMap.prototype._Insert_by_range = function (first, last) { - for (; !first.equal_to(last); first = first.next()) - this._Insert_by_pair(std.make_pair(first.value.first, first.value.second)); + Vector.prototype._Erase_by_range = function (first, last) { + if (first.index == -1) + return first; + // ERASE ELEMENTS + if (last.index == -1) { + _super.prototype.splice.call(this, first.index); + return this.end(); + } + else + _super.prototype.splice.call(this, first.index, last.index - first.index); + return first; + }; + Vector.prototype.swap = function (obj) { + var supplement = new Vector(this.begin(), this.end()); + this.assign(obj.begin(), obj.end()); + obj.assign(supplement.begin(), supplement.end()); }; + return Vector; + }(Array)); + std.Vector = Vector; +})(std || (std = {})); +var std; +(function (std) { + /** + *

An iterator of Vector.

+ * + *

+ * + *

+ * + * @param Type of the elements. + * + * @author Jeongho Nam + */ + var VectorIterator = (function (_super) { + __extends(VectorIterator, _super); /* --------------------------------------------------------- - POST-PROCESS + CONSTRUCTORS + --------------------------------------------------------- */ + /** + *

Construct from the source {@link Vector container}.

+ * + *

Note

+ *

Do not create the iterator directly, by yourself.

+ *

Use {@link Vector.begin begin()}, {@link Vector.end end()} in {@link Vector container} instead.

+ * + * @param source The source {@link Vector container} to reference. + * @param index Sequence number of the element in the source {@link Vector}. + */ + function VectorIterator(source, index) { + _super.call(this, source); + this.index_ = index; + } + Object.defineProperty(VectorIterator.prototype, "vector", { + /* --------------------------------------------------------- + ACCESSORS + --------------------------------------------------------- */ + /** + * @hidden + */ + get: function () { + return this.source_; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(VectorIterator.prototype, "value", { + /** + * @inheritdoc + */ + get: function () { + return this.vector.at(this.index_); + }, + /** + * Set value of the iterator is pointing to. + * + * @param val Value to set. + */ + set: function (val) { + this.vector.set(this.index_, val); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(VectorIterator.prototype, "index", { + /** + * Get index. + */ + get: function () { + return this.index_; + }, + enumerable: true, + configurable: true + }); + /* --------------------------------------------------------- + MOVERS --------------------------------------------------------- */ /** * @inheritdoc */ - TreeMultiMap.prototype._Handle_insert = function (first, last) { - this.tree_.insert(first); + VectorIterator.prototype.prev = function () { + if (this.index_ == -1) + return new VectorIterator(this.vector, this.vector.size() - 1); + else if (this.index_ - 1 < 0) + return this.vector.end(); + else + return new VectorIterator(this.vector, this.index_ - 1); + }; + /** + * @inheritdoc + */ + VectorIterator.prototype.next = function () { + if (this.index_ >= this.source_.size() - 1) + return this.vector.end(); + else + return new VectorIterator(this.vector, this.index_ + 1); }; /** * @inheritdoc */ - TreeMultiMap.prototype._Handle_erase = function (first, last) { - for (; !first.equal_to(last); first = first.next()) - this.tree_.erase(last); + VectorIterator.prototype.advance = function (n) { + var new_index; + if (n < 0 && this.index_ == -1) + new_index = this.vector.size() + n; + else + new_index = this.index_ + n; + if (new_index < 0 || new_index >= this.vector.size()) + return this.vector.end(); + else + return new VectorIterator(this.vector, new_index); + }; + /* --------------------------------------------------------- + COMPARES + --------------------------------------------------------- */ + /** + *

Whether an iterator is equal with the iterator.

+ * + *

Compare two iterators and returns whether they are equal or not.

+ * + *

Note

+ *

Iterator's equal_to() only compare souce container and index number.

+ * + *

Although elements in a pair, key and value are equal_to, if the source map or + * index number is different, then the {@link equal_to equal_to()} will return false. If you want to + * compare the elements of a pair, compare them directly by yourself.

+ * + * @param obj An iterator to compare + * @return Indicates whether equal or not. + */ + VectorIterator.prototype.equal_to = function (obj) { + return _super.prototype.equal_to.call(this, obj) && this.index_ == obj.index_; }; /** * @inheritdoc */ - TreeMultiMap.prototype.swap = function (obj) { - if (obj instanceof TreeMultiMap && this.key_comp() == obj.key_comp()) { - this._Swap(obj); - _a = [obj.tree_, this.tree_], this.tree_ = _a[0], obj.tree_ = _a[1]; - } - else - _super.prototype.swap.call(this, obj); + VectorIterator.prototype.swap = function (obj) { + _a = [obj.value, this.value], this.value = _a[0], obj.value = _a[1]; var _a; }; - return TreeMultiMap; - }(std.base.MultiMap)); - std.TreeMultiMap = TreeMultiMap; + return VectorIterator; + }(std.Iterator)); + std.VectorIterator = VectorIterator; })(std || (std = {})); -/// -/// -/// var std; (function (std) { /** - *

System error exception.

- * - *

This class defines the type of objects thrown as exceptions to report conditions originating during - * runtime from the operating system or other low-level application program interfaces which have an - * associated {@link ErrorCode}.

+ *

A reverse-iterator of Vector.

* - *

The class inherits from {@link RuntimeError}, to which it adds an {@link ErrorCode} as - * member code (and defines a specialized what member).

+ *

+ * + *

* - *

- *

+ * @param Type of the elements. * - * @reference http://www.cplusplus.com/reference/system_error/system_error * @author Jeongho Nam */ - var SystemError = (function (_super) { - __extends(SystemError, _super); - function SystemError() { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i - 0] = arguments[_i]; - } - _super.call(this, ""); - } + var VectorReverseIterator = (function (_super) { + __extends(VectorReverseIterator, _super); /* --------------------------------------------------------- - ACCESSORS + CONSTRUCTORS --------------------------------------------------------- */ /** - *

Get error code.

- * - *

Returns the {@link ErrorCode} object associated with the exception.

+ * Construct from base iterator. + * + * @param base A reference of the base iterator, which iterates in the opposite direction. + */ + function VectorReverseIterator(base) { + _super.call(this, base); + } + /** + * @hidden + */ + VectorReverseIterator.prototype.create_neighbor = function (base) { + return new VectorReverseIterator(base); + }; + Object.defineProperty(VectorReverseIterator.prototype, "value", { + /* --------------------------------------------------------- + ACCESSORS + --------------------------------------------------------- */ + /** + * @inheritdoc + */ + get: function () { + return this.base_.value; + }, + /** + * Set value of the iterator is pointing to. + * + * @param val Value to set. + */ + set: function (val) { + this.base_.value = val; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(VectorReverseIterator.prototype, "index", { + /** + * Get index. + */ + get: function () { + return this.base_.index; + }, + enumerable: true, + configurable: true + }); + return VectorReverseIterator; + }(std.ReverseIterator)); + std.VectorReverseIterator = VectorReverseIterator; +})(std || (std = {})); +/// +var std; +(function (std) { + var base; + (function (base) { + /** + *

Static class holding enumeration codes of color of Red-black tree.

+ * + *

Color codes imposed to nodes of RB-Tree are following those rules:

+ * + *
    + *
  1. A node is either red or black.
  2. + *
  3. The root is black. This rule is sometimes omitted. Since the root can + * always be changed from red to black, but not + * necessarily vice versa, this rule has little effect on analysis.
  4. + *
  5. All leaves (NIL; null) are black.
  6. + *
  7. If a node is red, then both its children are + * black.
  8. + *
  9. Every path from a given node to any of its descendant NIL nodes contains the same number of + * black nodes. Some definitions: the number of + * black nodes from the root to a node is the node's + * black depth; the uniform number of black + * nodes in all paths from root to the leaves is called the black-height of + * the red-black tree.
  10. + *
+ * + * @author Migrated by Jeongho Nam + */ + (function (Color) { + /** + *

Code of color black.

+ * + *
    + *
  • Those are clearly black: root, leaf nodes or children nodes of red.
  • + *
  • Every path from a given nodes containes the same number of black nodes exclude NIL(s).
  • + *
+ */ + Color[Color["BLACK"] = 0] = "BLACK"; + /** + *

Code of color red.

+ */ + Color[Color["RED"] = 1] = "RED"; + })(base.Color || (base.Color = {})); + var Color = base.Color; + })(base = std.base || (std.base = {})); +})(std || (std = {})); +/// +var std; +(function (std) { + var base; + (function (base) { + (function (Hash) { + Hash[Hash["MIN_SIZE"] = 10] = "MIN_SIZE"; + Hash[Hash["RATIO"] = 1] = "RATIO"; + Hash[Hash["MAX_RATIO"] = 2] = "MAX_RATIO"; + })(base.Hash || (base.Hash = {})); + var Hash = base.Hash; + /** + *

Hask buckets.

+ * + * @author Jeongho Nam + */ + var HashBuckets = (function () { + /* --------------------------------------------------------- + CONSTRUCTORS + --------------------------------------------------------- */ + /** + * Default Constructor. + */ + function HashBuckets() { + this.clear(); + } + /** + *

Reconstruction of hash table.

+ * + *

All the elements in the hash buckets are rearranged according to their hash value into the new set of + * buckets. This may alter the order of iteration of elements within the container.

+ * + *

Notice that {@link rehash rehashes} are automatically performed whenever its number of elements is going + * to greater than its own {@link capacity}.

+ * + * @param size Number of bucket size to rehash. + */ + HashBuckets.prototype.rehash = function (size) { + if (size < Hash.MIN_SIZE) + size = Hash.MIN_SIZE; + var prev_matrix = this.buckets_; + this.buckets_ = new std.Vector(); + for (var i = 0; i < size; i++) + this.buckets_.push_back(new std.Vector()); + for (var i = 0; i < prev_matrix.size(); i++) + for (var j = 0; j < prev_matrix.at(i).size(); j++) { + var val = prev_matrix.at(i).at(j); + var bucket = this.buckets_.at(this.hash_index(val)); + bucket.push_back(val); + this.item_size_++; + } + }; + HashBuckets.prototype.clear = function () { + this.buckets_ = new std.Vector(); + this.item_size_ = 0; + for (var i = 0; i < Hash.MIN_SIZE; i++) + this.buckets_.push_back(new std.Vector()); + }; + /* --------------------------------------------------------- + ACCESSORS + --------------------------------------------------------- */ + HashBuckets.prototype.size = function () { + return this.buckets_.size(); + }; + HashBuckets.prototype.item_size = function () { + return this.item_size_; + }; + HashBuckets.prototype.capacity = function () { + return this.buckets_.size() * Hash.MAX_RATIO; + }; + HashBuckets.prototype.at = function (index) { + return this.buckets_.at(index); + }; + HashBuckets.prototype.hash_index = function (val) { + return std.hash(val) % this.buckets_.size(); + }; + /* --------------------------------------------------------- + ELEMENTS I/O + --------------------------------------------------------- */ + HashBuckets.prototype.insert = function (val) { + this.buckets_.at(this.hash_index(val)).push_back(val); + if (++this.item_size_ > this.capacity()) + this.rehash(this.item_size_ * Hash.RATIO); + }; + HashBuckets.prototype.erase = function (val) { + var bucket = this.buckets_.at(this.hash_index(val)); + for (var i = 0; i < bucket.size(); i++) + if (bucket.at(i) == val) { + bucket.splice(i, 1); + this.item_size_--; + break; + } + }; + return HashBuckets; + }()); + base.HashBuckets = HashBuckets; + })(base = std.base || (std.base = {})); +})(std || (std = {})); +/// +/// +var std; +(function (std) { + var base; + (function (base) { + /** + *

Hash buckets storing {@link MapIterator MapIterators}.

* - *

This value is either the {@link ErrorCode} passed to the construction or its equivalent - * (if constructed with a value and a {@link category}.

+ *

+ * + *

* - * @return The {@link ErrorCode} associated with the object. + * @author Jeongho Nam */ - SystemError.prototype.code = function () { - return this.code_; - }; - return SystemError; - }(std.RuntimeError)); - std.SystemError = SystemError; + var MapHashBuckets = (function (_super) { + __extends(MapHashBuckets, _super); + function MapHashBuckets(map) { + _super.call(this); + this.map = map; + } + MapHashBuckets.prototype.find = function (key) { + var index = std.hash(key) % this.size(); + var bucket = this.at(index); + for (var i = 0; i < bucket.size(); i++) + if (std.equal_to(bucket.at(i).first, key)) + return bucket.at(i); + return this.map.end(); + }; + return MapHashBuckets; + }(base.HashBuckets)); + base.MapHashBuckets = MapHashBuckets; + })(base = std.base || (std.base = {})); })(std || (std = {})); +/// +/// var std; (function (std) { - /** - *

Error category.

- * - *

This type serves as a base class for specific category types.

- * - *

Category types are used to identify the source of an error. They also define the relation between - * {@link ErrorCode} and {@link ErrorCondition}objects of its category, as well as the message set for {@link ErrorCode} - * objects. - * - *

Objects of these types have no distinct values and are not-copyable and not-assignable, and thus can only be - * passed by reference. As such, only one object of each of these types shall exist, each uniquely identifying its own - * category: all error codes and conditions of a same category shall return a reference to same object.

- * - *

- *

- * - * @reference http://www.cplusplus.com/reference/system_error/error_category - * @author Jeongho Nam - */ - var ErrorCategory = (function () { - /* --------------------------------------------------------- - CONSTRUCTORS - --------------------------------------------------------- */ + var base; + (function (base) { /** - * Default Constructor. + *

Hash buckets storing {@link SetIterator SetIterators}.

+ * + *

+ * + *

+ * + * @author Jeongho Nam */ - function ErrorCategory() { - } - /* --------------------------------------------------------- - OPERATORS - --------------------------------------------------------- */ + var SetHashBuckets = (function (_super) { + __extends(SetHashBuckets, _super); + function SetHashBuckets(set) { + _super.call(this); + this.set = set; + } + SetHashBuckets.prototype.find = function (val) { + var index = std.hash(val) % this.size(); + var bucket = this.at(index); + for (var i = 0; i < bucket.size(); i++) + if (std.equal_to(bucket.at(i).value, val)) + return bucket.at(i); + return this.set.end(); + }; + return SetHashBuckets; + }(base.HashBuckets)); + base.SetHashBuckets = SetHashBuckets; + })(base = std.base || (std.base = {})); +})(std || (std = {})); +/// +/// +/// +/// +/// +/// +var std; +(function (std) { + var base; + (function (base) { /** - *

Default error condition.

+ *

Red-black Tree.

* - *

Returns the default {@link ErrorCondition}object of this category that is associated with the - * {@link ErrorCode} identified by a value of val.

+ *

A red-black tree is a kind of self-balancing + * binary search tree. Each node of the binary tree has an extra bit, and that bit is often interpreted as the + * color (red or black) of the node. These color bits + * are used to ensure the tree remains approximately balanced during insertions and deletions.

* - *

Its definition in the base class {@link ErrorCategory} returns the same as constructing an - * {@link ErrorCondition} object with: + *

Balance is preserved by painting each node of the tree with one of two colors (typically called + * 'red' and 'black') in a way that satisfies certain + * properties, which collectively constrain how unbalanced the tree can become in the worst case. When the tree + * is modified, the new tree is subsequently rearranged and repainted to restore the coloring properties. The + * properties are designed in such a way that this rearranging and recoloring can be performed efficiently.

* - *

new ErrorCondition(val, *this);

+ *

The balancing of the tree is not perfect but it is good enough to allow it to guarantee searching in + * O(log n) time, where n is the total number of elements in the tree. The insertion and deletion operations, + * along with the tree rearrangement and recoloring, are also performed in O(log n) time.

* - *

As a virtual member function, this behavior can be overriden in derived classes.

+ *

Tracking the color of each node requires only 1 bit of information per node because there are only two + * colors. The tree does not contain any other data specific to its being a + * red-black tree so its memory footprint is almost + * identical to a classic (uncolored) binary search tree. In many cases the additional bit of information can + * be stored at no additional memory cost.

* - *

This function is called by the default definition of member {@link equivalent equivalent()}, which is used to - * compare {@link ErrorCondition error conditions} with error codes.

+ *

Properties

+ *

In addition to the requirements imposed on a binary search tree the following must be satisfied by a + * red-black tree:

* - * @param val A numerical value identifying an error condition. + *
    + *
  1. A node is either red or black.
  2. + *
  3. + * The root is black. This rule is sometimes omitted. Since the root can + * always be changed from red to black, but not + * necessarily vice versa, this rule has little effect on analysis. + *
  4. + *
  5. All leaves (NIL; null) are black.
  6. + *
  7. + * If a node is red, then both its children are + * black. + *
  8. + *
  9. + * Every path from a given node to any of its descendant NIL nodes contains the same number of + * black nodes. Some definitions: the number of + * black nodes from the root to a node is the node's + * black depth; the uniform number of black + * nodes in all paths from root to the leaves is called the black-height of + * the red-black tree. + *
  10. + *
* - * @return The default {@link ErrorCondition}object associated with condition value val for this category. - */ - ErrorCategory.prototype.default_error_condition = function (val) { - return new std.ErrorCondition(val, this); - }; - ErrorCategory.prototype.equivalent = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i - 0] = arguments[_i]; - } - if (args[1] instanceof std.ErrorCondition) { - var val_code = args[0]; - var cond = args[1]; - return std.equal_to(this.default_error_condition(val_code), cond); - } - else { - var code = args[0]; - var valcond = args[1]; - return std.equal_to(this, code.category()) && code.value() == valcond; - } - }; - return ErrorCategory; - }()); - std.ErrorCategory = ErrorCategory; -})(std || (std = {})); -var std; -(function (std) { - /** - *

Error condition.

- * - *

Objects of this type hold a condition {@link value} associated with a {@link category}.

- * - *

Objects of this type describe errors in a generic way so that they may be portable across different - * systems. This is in contrast with {@link ErrorCode} objects, that may contain system-specific - * information.

- * - *

Because {@link ErrorCondition}objects can be compared with error_code objects directly by using - * relational operators, {@link ErrorCondition}objects are generally used to check whether - * a particular {@link ErrorCode} obtained from the system matches a specific error condition no matter - * the system.

- * - *

The {@link ErrorCategory categories} associated with the {@link ErrorCondition} and the - * {@link ErrorCode} define the equivalences between them.

- * - *

- *

- * - * @reference http://www.cplusplus.com/reference/system_error/error_condition - * @author Jeongho Nam - */ - var ErrorCondition = (function (_super) { - __extends(ErrorCondition, _super); - function ErrorCondition(val, category) { - if (val === void 0) { val = 0; } - if (category === void 0) { category = null; } - _super.call(this, val, category); - } - return ErrorCondition; - }(std.base.ErrorInstance)); - std.ErrorCondition = ErrorCondition; -})(std || (std = {})); -var std; -(function (std) { - /** - *

Error code.

- * - *

Objects of this type hold an error code {@link value} associated with a {@link category}.

- * - *

The operating system and other low-level applications and libraries generate numerical error codes to - * represent possible results. These numerical values may carry essential information for a specific platform, - * but be non-portable from one platform to another.

- * - *

Objects of this class associate such numerical codes to {@link ErrorCategory error categories}, so that they - * can be interpreted when needed as more abstract (and portable) {@link ErrorCondition error conditions}.

- * - *

- *

- * - * @reference http://www.cplusplus.com/reference/system_error/error_code - * @author Jeongho Nam - */ - var ErrorCode = (function (_super) { - __extends(ErrorCode, _super); - function ErrorCode(val, category) { - if (val === void 0) { val = 0; } - if (category === void 0) { category = null; } - _super.call(this, val, category); - } - return ErrorCode; - }(std.base.ErrorInstance)); - std.ErrorCode = ErrorCode; + *

+ * + *

These constraints enforce a critical property of red-black trees: the path from the root to the farthest + * leaf is no more than twice as long as the path from the root to the nearest leaf. The result is that the tree + * is roughly height-balanced. Since operations such as inserting, deleting, and finding values require + * worst-case time proportional to the height of the tree, this theoretical upper bound on the height allows + * red-black trees to be efficient in the worst case, unlike ordinary binary search trees.

+ * + *

To see why this is guaranteed, it suffices to consider the effect of properties 4 and 5 together. For a + * red-black tree T, let B be the number of black nodes in property 5. Let the + * shortest possible path from the root of T to any leaf consist of B black nodes. + * Longer possible paths may be constructed by inserting red nodes. However, property 4 + * makes it impossible to insert more than one consecutive red node. Therefore, + * ignoring any black NIL leaves, the longest possible path consists of 2*B nodes, + * alternating black and red (this is the worst case). + * Counting the black NIL leaves, the longest possible path consists of 2*B-1 + * nodes.

+ * + *

The shortest possible path has all black nodes, and the longest possible + * path alternates between red and black nodes. Since all + * maximal paths have the same number of black nodes, by property 5, this shows + * that no path is more than twice as long as any other path.

+ * + * @param Type of elements. + * + * @reference https://en.wikipedia.org/w/index.php?title=Red%E2%80%93black_tree + * @inventor Rudolf Bayer + * @author Migrated by Jeongho Nam + */ + var XTree = (function () { + /* ========================================================= + CONSTRUCTOR + ========================================================= */ + /** + * Default Constructor. + */ + function XTree() { + this.root_ = null; + } + XTree.prototype.clear = function () { + this.root_ = null; + }; + /* ========================================================= + ACCESSORS + - GETTERS + - COMPARISON + ============================================================ + GETTERS + --------------------------------------------------------- */ + /** + * Find a node from its contained value. + * + * @param val Value to find. + */ + XTree.prototype.find = function (val) { + if (this.root_ == null) + return null; + var node = this.root_; + while (true) { + var newNode = null; + if (this.is_equal_to(val, node.value)) + break; // EQUALS, MEANS MATCHED, THEN TERMINATE + else if (this.is_less(val, node.value)) + newNode = node.left; // LESS, THEN TO THE LEFT + else + newNode = node.right; // GREATER, THEN TO THE RIGHT + // ULTIL CHILD NODE EXISTS + if (newNode == null) + break; + // SHIFT A NEW NODE TO THE NODE TO BE RETURNED + node = newNode; + } + return node; + }; + /** + * Fetch maximum (the rightes?) node from one. + * + * @param node A node to fetch its maximum node. + * @return The maximum node. + */ + XTree.prototype.fetch_maximum = function (node) { + while (node.right != null) + node = node.right; + return node; + }; + /* ========================================================= + ELEMENTS I/O + - INSERT + - ERASE + - COLOR + - ROTATION + ============================================================ + INSERT + --------------------------------------------------------- */ + /** + *

Insert an element with a new node.

+ * + *

Insertion begins by adding the node as any binary search tree insertion does and by coloring it + * red. Whereas in the binary search tree, we always add a leaf, in the red-black + * tree, leaves contain no information, so instead we add a red interior node, with + * two black leaves, in place of an existing + * black leaf.

+ * + *

What happens next depends on the color of other nearby nodes. The term uncle node will be used to + * refer to the sibling of a node's parent, as in human family trees. Note that:

+ * + *
    + *
  • property 3 (all leaves are black) always holds.
  • + *
  • + * property 4 (both children of every red node are + * black) is threatened only by adding a red + * node, repainting a black node red, or a + * rotation. + *
  • + *
  • + * property 5 (all paths from any given node to its leaf nodes contain the same number of + * black nodes) is threatened only by adding a + * black node, repainting a red node + * black (or vice versa), or a rotation. + *
  • + *
+ * + *

Notes

+ *
    + *
  1. + * The label N will be used to denote the current node (colored + * red). In the diagrams N carries a blue contour. At the + * beginning, this is the new node being inserted, but the entire procedure may also be applied + * recursively to other nodes (see case 3). {@link XTreeNode.parent P} will denote + * N's parent node, {@link XTreeNode.grand_parent G} will denote N's + * grandparent, and {@link XTreeNode.uncle U} will denote N's uncle. In between + * some cases, the roles and labels of the nodes are exchanged, but in each case, every label continues + * to represent the same node it represented at the beginning of the case. + *
  2. + *
  3. + * If a node in the right (target) half of a diagram carries a blue contour it will become the current + * node in the next iteration and there the other nodes will be newly assigned relative to it. Any + * color shown in the diagram is either assumed in its case or implied by those assumptions. + *
  4. + *
  5. + * A numbered triangle represents a subtree of unspecified depth. A black + * circle atop a triangle means that black-height of subtree is greater + * by one compared to subtree without this circle.
  6. + *
+ * + *

There are several cases of red-black tree insertion to handle:

+ * + *
    + *
  • N is the root node, i.e., first node of red-black tree.
  • + *
  • + * N's parent ({@link XTreeNode.parent P}) is black. + *
  • + *
  • + * N's parent ({@link XTreeNode.parent P}) and uncle + * ({@link XTreeNode.uncle U}) are red. + *
  • + *
  • + * N is added to right of left child of grandparent, or N is added to left + * of right child of grandparent ({@link XTreeNode.parent P} is red and + * {@link XTreeNode.uncle U} is black). + *
  • + *
  • + * N is added to left of left child of grandparent, or N is added to right + * of right child of grandparent ({@link XTreeNode.parent P} is red and + * {@link XTreeNode.uncle U} is black). + *
  • + *
+ * + *

Note

+ *

Note that inserting is actually in-place, since all the calls above use tail recursion.

+ * + *

In the algorithm above, all cases are chained in order, except in insert case 3 where it can recurse + * to case 1 back to the grandparent node: this is the only case where an iterative implementation will + * effectively loop. Because the problem of repair is escalated to the next higher level but one, it takes + * maximally h⁄2 iterations to repair the tree (where h is the height of the tree). Because the probability + * for escalation decreases exponentially with each iteration the average insertion cost is constant.

+ * + * @param val An element to insert. + */ + XTree.prototype.insert = function (val) { + var parent = this.find(val); + var node = new base.XTreeNode(val, base.Color.RED); + if (parent == null) + this.root_ = node; + else { + node.parent = parent; + if (this.is_less(node.value, parent.value)) + parent.left = node; + else + parent.right = node; + } + this.insert_case1(node); + }; + /** + *

N is the root node, i.e., first node of red-black tree.

+ * + *

The current node N is at the {@link root_ root} of the tree.

+ * + *

In this case, it is repainted black to satisfy property 2 (the root is + * black). Since this adds one black node to + * every path at once, property 5 (all paths from any given node to its leaf nodes contain the same number + * of black nodes) is not violated.

+ * + * @param N A node to be inserted or swapped. + */ + XTree.prototype.insert_case1 = function (N) { + if (N.parent == null) + N.color = base.Color.BLACK; + else + this.insert_case2(N); + }; + /** + *

N's parent ({@link XTreeNode.parent P}) is black.

+ * + *

The current node's parent {@link XTreeNode.parent P} is black, + * so property 4 (both children of every red node are + * black) is not invalidated.

+ * + *

In this case, the tree is still valid. Property 5 (all paths from any given node to its leaf nodes + * contain the same number of black nodes) is not threatened, because the + * current node N has two black leaf children, but because + * N is red, the paths through each of its children have the same + * number of black nodes as the path through the leaf it replaced, which was + * black, and so this property remains satisfied.

+ * + * @param N A node to be inserted or swapped. + */ + XTree.prototype.insert_case2 = function (N) { + if (this.fetch_color(N.parent) == base.Color.BLACK) + return; + else + this.insert_case3(N); + }; + /** + *

N's parent ({@link XTreeNode.parent P}) and uncle + * ({@link XTreeNode.uncle U}) are red.

+ * + *

If both the parent {@link XTreeNode.parent P} and the uncle {@link XTreeNode.uncle U} + * are red, then both of them can be repainted black + * and the grandparent {@link XTreeNode.grand_parent G} becomes red (to + * maintain property 5 (all paths from any given node to its leaf nodes contain the same number of + * black nodes)).

+ * + *

Now, the current red node N has a + * black parent. Since any path through the parent or uncle must pass through + * the grandparent, the number of black nodes on these paths has not changed. + * + *

However, the grandparent {@link XTreeNode.grand_parent G} may now violate properties 2 (The + * root is black) or 4 (Both children of every red + * node are black) (property 4 possibly being violated since + * {@link XTreeNode.grand_parent G} may have a red parent).

+ * + *

To fix this, the entire procedure is recursively performed on {@link XTreeNode.grand_parent G} + * from case 1. Note that this is a tail-recursive call, so it could be rewritten as a loop; since this is + * the only loop, and any rotations occur after this loop, this proves that a constant number of rotations + * occur.

+ * + *

+ * + * @param N A node to be inserted or swapped. + */ + XTree.prototype.insert_case3 = function (N) { + if (this.fetch_color(N.uncle) == base.Color.RED) { + N.parent.color = base.Color.BLACK; + N.uncle.color = base.Color.BLACK; + N.grand_parent.color = base.Color.RED; + this.insert_case1(N.grand_parent); + } + else { + this.insert_case4(N); + } + }; + /** + *

N is added to right of left child of grandparent, or N is added to left + * of right child of grandparent ({@link XTreeNode.parent P} is red and + * {@link XTreeNode.uncle U} is black).

+ * + *

The parent {@link XTreeNode.parent P} is red but the uncle + * {@link XTreeNode.uncle U} is black; also, the current node + * N is the right child of {@link XTreeNode.parent P}, and + * {@link XTreeNode.parent P} in turn is the left child of its parent + * {@link XTreeNode.grand_parent G}.

+ * + *

In this case, a left rotation on {@link XTreeNode.parent P} that switches the roles of the + * current node N and its parent {@link XTreeNode.parent P} can be performed; then, + * the former parent node {@link XTreeNode.parent P} is dealt with using case 5 + * (relabeling N and {@link XTreeNode.parent P}) because property 4 (both children of + * every red node are black) is still violated.

+ * + *

The rotation causes some paths (those in the sub-tree labelled "1") to pass through the node + * N where they did not before. It also causes some paths (those in the sub-tree labelled "3") + * not to pass through the node {@link XTreeNode.parent P} where they did before. However, both of + * these nodes are red, so property 5 (all paths from any given node to its leaf + * nodes contain the same number of black nodes) is not violated by the + * rotation.

+ * + *

After this case has been completed, property 4 (both children of every red + * node are black) is still violated, but now we can resolve this by + * continuing to case 5.

+ * + *

+ * + * @param N A node to be inserted or swapped. + */ + XTree.prototype.insert_case4 = function (node) { + if (node == node.parent.right && node.parent == node.grand_parent.left) { + this.rotate_left(node.parent); + node = node.left; + } + else if (node == node.parent.left && node.parent == node.grand_parent.right) { + this.rotate_right(node.parent); + node = node.right; + } + this.insert_case5(node); + }; + /** + *

N is added to left of left child of grandparent, or N is added to right + * of right child of grandparent ({@link XTreeNode.parent P} is red and + * {@link XTreeNode.uncle U} is black).

+ * + *

The parent {@link XTreeNode.parent P} is red but the uncle + * {@link XTreeNode.uncle U} is black, the current node N + * is the left child of {@link XTreeNode.parent P}, and {@link XTreeNode.parent P} is the left + * child of its parent {@link XTreeNode.grand_parent G}.

+ * + *

In this case, a right rotation on {@link XTreeNode.grand_parent G} is performed; the result is a + * tree where the former parent {@link XTreeNode.parent P} is now the parent of both the current node + * N and the former grandparent {@link XTreeNode.grand_parent G}.

+ * + *

{@link XTreeNode.grand_parent G} is known to be black, since its + * former child {@link XTreeNode.parent P} could not have been red otherwise + * (without violating property 4). Then, the colors of {@link XTreeNode.parent P} and + * {@link XTreeNode.grand_parent G} are switched, and the resulting tree satisfies property 4 (both + * children of every red node are black). Property 5 + * (all paths from any given node to its leaf nodes contain the same number of + * black nodes) also remains satisfied, since all paths that went through any + * of these three nodes went through {@link XTreeNode.grand_parent G} before, and now they all go + * through {@link XTreeNode.parent P}. In each case, this is the only + * black node of the three.

+ * + *

+ * + * @param N A node to be inserted or swapped. + */ + XTree.prototype.insert_case5 = function (node) { + node.parent.color = base.Color.BLACK; + node.grand_parent.color = base.Color.RED; + if (node == node.parent.left && node.parent == node.grand_parent.left) + this.rotate_right(node.grand_parent); + else + this.rotate_left(node.grand_parent); + }; + /* --------------------------------------------------------- + ERASE + --------------------------------------------------------- */ + /** + *

Erase an element with its node.

+ * + *

In a regular binary search tree when deleting a node with two non-leaf children, we find either the + * maximum element in its left subtree (which is the in-order predecessor) or the minimum element in its + * right subtree (which is the in-order successor) and move its value into the node being deleted (as shown + * here). We then delete the node we copied the value from, which must have fewer than two non-leaf children. + * (Non-leaf children, rather than all children, are specified here because unlike normal binary search + * trees, red-black trees can have leaf nodes anywhere, so that all nodes are either internal nodes with + * two children or leaf nodes with, by definition, zero children. In effect, internal nodes having two leaf + * children in a red-black tree are like the leaf nodes in a regular binary search tree.) Because merely + * copying a value does not violate any red-black properties, this reduces to the problem of deleting a node + * with at most one non-leaf child. Once we have solved that problem, the solution applies equally to the + * case where the node we originally want to delete has at most one non-leaf child as to the case just + * considered where it has two non-leaf children.

+ * + *

Therefore, for the remainder of this discussion we address the deletion of a node with at most one + * non-leaf child. We use the label M to denote the node to be deleted; C will denote a + * selected child of M, which we will also call "its child". If M does have a non-leaf child, + * call that its child, C; otherwise, choose either leaf as its child, C.

+ * + *

If M is a red node, we simply replace it with its child C, + * which must be black by property 4. (This can only occur when M has + * two leaf children, because if the red node M had a + * black non-leaf child on one side but just a leaf child on the other side, + * then the count of black nodes on both sides would be different, thus the + * tree would violate property 5.) All paths through the deleted node will simply pass through one fewer + * red node, and both the deleted node's parent and child must be + * black, so property 3 (all leaves are black) + * and property 4 (both children of every red node are + * black) still hold.

+ * + *

Another simple case is when M is black and C is + * red. Simply removing a black node could break + * Properties 4 (“Both children of every red node are + * black”) and 5 (“All paths from any given node to its leaf nodes contain the + * same number of black nodes”), but if we repaint C + * black, both of these properties are preserved.

+ * + *

The complex case is when both M and C are black. (This + * can only occur when deleting a black node which has two leaf children, + * because if the black node M had a black + * non-leaf child on one side but just a leaf child on the other side, then the count of + * black nodes on both sides would be different, thus the tree would have been + * an invalid red-black tree by violation of property 5.) We begin by replacing M with its child + * C. We will relabel this child C (in its new position) N, and its sibling (its + * new parent's other child) {@link XTreeNode.sibling S}. ({@link XTreeNode.sibling S} was + * previously the sibling of M.)

+ * + *

In the diagrams below, we will also use {@link XTreeNode.parent P} for N's new + * parent (M's old parent), SL for {@link XTreeNode.sibling S}'s left child, and + * SR for {@link XTreeNode.sibling S}'s right child ({@link XTreeNode.sibling S} cannot + * be a leaf because if M and C were black, then + * {@link XTreeNode.parent P}'s one subtree which included M counted two + * black-height and thus {@link XTreeNode.parent P}'s other subtree + * which includes {@link XTreeNode.sibling S} must also count two + * black-height, which cannot be the case if {@link XTreeNode.sibling S} + * is a leaf node).

+ * + *

Notes

+ *
    + *
  1. + * The label N will be used to denote the current node (colored + * black). In the diagrams N carries a blue contour. At the + * beginning, this is the replacement node and a leaf, but the entire procedure may also be applied + * recursively to other nodes (see case 3). In between some cases, the roles and labels of the nodes + * are exchanged, but in each case, every label continues to represent the same node it represented at + * the beginning of the case. + *
  2. + *
  3. + * If a node in the right (target) half of a diagram carries a blue contour it will become the current + * node in the next iteration and there the other nodes will be newly assigned relative to it. Any + * color shown in the diagram is either assumed in its case or implied by those assumptions. + * White represents an arbitrary color (either red or + * black), but the same in both halves of the diagram. + *
  4. + *
  5. + * A numbered triangle represents a subtree of unspecified depth. A black + * circle atop a triangle means that black-height of subtree is greater + * by one compared to subtree without this circle. + *
  6. + *
+ * + *

If both N and its original parent are black, then + * deleting this original parent causes paths which proceed through N to have one fewer + * black node than paths that do not. As this violates property 5 (all paths + * from any given node to its leaf nodes contain the same number of black + * nodes), the tree must be rebalanced. There are several cases to consider:

+ * + *
    + *
  1. N is the new root.
  2. + *
  3. {@link XTreeNode.sibling S} is red.
  4. + *
  5. + * {@link XTreeNode.parent P}, {@link XTreeNode.sibling S}, and + * {@link XTreeNode.sibling S}'s children are black.
  6. + *
  7. + * {@link XTreeNode.sibling S} and {@link XTreeNode.sibling S}'s children are + * black, but {@link XTreeNode.parent P} is + * red. + *
  8. + *
  9. + * {@link XTreeNode.sibling S} is black, + * {@link XTreeNode.sibling S}'s left child is red, + * {@link XTreeNode.sibling S}'s right child is black, and + * N is the left child of its parent. + *
  10. + *
  11. + * {@link XTreeNode.sibling S} is black, + * {@link XTreeNode.sibling S}'s right child is red, and + * N is the left child of its parent {@link XTreeNode.parent P}. + *
  12. + *
+ * + *

Again, the function calls all use tail recursion, so the algorithm is in-place.

+ * + *

In the algorithm above, all cases are chained in order, except in delete case 3 where it can recurse + * to case 1 back to the parent node: this is the only case where an iterative implementation will + * effectively loop. No more than h loops back to case 1 will occur (where h is the height of the tree). + * And because the probability for escalation decreases exponentially with each iteration the average + * removal cost is constant.

+ * + *

Additionally, no tail recursion ever occurs on a child node, so the tail recursion loop can only + * move from a child back to its successive ancestors. If a rotation occurs in case 2 (which is the only + * possibility of rotation within the loop of cases 1–3), then the parent of the node N + * becomes red after the rotation and we will exit the loop. Therefore, at most one + * rotation will occur within this loop. Since no more than two additional rotations will occur after + * exiting the loop, at most three rotations occur in total.

+ * + * @param val An element to erase. + */ + XTree.prototype.erase = function (val) { + var node = this.find(val); + if (node == null || this.is_equal_to(val, node.value) == false) + return; + if (node.left != null && node.right != null) { + var pred = this.fetch_maximum(node.left); + node.value = pred.value; + node = pred; + } + var child = (node.right == null) ? node.left : node.right; + if (this.fetch_color(node) == base.Color.BLACK) { + node.color = this.fetch_color(child); + this.erase_case1(node); + } + this.replace_node(node, child); + }; + /** + *

N is the new root.

+ * + *

In this case, we are done. We removed one black node from every path, + * and the new root is black, so the properties are preserved.

+ * + *

Note

+ *

In cases 2, 5, and 6, we assume N is the left child of its parent + * {@link XTreeNode.parent P}. If it is the right child, left and right should be reversed throughout + * these three cases. Again, the code examples take both cases into account.

+ * + * @param N A node to be erased or swapped. + */ + XTree.prototype.erase_case1 = function (N) { + if (N.parent == null) + return; + else + this.erase_case2(N); + }; + /** + *

{@link XTreeNode.sibling S} is red.

+ * + *

+ * + *

In this case we reverse the colors of {@link XTreeNode.parent P} and + * {@link XTreeNode.sibling S}, and then rotate left at {@link XTreeNode.parent P}, turning + * {@link XTreeNode.sibling S} into N's grandparent.

+ * + *

Note that {@link XTreeNode.parent P} has to be black as it had a + * red child. The resulting subtree has a path short one + * black node so we are not done. Now N has a + * black sibling and a red parent, so we can proceed + * to step 4, 5, or 6. (Its new sibling is black because it was once the child + * of the red {@link XTreeNode.sibling S}.) In later cases, we will re-label + * N's new sibling as {@link XTreeNode.sibling S}.

+ * + * @param N A node to be erased or swapped. + */ + XTree.prototype.erase_case2 = function (N) { + if (this.fetch_color(N.sibling) == base.Color.RED) { + N.parent.color = base.Color.RED; + N.sibling.color = base.Color.BLACK; + if (N == N.parent.left) + this.rotate_left(N.parent); + else + this.rotate_right(N.parent); + } + this.erase_case3(N); + }; + /** + *

{@link XTreeNode.parent P}, {@link XTreeNode.sibling S}, and {@link XTreeNode.sibling + * S}'s children are black.

+ * + *

+ * + *

In this case, we simply repaint {@link XTreeNode.sibling S} red. The + * result is that all paths passing through {@link XTreeNode.sibling S}, which are precisely those + * paths not passing through N, have one less black node. + * Because deleting N's original parent made all paths passing through N have + * one less black node, this evens things up.

+ * + *

However, all paths through {@link XTreeNode.parent P} now have one fewer + * black node than paths that do not pass through + * {@link XTreeNode.parent P}, so property 5 (all paths from any given node to its leaf nodes contain + * the same number of black nodes) is still violated.

+ * + *

To correct this, we perform the rebalancing procedure on {@link XTreeNode.parent P}, starting + * at case 1.

+ * + * @param N A node to be erased or swapped. + */ + XTree.prototype.erase_case3 = function (N) { + if (this.fetch_color(N.parent) == base.Color.BLACK && + this.fetch_color(N.sibling) == base.Color.BLACK && + this.fetch_color(N.sibling.left) == base.Color.BLACK && + this.fetch_color(N.sibling.right) == base.Color.BLACK) { + N.sibling.color = base.Color.RED; + this.erase_case1(N.parent); + } + else + this.erase_case4(N); + }; + /** + *

{@link XTreeNode.sibling S} and {@link XTreeNode.sibling S}'s children are + * black, but {@link XTreeNode.parent P} is red.

+ * + *

+ * + *

In this case, we simply exchange the colors of {@link XTreeNode.sibling S} and + * {@link XTreeNode.parent P}. This does not affect the number of black + * nodes on paths going through {@link XTreeNode.sibling S}, but it does add one to the number of + * black nodes on paths going through N, making up for the + * deleted black node on those paths.

+ * + * @param N A node to be erased or swapped. + */ + XTree.prototype.erase_case4 = function (N) { + if (this.fetch_color(N.parent) == base.Color.RED && + N.sibling != null && + this.fetch_color(N.sibling) == base.Color.BLACK && + this.fetch_color(N.sibling.left) == base.Color.BLACK && + this.fetch_color(N.sibling.right) == base.Color.BLACK) { + N.sibling.color = base.Color.RED; + N.parent.color = base.Color.BLACK; + } + else + this.erase_case5(N); + }; + /** + *

{@link XTreeNode.sibling S} is black, {@link XTreeNode.sibling S}'s + * left child is red, {@link XTreeNode.sibling S}'s right child is + * black, and N is the left child of its parent.

+ * + *

+ * + *

In this case we rotate right at {@link XTreeNode.sibling S}, so that + * {@link XTreeNode.sibling S}'s left child becomes {@link XTreeNode.sibling S}'s parent and + * N's new sibling. We then exchange the colors of {@link XTreeNode.sibling S} and its + * new parent.

+ * + *

All paths still have the same number of black nodes, but now + * N has a black sibling whose right child is + * red, so we fall into case 6. Neither N nor its parent are affected + * by this transformation. (Again, for case 6, we relabel N's new sibling as + * {@link XTreeNode.sibling S}.)

+ * + * @param N A node to be erased or swapped. + */ + XTree.prototype.erase_case5 = function (N) { + if (N == N.parent.left && + N.sibling != null && + this.fetch_color(N.sibling) == base.Color.BLACK && + this.fetch_color(N.sibling.left) == base.Color.RED && + this.fetch_color(N.sibling.right) == base.Color.BLACK) { + N.sibling.color = base.Color.RED; + N.sibling.left.color = base.Color.BLACK; + this.rotate_right(N.sibling); + } + else if (N == N.parent.right && + N.sibling != null && + this.fetch_color(N.sibling) == base.Color.BLACK && + this.fetch_color(N.sibling.left) == base.Color.BLACK && + this.fetch_color(N.sibling.right) == base.Color.RED) { + N.sibling.color = base.Color.RED; + N.sibling.right.color = base.Color.BLACK; + this.rotate_left(N.sibling); + } + }; + /** + *

{@link XTreeNode.sibling S} is black, + * {@link XTreeNode.sibling S}'s right child is red, and N is + * the left child of its parent {@link XTreeNode.parent P}.

+ * + *

In this case we rotate left at {@link XTreeNode.parent P}, so that + * {@link XTreeNode.sibling S} becomes the parent of {@link XTreeNode.parent P} and + * {@link XTreeNode.sibling S}'s right child. We then exchange the colors of + * {@link XTreeNode.parent P} and {@link XTreeNode.sibling S}, and make + * {@link XTreeNode.sibling S}'s right child black.

+ * + *

The subtree still has the same color at its root, so Properties 4 (Both children of every + * red node are black) and 5 (All paths from any + * given node to its leaf nodes contain the same number of black nodes) are + * not violated. However, N now has one additional black + * ancestor: either {@link XTreeNode.parent P} has become black, or it + * was black and {@link XTreeNode.sibling S} was added as a + * black grandparent.

+ * + *

Thus, the paths passing through N pass through one additional + * black node.

+ * + *

+ * + *

Meanwhile, if a path does not go through N, then there are two possibilities:

+ *
    + *
  1. + * It goes through N's new sibling SL, a node with arbitrary color and the root of + * the subtree labeled 3 (s. diagram). Then, it must go through {@link XTreeNode.sibling S} and + * {@link XTreeNode.parent P}, both formerly and currently, as they have only exchanged colors + * and places. Thus the path contains the same number of black nodes. + *
  2. + *
  3. + * It goes through N's new uncle, {@link XTreeNode.sibling S}'s right child. Then, + * it formerly went through {@link XTreeNode.sibling S}, {@link XTreeNode.sibling S}'s + * parent, and {@link XTreeNode.sibling S}'s right child SR (which was + * red), but now only goes through {@link XTreeNode.sibling S}, which + * has assumed the color of its former parent, and {@link XTreeNode.sibling S}'s right child, + * which has changed from red to black (assuming + * {@link XTreeNode.sibling S}'s color: black). The net effect is + * that this path goes through the same number of black nodes. + *
  4. + *
+ * + *

Either way, the number of black nodes on these paths does not change. + * Thus, we have restored Properties 4 (Both children of every red node are + * black) and 5 (All paths from any given node to its leaf nodes contain the + * same number of black nodes). The white node in the diagram can be either + * red or black, but must refer to the same color + * both before and after the transformation.

+ * + * @param N A node to be erased or swapped. + */ + XTree.prototype.erase_case6 = function (node) { + node.sibling.color = this.fetch_color(node.parent); + node.parent.color = base.Color.BLACK; + if (node == node.parent.left) { + node.sibling.right.color = base.Color.BLACK; + this.rotate_left(node.parent); + } + else { + node.sibling.left.color = base.Color.BLACK; + this.rotate_right(node.parent); + } + }; + /* --------------------------------------------------------- + ROTATION + --------------------------------------------------------- */ + /** + * Rotate a node left. + * + * @param node Node to rotate left. + */ + XTree.prototype.rotate_left = function (node) { + var right = node.right; + this.replace_node(node, right); + node.right = right.left; + if (right.left != null) + right.left.parent = node; + right.left = node; + node.parent = right; + }; + /** + * Rotate a node to right. + * + * @param node A node to rotate right. + */ + XTree.prototype.rotate_right = function (node) { + var left = node.left; + this.replace_node(node, left); + node.left = left.right; + if (left.right != null) + left.right.parent = node; + left.right = node; + node.parent = left; + }; + /** + * Replace a node. + * + * @param oldNode Ordinary node to be replaced. + * @param newNode Target node to replace. + */ + XTree.prototype.replace_node = function (oldNode, newNode) { + if (oldNode.parent == null) + this.root_ = newNode; + else { + if (oldNode == oldNode.parent.left) + oldNode.parent.left = newNode; + else + oldNode.parent.right = newNode; + } + if (newNode != null) + newNode.parent = oldNode.parent; + }; + /* --------------------------------------------------------- + COLOR + --------------------------------------------------------- */ + /** + * Fetch color from a node. + * + * @param node A node to fetch color. + * @retur color. + */ + XTree.prototype.fetch_color = function (node) { + if (node == null) + return base.Color.BLACK; + else + return node.color; + }; + return XTree; + }()); + base.XTree = XTree; + })(base = std.base || (std.base = {})); })(std || (std = {})); -/// +/// +/// var std; (function (std) { - /** - *

Running on Node.

- * - *

Test whether the JavaScript is running on Node.

- * - * @references http://stackoverflow.com/questions/17575790/environment-detection-node-js-or-browser - */ - function is_node() { - if (typeof process === "object") - if (typeof process.versions === "object") - if (typeof process.versions.node !== "undefined") - return true; - return false; - } - std.is_node = is_node; - /** - *

Pair of values.

- * - *

This class couples together a pair of values, which may be of different types (T1 and - * T2). The individual values can be accessed through its public members {@link first} and - * {@link second}.

- * - * @param Type of member {@link first}. - * @param Type of member {@link second}. - * - * @reference http://www.cplusplus.com/reference/utility/pair - * @author Jeongho Nam - */ - var Pair = (function () { - /* --------------------------------------------------------- - CONSTRUCTORS - --------------------------------------------------------- */ + var base; + (function (base) { /** - *

Construct from pair values.

+ *

A red-black tree storing {@link MapIterator MapIterators}.

* - * @param first The first value of the Pair - * @param second The second value of the Pair + *

+ *

+ * + * @author Jeongho Nam */ - function Pair(first, second) { - this.first = first; - this.second = second; - } - /* --------------------------------------------------------- - COMPARISON - --------------------------------------------------------- */ + var PairTree = (function (_super) { + __extends(PairTree, _super); + /* --------------------------------------------------------- + CONSTRUCTOR + --------------------------------------------------------- */ + /** + * Default Constructor. + */ + function PairTree(map, compare) { + if (compare === void 0) { compare = std.less; } + _super.call(this); + this.map_ = map; + this.compare_ = compare; + } + PairTree.prototype.find = function (val) { + if (val instanceof std.MapIterator && val.first instanceof std.SetIterator == false) + return _super.prototype.find.call(this, val); + else + return this.find_by_key(val); + }; + /** + * @hidden + */ + PairTree.prototype.find_by_key = function (key) { + if (this.root_ == null) + return null; + var node = this.root_; + while (true) { + var newNode = null; + if (std.equal_to(key, node.value.first)) + break; // EQUALS, MEANS MATCHED, THEN TERMINATE + else if (this.compare_(key, node.value.first)) + newNode = node.left; // LESS, THEN TO THE LEFT + else + newNode = node.right; // GREATER, THEN TO THE RIGHT + // ULTIL CHILD NODE EXISTS + if (newNode == null) + break; + // SHIFT A NEW NODE TO THE NODE TO BE RETURNED + node = newNode; + } + return node; + }; + /* --------------------------------------------------------- + BOUNDS + --------------------------------------------------------- */ + /** + *

Return iterator to lower bound.

+ * + *

Returns an iterator pointing to the first element in the container whose key is not considered to + * go before k (i.e., either it is equivalent or goes after).

+ * + *

The function uses its internal comparison object (key_comp) to determine this, returning an + * iterator to the first element for which key_comp(k, element_key) would return false.

+ * + *

If the {@link ITreeMap} class is instantiated with the default comparison type ({@link less}), + * the function returns an iterator to the first element whose key is not less than k

. + * + *

A similar member function, {@link upper_bound}, has the same behavior as {@link lower_bound}, except + * in the case that the {@link ITreeMap} contains an element with a key equivalent to k: In this + * case, {@link lower_bound} returns an iterator pointing to that element, whereas {@link upper_bound} + * returns an iterator pointing to the next element.

+ * + * @param k Key to search for. + * + * @return An iterator to the the first element in the container whose key is not considered to go before + * k, or {@link ITreeMap.end} if all keys are considered to go before k. + */ + PairTree.prototype.lower_bound = function (key) { + var node = this.find(key); + if (node == null) + return this.map_.end(); + else if (this.compare_(node.value.first, key)) + return node.value.next(); + else { + var it = node.value; + while (!std.equal_to(it, this.map_.end()) && this.compare_(it.first, key)) + it = it.next(); + return it; + } + }; + /** + *

Return iterator to upper bound.

+ * + *

Returns an iterator pointing to the first element in the container whose key is considered to + * go after k

. + * + *

The function uses its internal comparison object (key_comp) to determine this, returning an + * iterator to the first element for which key_comp(k, element_key) would return true.

+ * + *

If the {@link ITreeMap} class is instantiated with the default comparison type ({@link less}), + * the function returns an iterator to the first element whose key is greater than k

. + * + *

A similar member function, {@link lower_bound}, has the same behavior as {@link upper_bound}, except + * in the case that the map contains an element with a key equivalent to k: In this case + * {@link lower_bound} returns an iterator pointing to that element, whereas {@link upper_bound} returns an + * iterator pointing to the next element.

+ * + * @param k Key to search for. + * + * @return An iterator to the the first element in the container whose key is considered to go after + * k, or {@link TreeMap.end end} if no keys are considered to go after k. + */ + PairTree.prototype.upper_bound = function (key) { + var node = this.find(key); + if (node == null) + return this.map_.end(); + else { + var it = node.value; + while (!std.equal_to(it, this.map_.end()) && (std.equal_to(it.first, key) || this.compare_(it.first, key))) + it = it.next(); + return it; + } + }; + /** + *

Get range of equal elements.

+ * + *

Returns the bounds of a range that includes all the elements in the container which have a key + * equivalent to k

. + * + *

If no matches are found, the range returned has a length of zero, with both iterators pointing to + * the first element that has a key considered to go after k according to the container's internal + * comparison object (key_comp).

+ * + *

Two keys are considered equivalent if the container's comparison object returns false reflexively + * (i.e., no matter the order in which the keys are passed as arguments).

+ * + * @param k Key to search for. + * + * @return The function returns a {@link Pair}, whose member {@link Pair.first} is the lower bound of + * the range (the same as {@link lower_bound}), and {@link Pair.second} is the upper bound + * (the same as {@link upper_bound}). + */ + PairTree.prototype.equal_range = function (key) { + return std.make_pair(this.lower_bound(key), this.upper_bound(key)); + }; + /* --------------------------------------------------------- + COMPARISON + --------------------------------------------------------- */ + /** + *

Return key comparison function.

+ * + *

Returns a references of the comparison function used by the container to compare keys.

+ * + *

The comparison object of a {@link ITreeMap tree-map object} is set on + * {@link TreeMap.constructor construction}. Its type (Key) is the last parameter of the + * {@link ITreeMap.constructor constructors}. By default, this is a {@link less} function, which returns the same + * as operator<.

+ * + *

This function determines the order of the elements in the container: it is a function pointer that takes + * two arguments of the same type as the element keys, and returns true if the first argument + * is considered to go before the second in the strict weak ordering it defines, and false otherwise. + *

+ * + *

Two keys are considered equivalent if {@link key_comp} returns false reflexively (i.e., no + * matter the order in which the keys are passed as arguments).

+ * + * @return The comparison function. + */ + PairTree.prototype.key_comp = function () { + return this.compare_; + }; + /** + *

Return value comparison function.

+ * + *

Returns a comparison function that can be used to compare two elements to get whether the key of the first + * one goes before the second.

+ * + *

The arguments taken by this function object are of member type std.Pair (defined in + * {@link ITreeMap}), but the mapped type (T) part of the value is not taken into consideration in this + * comparison.

+ * + *

This comparison class returns true if the {@link Pair.first key} of the first argument + * is considered to go before that of the second (according to the strict weak ordering specified by the + * container's comparison function, {@link key_comp}), and false otherwise.

+ * + * @return The comparison function for element values. + */ + PairTree.prototype.value_comp = function () { + var compare = this.compare_; + var fn = function (x, y) { + return compare(x.first, y.first); + }; + return fn; + }; + /** + * @inheritdoc + */ + PairTree.prototype.is_equal_to = function (left, right) { + return std.equal_to(left.first, right.first); + }; + /** + * @inheritdoc + */ + PairTree.prototype.is_less = function (left, right) { + return this.compare_(left.first, right.first); + }; + return PairTree; + }(base.XTree)); + base.PairTree = PairTree; + })(base = std.base || (std.base = {})); +})(std || (std = {})); +/// +/// +var std; +(function (std) { + var base; + (function (base) { /** - *

Whether a Pair is equal with the Pair.

- *

Compare each first and second value of two Pair(s) and returns whether they are equal or not.

+ *

A red-black Tree storing {@link SetIterator SetIterators}.

* - *

If stored key and value in a Pair are not number or string but an object like a class or struct, - * the comparison will be executed by a member method (SomeObject)::equal_to(). If the object does not have - * the member method equal_to(), only address of pointer will be compared.

+ *

+ *

* - * @param obj A Map to compare - * @return Indicates whether equal or not. + * @author Jeongho Nam */ - Pair.prototype.equal_to = function (pair) { - return std.equal_to(this.first, pair.first) && std.equal_to(this.second, pair.second); - }; - Pair.prototype.less = function (pair) { - if (std.equal_to(this.first, pair.first) == false) - return std.less(this.first, pair.first); - else - return std.less(this.second, pair.second); - }; - return Pair; - }()); - std.Pair = Pair; - /** - *

Construct {@link Pair} object.

- * - *

Constructs a {@link Pair} object with its {@link Pair.first first} element set to x and its - * {@link Pair.second second} element set to y.

- * - *

The template types can be implicitly deduced from the arguments passed to {@link make_pair}.

- * - *

{@link Pair} objects can be constructed from other {@link Pair} objects containing different types, if the - * respective types are implicitly convertible.

- * - * @param x Value for member {@link Pair.first first}. - * @param y Value for member {@link Pair.second second}. - * - * @return A {@link Pair} object whose elements {@link Pair.first first} and {@link Pair.second second} are set to - * x and y respectivelly. - */ - function make_pair(x, y) { - return new Pair(x, y); - } - std.make_pair = make_pair; + var AtomicTree = (function (_super) { + __extends(AtomicTree, _super); + /* --------------------------------------------------------- + CONSTRUCTOR + --------------------------------------------------------- */ + /** + * Default Constructor. + */ + function AtomicTree(set, compare) { + if (compare === void 0) { compare = std.less; } + _super.call(this); + this.set_ = set; + this.compare_ = compare; + } + AtomicTree.prototype.find = function (val) { + if (val instanceof std.SetIterator && val.value instanceof std.SetIterator == false) + return _super.prototype.find.call(this, val); + else + return this.find_by_val(val); + }; + /** + * @hidden + */ + AtomicTree.prototype.find_by_val = function (val) { + if (this.root_ == null) + return null; + var node = this.root_; + while (true) { + var newNode = null; + if (std.equal_to(val, node.value.value)) + break; // EQUALS, MEANS MATCHED, THEN TERMINATE + else if (this.compare_(val, node.value.value)) + newNode = node.left; // LESS, THEN TO THE LEFT + else + newNode = node.right; // GREATER, THEN TO THE RIGHT + // ULTIL CHILD NODE EXISTS + if (newNode == null) + break; + // SHIFT A NEW NODE TO THE NODE TO BE RETURNED + node = newNode; + } + return node; + }; + /* --------------------------------------------------------- + BOUNDS + --------------------------------------------------------- */ + /** + *

Return iterator to lower bound.

+ * + *

Returns an iterator pointing to the first element in the container which is not considered to + * go before val (i.e., either it is equivalent or goes after).

+ * + *

The function uses its internal comparison object (key_comp) to determine this, returning an + * iterator to the first element for which key_comp(element,val) would return false.

+ * + *

If the {@link ITreeSet} class is instantiated with the default comparison type ({@link less}), + * the function returns an iterator to the first element that is not less than val.

+ + *

A similar member function, {@link upper_bound}, has the same behavior as {@link lower_bound}, except + * in the case that the {@link ITreeSet} contains elements equivalent to val: In this case + * {@link lower_bound} returns an iterator pointing to the first of such elements, whereas + * {@link upper_bound} returns an iterator pointing to the element following the last.

+ * + * @param val Value to compare. + * + * @return An iterator to the the first element in the container which is not considered to go before + * val, or {@link ITreeSet.end} if all elements are considered to go before val. + */ + AtomicTree.prototype.lower_bound = function (val) { + var node = this.find(val); + if (node == null) + return this.set_.end(); + else if (std.equal_to(node.value.value, val)) + return node.value; + else { + var it = node.value; + while (!std.equal_to(it, this.set_.end()) && this.compare_(it.value, val)) + it = it.next(); + return it; + } + }; + /** + *

Return iterator to upper bound.

+ * + *

Returns an iterator pointing to the first element in the container which is considered to go after + * val.

+ + *

The function uses its internal comparison object (key_comp) to determine this, returning an + * iterator to the first element for which key_comp(val,element) would return true.

+ + *

If the {@code ITreeSet} class is instantiated with the default comparison type (less), the + * function returns an iterator to the first element that is greater than val.

+ * + *

A similar member function, {@link lower_bound}, has the same behavior as {@link upper_bound}, except + * in the case that the {@ITreeSet} contains elements equivalent to val: In this case + * {@link lower_bound} returns an iterator pointing to the first of such elements, whereas + * {@link upper_bound} returns an iterator pointing to the element following the last.

+ * + * @param val Value to compare. + * + * @return An iterator to the the first element in the container which is considered to go after + * val, or {@link TreeSet.end end} if no elements are considered to go after val. + */ + AtomicTree.prototype.upper_bound = function (val) { + var node = this.find(val); + if (node == null) + return this.set_.end(); + else { + var it = node.value; + while (!std.equal_to(it, this.set_.end()) && (std.equal_to(it.value, val) || this.compare_(it.value, val))) + it = it.next(); + return it; + } + }; + /** + *

Get range of equal elements.

+ * + *

Returns the bounds of a range that includes all the elements in the container that are equivalent + * to val.

+ * + *

If no matches are found, the range returned has a length of zero, with both iterators pointing to + * the first element that is considered to go after val according to the container's + * internal comparison object (key_comp).

+ * + *

Two elements of a multiset are considered equivalent if the container's comparison object returns + * false reflexively (i.e., no matter the order in which the elements are passed as arguments).

+ * + * @param key Value to search for. + * + * @return The function returns a {@link Pair}, whose member {@link Pair.first} is the lower bound of + * the range (the same as {@link lower_bound}), and {@link Pair.second} is the upper bound + * (the same as {@link upper_bound}). + */ + AtomicTree.prototype.equal_range = function (val) { + return std.make_pair(this.lower_bound(val), this.upper_bound(val)); + }; + /* --------------------------------------------------------- + COMPARISON + --------------------------------------------------------- */ + /** + *

Return comparison function.

+ * + *

Returns a copy of the comparison function used by the container.

+ * + *

By default, this is a {@link less} object, which returns the same as operator<.

+ * + *

This object determines the order of the elements in the container: it is a function pointer or a function + * object that takes two arguments of the same type as the container elements, and returns true if + * the first argument is considered to go before the second in the strict weak ordering it + * defines, and false otherwise.

+ * + *

Two elements of a {@link ITreeSet} are considered equivalent if {@link key_comp} returns false + * reflexively (i.e., no matter the order in which the elements are passed as arguments).

+ * + *

In {@link ITreeSet} containers, the keys to sort the elements are the values (T) themselves, + * therefore {@link key_comp} and its sibling member function {@link value_comp} are equivalent.

+ * + * @return The comparison function. + */ + AtomicTree.prototype.key_comp = function () { + return this.compare_; + }; + /** + *

Return comparison function.

+ * + *

Returns a copy of the comparison function used by the container.

+ * + *

By default, this is a {@link less} object, which returns the same as operator<.

+ * + *

This object determines the order of the elements in the container: it is a function pointer or a function + * object that takes two arguments of the same type as the container elements, and returns true if + * the first argument is considered to go before the second in the strict weak ordering it + * defines, and false otherwise.

+ * + *

Two elements of a {@link ITreeSet} are considered equivalent if {@link key_comp} returns false + * reflexively (i.e., no matter the order in which the elements are passed as arguments).

+ * + *

In {@link ITreeSet} containers, the keys to sort the elements are the values (T) themselves, + * therefore {@link key_comp} and its sibling member function {@link value_comp} are equivalent.

+ * + * @return The comparison function. + */ + AtomicTree.prototype.value_comp = function () { + return this.compare_; + }; + /** + * @inheritdoc + */ + AtomicTree.prototype.is_equal_to = function (left, right) { + return std.equal_to(left, right); + }; + /** + * @inheritdoc + */ + AtomicTree.prototype.is_less = function (left, right) { + return this.compare_(left.value, right.value); + }; + return AtomicTree; + }(base.XTree)); + base.AtomicTree = AtomicTree; + })(base = std.base || (std.base = {})); +})(std || (std = {})); +/// +var std; +(function (std) { + var base; + (function (base) { + /** + *

A node in an XTree.

+ * + * @param Type of elements. + * + * @inventor Rudolf Bayer + * @author Migrated by Jeongho Nam + */ + var XTreeNode = (function () { + /* --------------------------------------------------------- + CONSTRUCTORS + --------------------------------------------------------- */ + /** + * Construct from value and color of node. + * + * @param value Value to be stored in. + * @param color Color of the node, red or black. + */ + function XTreeNode(value, color) { + this.value = value; + this.color = color; + this.parent = null; + this.left = null; + this.right = null; + } + Object.defineProperty(XTreeNode.prototype, "grand_parent", { + /** + * Get grand-parent. + */ + get: function () { + return this.parent.parent; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(XTreeNode.prototype, "sibling", { + /** + * Get sibling, opposite side node in same parent. + */ + get: function () { + if (this == this.parent.left) + return this.parent.right; + else + return this.parent.left; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(XTreeNode.prototype, "uncle", { + /** + * Get uncle, parent's sibling. + */ + get: function () { + return this.parent.sibling; + }, + enumerable: true, + configurable: true + }); + return XTreeNode; + }()); + base.XTreeNode = XTreeNode; + })(base = std.base || (std.base = {})); })(std || (std = {})); /// /// @@ -10733,180 +10910,3 @@ try { module.exports = std; } catch (exception) { } -/// -var std; -(function (std) { - /** - *

Priority queue.

- * - *

{@link PriorityQueue Priority queues} are a type of container adaptors, specifically designed such that its - * first element is always the greatest of the elements it contains, according to some strict weak ordering - * criterion.

- * - *

This context is similar to a heap, where elements can be inserted at any moment, and only the - * max heap element can be retrieved (the one at the top in the {@link PriorityQueue priority queue}).

- * - *

{@link PriorityQueue Priority queues} are implemented as container adaptors, which are classes that - * use an encapsulated object of a specific container class as its {@link container_ underlying container}, - * providing a specific set of member functions to access its elements. Elements are popped from the "back" - * of the specific container, which is known as the top of the {@link PriorityQueue Priority queue}.

- * - *

The {@link container_ underlying container} may be any of the standard container class templates or some - * other specifically designed container class. The container shall be accessible through - * {@link IArrayIterator random access iterators} and support the following operations:

- * - *
    - *
  • empty()
  • - *
  • size()
  • - *
  • front()
  • - *
  • push_back()
  • - *
  • pop_back()
  • - *
- * - *

The standard container classes {@link Vector} and {@link Deque} fulfill these requirements. By default, if - * no container class is specified for a particular {@link PriorityQueue} class instantiation, the standard - * container {@link Vector} is used.

- * - *

Support of {@link IArrayIterator random access iterators} is required to keep a heap structure internally - * at all times. This is done automatically by the container adaptor by automatically calling the algorithm - * functions make_heap, push_heap and pop_heap when needed.

- * - * @param Type of the elements. - * - * @reference http://www.cplusplus.com/reference/queue/priority_queue/ - * @author Jeongho Nam - */ - var PriorityQueue = (function () { - function PriorityQueue() { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i - 0] = arguments[_i]; - } - // INIT MEMBER - this.container_ = new std.TreeMultiSet(); - if (args.length >= 1 && args[0] instanceof std.base.Container) { - // COPY CONSTRUCTOR - var container = args[0]; // PARAMETER - if (args.length == 2) - this.container_["tree_"]["compare_"] = (args[1]); - this.container_.assign(container.begin(), container.end()); - } - else if (args.length >= 1 && args[0] instanceof Array) { - // INITIALIZER LIST CONSTRUCTOR - var items = args[0]; // PARAMETER - if (args.length == 2) - this.container_["tree_"]["compare_"] = (args[1]); - (_a = this.container_).push.apply(_a, items); - } - else if (args.length >= 2 && args[0] instanceof std.Iterator && args[1] instanceof std.Iterator) { - // RANGE CONSTRUCTOR - var first = args[0]; // PARAMETER 1 - var last = args[1]; // PARAMETER 2 - if (args.length == 2) - this.container_["tree_"]["compare_"] = (args[2]); - this.container_.assign(first, last); - } - else if (args.length == 1) { - // DEFAULT CONSTRUCTOR WITH SPECIFIED COMPARISON FUNCTION - this.container_["tree_"]["compare_"] = (args[0]); - } - var _a; - } - /* --------------------------------------------------------- - ACCESSORS - --------------------------------------------------------- */ - /** - *

Return size.

- * - *

Returns the number of elements in the {@link PriorityQueue}.

- * - *

This member function effectively calls member {@link IArray.size size} of the - * {@link container_ underlying container} object.

- * - * @return The number of elements in the underlying - */ - PriorityQueue.prototype.size = function () { - return this.container_.size(); - }; - /** - *

Test whether container is empty.

- * - *

Returns whether the {@link PriorityQueue} is empty: i.e. whether its {@link size} is zero.

- * - *

This member function effectively calls member {@link IARray.empty empty} of the - * {@link container_ underlying container} object.

- */ - PriorityQueue.prototype.empty = function () { - return this.container_.empty(); - }; - /* --------------------------------------------------------- - ELEMENTS I/O - --------------------------------------------------------- */ - /** - *

Access top element.

- * - *

Returns a constant reference to the top element in the {@link PriorityQueue}.

- * - *

The top element is the element that compares higher in the {@link PriorityQueue}, and the next that is - * removed from the container when {@link PriorityQueue.pop} is called.

- * - *

This member function effectively calls member {@link IArray.front front} of the - * {@link container_ underlying container} object.

- * - * @return A reference to the top element in the {@link PriorityQueue}. - */ - PriorityQueue.prototype.top = function () { - return this.container_.begin().value; - }; - /** - *

Insert element.

- * - *

Inserts a new element in the {@link PriorityQueue}. The content of this new element is initialized to - * val. - * - *

This member function effectively calls the member function {@link IArray.push_back push_back} of the - * {@link container_ underlying container} object, and then reorders it to its location in the heap by calling - * the push_heap algorithm on the range that includes all the elements of the

- * - * @param val Value to which the inserted element is initialized. - */ - PriorityQueue.prototype.push = function (val) { - this.container_.insert(val); - }; - /** - *

Remove top element.

- * - *

Removes the element on top of the {@link PriorityQueue}, effectively reducing its {@link size} by one. - * The element removed is the one with the highest (or lowest) value.

- * - *

The value of this element can be retrieved before being popped by calling member - * {@link PriorityQueue.top}.

- * - *

This member function effectively calls the pop_heap algorithm to keep the heap property of - * {@link PriorityQueue PriorityQueues} and then calls the member function {@link IArray.pop_back pop_back} of - * the {@link container_ underlying container} object to remove the element.

- */ - PriorityQueue.prototype.pop = function () { - this.container_.erase(this.container_.begin()); - }; - /** - *

Swap contents.

- * - *

Exchanges the contents of the container adaptor by those of obj, swapping both the - * {@link container_ underlying container} value and their comparison function using the corresponding - * {@link std.swap swap} non-member functions (unqualified).

- * - *

This member function has a noexcept specifier that matches the combined noexcept of the - * {@link IArray.swap swap} operations on the {@link container_ underlying container} and the comparison - * functions.

- * - * @param obj {@link PriorityQueue} container adaptor of the same type (i.e., instantiated with the same - * template parameters, T). Sizes may differ. - */ - PriorityQueue.prototype.swap = function (obj) { - this.container_.swap(obj.container_); - }; - return PriorityQueue; - }()); - std.PriorityQueue = PriorityQueue; -})(std || (std = {})); diff --git a/lib/typescript-stl.min.js b/lib/typescript-stl.min.js index d435e08c..773c46bf 100644 --- a/lib/typescript-stl.min.js +++ b/lib/typescript-stl.min.js @@ -1,3 +1,3 @@ -var __extends=this&&this.__extends||function(t,e){function r(){this.constructor=t}for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n]);t.prototype=null===e?Object.create(e):(r.prototype=e.prototype,new r)},std;!function(t){t.vector=t.Vector,t.list=t.List,t.deque=t.Deque,t.stack=t.Stack,t.queue=t.Queue,t.priority_queue=t.PriorityQueue,t.set=t.TreeSet,t.multiset=t.TreeMultiSet,t.unordered_set=t.HashSet,t.unordered_multiset=t.HashMultiSet,t.map=t.TreeMap,t.multimap=t.TreeMultiMap,t.unordered_map=t.HashMap,t.unordered_multimap=t.HashMultiMap,t.exception=t.Exception,t.logic_error=t.LogicError,t.domain_error=t.DomainError,t.invalid_argument=t.InvalidArgument,t.length_error=t.LengthError,t.out_of_range=t.OutOfRange,t.runtime_error=t.RuntimeError,t.overflow_error=t.OverflowError,t.underflow_error=t.UnderflowError,t.range_error=t.RangeError,t.system_error=t.SystemError,t.error_category=t.ErrorCategory,t.error_condition=t.ErrorCondition,t.error_code=t.ErrorCode}(std||(std={}));var std;!function(t){function e(t,e,r){for(var n=t;!n.equal_to(e);n=n.next())r(n.value);return r}function r(t,e,r){for(var n=0;nu?t.copy(_.begin(),_.begin().advance(u),i):t.copy(_.begin(),_.end(),i)}function i(e,r,n){if(void 0===n&&(n=t.equal_to),e.equal_to(r))return!0;for(var i=e.next();!i.equal_to(r);i=i.next()){if(t.less(i.value,e.value))return!1;e=e.next()}return!0}function o(e,r,n){if(void 0===n&&(n=t.equal_to),e.equal_to(r))return e;for(var i=e.next();!i.equal_to(r);i=i.next()){if(t.less(i.value,e.value))return i;e=e.next()}return r}function s(t,e,r,n){if(r==-2&&(r=t.size()-1),!(e>=r)){var i=a(t,e,r,n);s(t,e,i-1,n),s(t,i+1,r,n)}}function a(t,e,r,n){for(var i=t.at(e),o=e,s=r+1;;){for(;n(t.at(++o),i)&&o!=r;);for(;n(i,t.at(--s))&&s!=e;);if(o>=s)break;var a=t.at(o);t.set(o,t.at(s)),t.set(s,a)}var u=t.at(e);return t.set(e,t.at(s)),t.set(s,u),s}function u(t,e,r,n,i){n==-1&&(n=t.size());for(var o=e;o0;){var s=Math.floor(o/2),a=e.advance(s);i(a.value,n)?o=s:(e=a.next(),o-=s+1)}return e}function r(e,r,n,i){void 0===i&&(i=t.less);for(var o=t.distance(e,r);o>0;){var s=Math.floor(o/2),a=e.advance(s);i(n,a.value)?o=s:(e=a.next(),o-=s+1)}return e}function n(n,i,o,s){void 0===s&&(s=t.less);var a=e(n,i,o,s);return t.make_pair(a,r(a,i,o,s))}function i(r,n,i,o){return void 0===o&&(o=t.less),r=e(r,n,i,o),!r.equal_to(n)&&!o(i,r.value)}t.lower_bound=e,t.upper_bound=r,t.equal_range=n,t.binary_search=i}(std||(std={}));var std;!function(t){function e(t,e,r){for(;!t.equal_to(e)&&r(t.value);)t=t.next();for(;!t.equal_to(e);t=t.next())if(r(t.value))return!1;return!0}function r(t,e,r){for(;!t.equal_to(e);){for(;r(t.value);)if(t=t.next(),t.equal_to(e))return t;do if(e=e.prev(),t.equal_to(e))return t;while(!r(e.value));t.swap(e),t=t.next()}return e}function n(t,e,n){return r(t,e,n)}function i(e,r,n,i,o){for(;!e.equal_to(r);e=e.next())o(e.value)?(n.value=e.value,n=n.next()):(i.value=e.value,i=i.next());return t.make_pair(n,i)}function o(e,r,n){for(var i=t.distance(e,r);i>0;){var o=Math.floor(i/2),s=e.advance(o);n(s.value)?(e=s.next(),i-=o+1):i=o}return e}t.is_partitioned=e,t.partition=r,t.stable_partition=n,t.partition_copy=i,t.partition_point=o}(std||(std={}));var std;!function(t){function e(e,r,n,i,o,s){for(void 0===s&&(s=t.less);;){if(e.equal_to(r))return t.copy(n,i,o);if(n.equal_to(i))return t.copy(e,r,o);s(e.value,n.value)?(o.value=e.value,e=e.next()):(o.value=n.value,n=n.next()),o=o.next()}}function r(r,n,i,o){void 0===o&&(o=t.less);var s=new t.Vector(t.distance(r,i),null);e(r,n,n,i,s.begin()),t.copy(s.begin(),s.end(),r)}function n(e,r,n,i,o){for(void 0===o&&(o=t.less);!n.equal_to(i);){if(e.equal_to(i)||o(n.value,e.value))return!1;o(e.value,n.value)||(n=n.next()),e=e.next()}return!0}function i(e,r,n,i,o,s){for(void 0===s&&(s=t.less);;){if(e.equal_to(r))return t.copy(n,i,o);if(n.equal_to(i))return t.copy(e,r,o);s(e.value,n.value)?(o.value=e.value,e=e.next()):s(n.value,e.value)?(o.value=n.value,n=n.next()):(o.value=e.value,e=e.next(),n=n.next()),o=o.next()}}function o(e,r,n,i,o,s){for(void 0===s&&(s=t.less);;){if(e.equal_to(r))return t.copy(n,i,o);if(n.equal_to(i))return t.copy(e,r,o);s(e.value,n.value)?e=e.next():s(n.value,e.value)?n=n.next():(o.value=e.value,o=o.next(),e=e.next(),n=n.next())}}function s(e,r,n,i,o,s){for(void 0===s&&(s=t.less);!e.equal_to(r)&&!n.equal_to(i);)t.less(e.value,n.value)?(o.value=e.value,o=o.next(),e=e.next()):t.less(n.value,e.value)?n=n.next():(e=e.next(),n=n.next());return t.copy(e,r,o)}function a(e,r,n,i,o,s){for(void 0===s&&(s=t.less);;){if(e.equal_to(r))return t.copy(n,i,o);if(n.equal_to(i))return t.copy(e,r,o);s(e.value,n.value)?(o.value=e.value,o=o.next(),e=e.next()):s(n.value,e.value)?(o.value=n.value,o=o.next(),n=n.next()):(e=e.next(),n=n.next())}}t.merge=e,t.inplace_merge=r,t.includes=n,t.set_union=i,t.set_intersection=o,t.set_difference=s,t.set_symmetric_difference=a}(std||(std={}));var std;!function(t){function e(){for(var e=[],r=0;rthis.capacity()&&this.rehash(this.item_size_*r.RATIO)},e.prototype.erase=function(t){for(var e=this.buckets_.at(this.hash_index(t)),r=0;r=0)for(e=0;e=this.get_col_size()&&(a=new Array,this.matrix_.push(a)),a.push(s.value)}else{var o=e,u=r;this.reserve(o),this.size_=o;for(var a=this.matrix_[0],_=0;_=this.get_col_size()&&(a=new Array,this.matrix_.push(a)),a.push(u)}},r.prototype.reserve=function(t){var e=this.matrix_;this.size_;this.matrix_=new Array,this.matrix_.push(new Array);for(var r=this.matrix_[0],n=0;n=this.get_col_size()&&(r=new Array,this.matrix_.push(r)),r.push(e[n][i])},r.prototype.clear=function(){this.matrix_=new Array,this.matrix_.push(new Array),this.size_=0,this.capacity_=r.MIN_CAPACITY},r.prototype.begin=function(){return 1==this.empty()?this.end():new t.DequeIterator(this,0)},r.prototype.end=function(){return new t.DequeIterator(this,-1)},r.prototype.rbegin=function(){return new t.DequeReverseIterator(this.end())},r.prototype.rend=function(){return new t.DequeReverseIterator(this.begin())},r.prototype.size=function(){return this.size_},r.prototype.empty=function(){return 0==this.size_},r.prototype.capacity=function(){return this.capacity_},r.prototype.at=function(e){if(e>this.size())throw new t.OutOfRange("Target index is greater than Deque's size.");var r=this.fetch_index(e);return this.matrix_[r.first][r.second]},r.prototype.set=function(e,r){if(e>this.size())throw new t.OutOfRange("Target index is greater than Deque's size.");var n=this.fetch_index(e);this.matrix_[n.first][n.second]=r},r.prototype.front=function(){return this.matrix_[0][0]},r.prototype.back=function(){var t=this.matrix_[this.matrix_.length-1];return t[t.length-1]},r.prototype.fetch_index=function(e){var r;for(r=0;rthis.capacity_&&this.reserve(this.size_+t.length);for(var r=this.matrix_[this.matrix_.length-1],n=0;n=this.get_col_size()&&(r=new Array,this.matrix_.push(r)),r.push(t[n]);return this.size_+=t.length,this.size_},r.prototype.push_front=function(t){this.matrix_[0].unshift(t),this.size_++,this.size_>this.capacity_&&this.reserve(2*this.size_)},r.prototype.push_back=function(t){var e=this.matrix_[this.matrix_.length-1];e.length>=this.get_col_size()&&this.matrix_.lengththis.capacity_&&this.reserve(2*this.size_)},r.prototype.pop_front=function(){1!=this.empty()&&(this.matrix_[0].shift(),this.size_--,0==this.matrix_[0].length&&this.matrix_.length>1&&this.matrix_.shift())},r.prototype.pop_back=function(){if(1!=this.empty()){var t=this.matrix_[this.matrix_.length-1];t.splice(t.length-1,1),this.size_--,0==t.length&&this.matrix_.length>1&&this.matrix_.splice(this.matrix_.length-1,1)}},r.prototype.insert=function(){for(var e=[],r=0;r1&&this.matrix_.splice(n.first,1),r-=o}return e.index==-1?this.end():t},r.prototype.swap=function(t){t instanceof r?(n=[t.matrix_,this.matrix_],this.matrix_=n[0],t.matrix_=n[1],i=[t.size_,this.size_],this.size_=i[0],t.size_=i[1],o=[t.capacity_,this.capacity_],this.capacity_=o[0],t.capacity_=o[1]):e.prototype.swap.call(this,t);var n,i,o},r}(t.base.Container);t.Deque=e}(std||(std={}));var std;!function(t){var e=function(t){function e(e,r){t.call(this,e),this.index_=r}return __extends(e,t),Object.defineProperty(e.prototype,"deque",{get:function(){return this.source_},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"value",{get:function(){return this.deque.at(this.index_)},set:function(t){this.deque.set(this.index_,t)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"index",{get:function(){return this.index_},enumerable:!0,configurable:!0}),e.prototype.prev=function(){return this.index_==-1?new e(this.deque,this.deque.size()-1):this.index_-1<0?this.deque.end():new e(this.deque,this.index_-1)},e.prototype.next=function(){return this.index_>=this.source_.size()-1?this.deque.end():new e(this.deque,this.index_+1)},e.prototype.advance=function(t){var r;return r=t<0&&this.index_==-1?this.deque.size()+t:this.index_+t,r<0||r>=this.deque.size()?this.deque.end():new e(this.deque,r)},e.prototype.equal_to=function(e){return t.prototype.equal_to.call(this,e)&&this.index_==e.index_},e.prototype.swap=function(t){e=[t.value,this.value],this.value=e[0],t.value=e[1];var e},e}(t.Iterator);t.DequeIterator=e}(std||(std={}));var std;!function(t){var e=function(t){function e(e){t.call(this,e)}return __extends(e,t),e.prototype.create_neighbor=function(t){return new e(t)},Object.defineProperty(e.prototype,"value",{get:function(){return this.base_.value},set:function(t){this.base_.value=t},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"index",{get:function(){return this.base_.index},enumerable:!0,configurable:!0}),e}(t.ReverseIterator);t.DequeReverseIterator=e}(std||(std={}));var std;!function(t){function e(){null!=f&&f(),1==t.is_node()?process.exit():(window.open("","_self",""),window.close())}function r(e){f=e,1==t.is_node()?process.on("uncaughtException",function(t){f()}):window.onerror=function(t,e,r,n,i){f()}}function n(){return f}t.terminate=e,t.set_terminate=r,t.get_terminate=n;var i=function(t){function e(e){void 0===e&&(e=""),t.call(this),this.description=e}return __extends(e,t),e.prototype.what=function(){return this.description},Object.defineProperty(e.prototype,"message",{get:function(){return this.description},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"name",{get:function(){return this.constructor.name},enumerable:!0,configurable:!0}),e}(Error);t.Exception=i;var o=function(t){function e(e){t.call(this,e)}return __extends(e,t),e}(i);t.LogicError=o;var s=function(t){function e(e){t.call(this,e)}return __extends(e,t),e}(o);t.DomainError=s;var a=function(t){function e(e){t.call(this,e)}return __extends(e,t),e}(o);t.InvalidArgument=a;var u=function(t){function e(e){t.call(this,e)}return __extends(e,t),e}(o);t.LengthError=u;var _=function(t){function e(e){t.call(this,e)}return __extends(e,t),e}(o);t.OutOfRange=_;var h=function(t){function e(e){t.call(this,e)}return __extends(e,t),e}(i);t.RuntimeError=h;var c=function(t){function e(e){t.call(this,e)}return __extends(e,t),e}(h);t.OverflowError=c;var l=function(t){function e(e){t.call(this,e)}return __extends(e,t),e}(h);t.UnderflowError=l;var p=function(t){function e(e){t.call(this,e)}return __extends(e,t),e}(h);t.RangeError=p;var f=null}(std||(std={}));var std;!function(t){function e(t,e){return t instanceof Object&&void 0!=t.equal_to?t.equal_to(e):t==e}function r(e,r){return!t.equal_to(e,r)}function n(t,e){return t instanceof Object?void 0!=t.less?t.less(e):t.__get_m_iUID()s)for(var h=s;hthis.hash_buckets_.size()*t.base.Hash.MAX_RATIO&&this.hash_buckets_.rehash((this.size()+i)*t.base.Hash.RATIO),this._Handle_insert(n,this.end())},r.prototype._Handle_insert=function(t,e){for(;!t.equal_to(e);t=t.next())this.hash_buckets_.insert(t)},r.prototype._Handle_erase=function(t,e){for(;!t.equal_to(e);t=t.next())this.hash_buckets_.erase(t)},r.prototype.swap=function(t){t instanceof r?(this._Swap(t),n=[t.hash_buckets_,this.hash_buckets_],this.hash_buckets_=n[0],t.hash_buckets_=n[1]):e.prototype.swap.call(this,t);var n},r}(t.base.UniqueMap);t.HashMap=e}(std||(std={}));var std;!function(t){var e=function(e){function r(){for(var n=[],i=0;ithis.hash_buckets_.item_size()*t.base.Hash.MAX_RATIO&&this.hash_buckets_.rehash(this.size()*t.base.Hash.RATIO),this._Handle_insert(i,this.end())},r.prototype._Handle_insert=function(t,e){for(;!t.equal_to(e);t=t.next())this.hash_buckets_.insert(t)},r.prototype._Handle_erase=function(t,e){for(;!t.equal_to(e);t=t.next())this.hash_buckets_.erase(t)},r.prototype.swap=function(t){t instanceof r?(this._Swap(t),n=[t.hash_buckets_,this.hash_buckets_],this.hash_buckets_=n[0],t.hash_buckets_=n[1]):e.prototype.swap.call(this,t);var n},r}(t.base.MultiMap);t.HashMultiMap=e}(std||(std={}));var std;!function(t){var e=function(e){function r(){for(var n=[],i=0;ithis.hash_buckets_.item_size()*t.base.Hash.MAX_RATIO&&this.hash_buckets_.rehash(this.size()*t.base.Hash.RATIO),this._Handle_insert(i,this.end())},r.prototype._Handle_insert=function(t,e){for(;!t.equal_to(e);t=t.next())this.hash_buckets_.insert(t)},r.prototype._Handle_erase=function(t,e){for(;!t.equal_to(e);t=t.next())this.hash_buckets_.erase(t)},r.prototype.swap=function(t){t instanceof r?(this._Swap(t),n=[t.hash_buckets_,this.hash_buckets_],this.hash_buckets_=n[0],t.hash_buckets_=n[1]):e.prototype.swap.call(this,t);var n},r}(t.base.MultiSet);t.HashMultiSet=e}(std||(std={}));var std;!function(t){var e=function(e){function r(){for(var n=[],i=0;ithis.hash_buckets_.size()*t.base.Hash.MAX_RATIO&&this.hash_buckets_.rehash((this.size()+i)*t.base.Hash.RATIO),this._Handle_insert(n,this.end())},r.prototype._Handle_insert=function(t,e){for(;!t.equal_to(e);t=t.next())this.hash_buckets_.insert(t)},r.prototype._Handle_erase=function(t,e){for(;!t.equal_to(e);t=t.next())this.hash_buckets_.erase(t)},r.prototype.swap=function(t){t instanceof r?(this._Swap(t),n=[t.hash_buckets_,this.hash_buckets_],this.hash_buckets_=n[0],t.hash_buckets_=n[1]):e.prototype.swap.call(this,t);var n},r}(t.base.UniqueSet);t.HashSet=e}(std||(std={}));var std;!function(t){var e=function(e){function r(){for(var n=[],i=0;i=0){for(var r=0;rthis.length)throw new t.OutOfRange("Target index is greater than Vector's size.");var n=this[e];return this[e]=r,n},r.prototype.front=function(){return this.at(0)},r.prototype.back=function(){return this.at(this.length-1)},r.prototype.push_back=function(t){e.prototype.push.call(this,t)},r.prototype.insert=function(){for(var e=[],r=0;r=this.source_.size()-1?this.vector.end():new e(this.vector,this.index_+1)},e.prototype.advance=function(t){var r;return r=t<0&&this.index_==-1?this.vector.size()+t:this.index_+t,r<0||r>=this.vector.size()?this.vector.end():new e(this.vector,r)},e.prototype.equal_to=function(e){return t.prototype.equal_to.call(this,e)&&this.index_==e.index_},e.prototype.swap=function(t){e=[t.value,this.value],this.value=e[0],t.value=e[1];var e},e}(t.Iterator);t.VectorIterator=e}(std||(std={}));var std;!function(t){var e=function(t){function e(e){t.call(this,e)}return __extends(e,t),e.prototype.create_neighbor=function(t){return new e(t)},Object.defineProperty(e.prototype,"value",{get:function(){return this.base_.value},set:function(t){this.base_.value=t},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"index",{get:function(){return this.base_.index},enumerable:!0,configurable:!0}),e}(t.ReverseIterator);t.VectorReverseIterator=e}(std||(std={}));var std;!function(t){var e=function(){function e(e){void 0===e&&(e=null),this.container_=new t.List,null!=e&&this.container_.assign(e.container_.begin(),e.container_.end())}return e.prototype.size=function(){return this.container_.size()},e.prototype.empty=function(){return this.container_.empty()},e.prototype.front=function(){return this.container_.front()},e.prototype.back=function(){return this.container_.back()},e.prototype.push=function(t){this.container_.push_back(t)},e.prototype.pop=function(){this.container_.pop_front()},e.prototype.swap=function(t){this.container_.swap(t.container_)},e}();t.Queue=e}(std||(std={}));var std;!function(t){var e=function(){function e(e){void 0===e&&(e=null),this.container_=new t.List,null!=e&&this.container_.assign(e.container_.begin(),e.container_.end())}return e.prototype.size=function(){return this.container_.size()},e.prototype.empty=function(){return this.container_.empty()},e.prototype.top=function(){return this.container_.back()},e.prototype.push=function(t){this.container_.push_back(t)},e.prototype.pop=function(){this.container_.pop_back()},e.prototype.swap=function(t){this.container_.swap(t.container_)},e}();t.Stack=e}(std||(std={}));var std;!function(t){var e=function(e){function r(){for(var n=[],i=0;i=1&&n[0]instanceof r){var o=n[0];2==n.length&&(this.tree_.compare_=n[1]),this.assign(o.begin(),o.end())}else if(n.length>=1&&n[0]instanceof Array){var s=n[0];2==n.length&&(this.tree_.compare_=n[1]),this.push.apply(this,s)}else if(n.length>=2&&n[0]instanceof t.Iterator&&n[1]instanceof t.Iterator){var a=n[0],u=n[1];2==n.length&&(this.tree_.compare_=n[2]),this.assign(a,u)}else 1==n.length&&(this.tree_.compare_=n[0])}return __extends(r,e),r.prototype.clear=function(){e.prototype.clear.call(this),this.tree_.clear()},r.prototype.find=function(e){var r=this.tree_.find(e);return null==r||0==t.equal_to(r.value.value,e)?this.end():r.value},r.prototype.key_comp=function(){return this.tree_.key_comp()},r.prototype.value_comp=function(){return this.tree_.key_comp()},r.prototype.lower_bound=function(t){return this.tree_.lower_bound(t)},r.prototype.upper_bound=function(t){return this.tree_.upper_bound(t)},r.prototype.equal_range=function(t){return this.tree_.equal_range(t)},r.prototype._Insert_by_val=function(e){var r=this.tree_.find(e);if(null!=r&&1==t.equal_to(r.value.value,e))return t.make_pair(r.value,!1);var n;return n=null==r?this.end():1==this.key_comp()(r.value.value,e)?r.value.next():r.value,n=new t.SetIterator(this,this.data_.insert(n.get_list_iterator(),e)),this._Handle_insert(n,n.next()),t.make_pair(n,!0)},r.prototype._Insert_by_hint=function(e,r){if(1==this.has(r))return this.end();var n,i=this.tree_.key_comp();return 1!=i(e.value,r)||!e.next().equal_to(this.end())&&1!=i(r,e.next().value)?n=this._Insert_by_val(r).first:(n=new t.SetIterator(this,this.data_.insert(e.get_list_iterator(),r)),this._Handle_insert(n,n.next())),n},r.prototype._Insert_by_range=function(t,e){for(;!t.equal_to(e);t=t.next())this._Insert_by_val(t.value)},r.prototype._Handle_insert=function(t,e){this.tree_.insert(t)},r.prototype._Handle_erase=function(t,e){for(;!t.equal_to(e);t=t.next())this.tree_.erase(e)},r.prototype.swap=function(t){t instanceof r&&this.key_comp()==t.key_comp()?(this._Swap(t),n=[t.tree_,this.tree_],this.tree_=n[0],t.tree_=n[1]):e.prototype.swap.call(this,t);var n},r}(t.base.UniqueSet);t.TreeSet=e}(std||(std={}));var std;!function(t){var e=function(e){function r(){for(var n=[],i=0;i=1&&n[0]instanceof r){var o=n[0];2==n.length&&(this.tree_.compare_=n[1]),this.assign(o.begin(),o.end())}else if(n.length>=1&&n[0]instanceof Array){var s=n[0];2==n.length&&(this.tree_.compare_=n[1]),this.push.apply(this,s)}else if(n.length>=2&&n[0]instanceof t.Iterator&&n[1]instanceof t.Iterator){var a=n[0],u=n[1];2==n.length&&(this.tree_.compare_=n[2]),this.assign(a,u)}else 1==n.length&&(this.tree_.compare_=n[0])}return __extends(r,e),r.prototype.clear=function(){e.prototype.clear.call(this),this.tree_.clear()},r.prototype.find=function(e){var r=this.tree_.find(e);return null==r||0==t.equal_to(r.value.first,e)?this.end():r.value},r.prototype.key_comp=function(){return this.tree_.key_comp()},r.prototype.value_comp=function(){return this.tree_.value_comp()},r.prototype.lower_bound=function(t){return this.tree_.lower_bound(t)},r.prototype.upper_bound=function(t){return this.tree_.upper_bound(t)},r.prototype.equal_range=function(t){return this.tree_.equal_range(t)},r.prototype._Insert_by_pair=function(e){var r=this.tree_.find(e.first);if(null!=r&&1==t.equal_to(r.value.first,e.first))return t.make_pair(r.value,!1);var n;return n=null==r?this.end():1==this.key_comp()(r.value.first,e.first)?r.value.next():r.value,n=new t.MapIterator(this,this.data_.insert(n.get_list_iterator(),e)),this._Handle_insert(n,n.next()),t.make_pair(n,!0)},r.prototype._Insert_by_hint=function(e,r){if(1==this.has(r.first))return this.end();var n,i=this.key_comp();return 1!=i(e.first,r.first)||!e.next().equal_to(this.end())&&1!=i(r.first,e.next().first)?n=this._Insert_by_pair(r).first:(n=new t.MapIterator(this,this.data_.insert(e.get_list_iterator(),r)),this._Handle_insert(n,n.next())),n},r.prototype._Insert_by_range=function(e,r){for(;!e.equal_to(r);e=e.next())this._Insert_by_pair(t.make_pair(e.value.first,e.value.second))},r.prototype._Handle_insert=function(t,e){this.tree_.insert(t)},r.prototype._Handle_erase=function(t,e){for(;!t.equal_to(e);t=t.next())this.tree_.erase(e)},r.prototype.swap=function(t){t instanceof r&&this.key_comp()==t.key_comp()?(this._Swap(t),n=[t.tree_,this.tree_],this.tree_=n[0],t.tree_=n[1]):e.prototype.swap.call(this,t);var n},r}(t.base.UniqueMap);t.TreeMap=e}(std||(std={}));var std;!function(t){var e=function(e){function r(){for(var n=[],i=0;i=1&&n[0]instanceof r){var o=n[0];2==n.length&&(this.tree_.compare_=n[1]),this.assign(o.begin(),o.end())}else if(n.length>=1&&n[0]instanceof Array){var s=n[0];2==n.length&&(this.tree_.compare_=n[1]),this.push.apply(this,s)}else if(n.length>=2&&n[0]instanceof t.Iterator&&n[1]instanceof t.Iterator){var a=n[0],u=n[1];2==n.length&&(this.tree_.compare_=n[2]),this.assign(a,u)}else 1==n.length&&(this.tree_.compare_=n[0])}return __extends(r,e),r.prototype.clear=function(){e.prototype.clear.call(this),this.tree_.clear()},r.prototype.find=function(e){var r=this.tree_.find(e);return null==r||0==t.equal_to(e,r.value.value)?this.end():r.value},r.prototype.count=function(e){for(var r=this.find(e),n=0;!r.equal_to(this.end())&&t.equal_to(r.value,e);r=r.next())n++;return n},r.prototype.key_comp=function(){return this.tree_.key_comp()},r.prototype.value_comp=function(){return this.tree_.key_comp()},r.prototype.lower_bound=function(t){return this.tree_.lower_bound(t)},r.prototype.upper_bound=function(t){return this.tree_.upper_bound(t)},r.prototype.equal_range=function(t){return this.tree_.equal_range(t)},r.prototype._Insert_by_val=function(e){var r,n=this.tree_.find(e);if(null==n)r=this.end();else if(1==t.equal_to(n.value.value,e))r=n.value.next();else if(1==this.key_comp()(n.value.value,e))for(r=n.value.next();0==r.equal_to(this.end())&&this.key_comp()(r.value,e);)r=r.next();else r=n.value;return r=new t.SetIterator(this,this.data_.insert(r.get_list_iterator(),e)),this._Handle_insert(r,r.next()),r},r.prototype._Insert_by_hint=function(e,r){var n,i=this.tree_.key_comp();return(i(e.value,r)||t.equal_to(e.value,r))&&(e.next().equal_to(this.end())||i(r,e.next().value)||t.equal_to(r,e.next().value))?(n=new t.SetIterator(this,this.data_.insert(e.get_list_iterator(),r)),this._Handle_insert(n,n.next())):n=this._Insert_by_val(r),n},r.prototype._Insert_by_range=function(t,e){for(;!t.equal_to(e);t=t.next())this._Insert_by_val(t.value)},r.prototype._Handle_insert=function(t,e){this.tree_.insert(t)},r.prototype._Handle_erase=function(t,e){for(;!t.equal_to(e);t=t.next())this.tree_.erase(e)},r.prototype.swap=function(t){t instanceof r&&this.key_comp()==t.key_comp()?(this._Swap(t),n=[t.tree_,this.tree_],this.tree_=n[0],t.tree_=n[1]):e.prototype.swap.call(this,t);var n},r}(t.base.MultiSet);t.TreeMultiSet=e}(std||(std={}));var std;!function(t){var e=function(e){function r(){for(var n=[],i=0;i=1&&n[0]instanceof r){var o=n[0];2==n.length&&(this.tree_.compare_=n[1]),this.assign(o.begin(),o.end())}else if(n.length>=1&&n[0]instanceof Array){var s=n[0];2==n.length&&(this.tree_.compare_=n[1]),this.push.apply(this,s)}else if(n.length>=2&&n[0]instanceof t.Iterator&&n[1]instanceof t.Iterator){var a=n[0],u=n[1];2==n.length&&(this.tree_.compare_=n[2]),this.assign(a,u)}else 1==n.length&&(this.tree_.compare_=n[0])}return __extends(r,e),r.prototype.clear=function(){e.prototype.clear.call(this),this.tree_.clear()},r.prototype.find=function(e){var r=this.tree_.find(e);return null==r||0==t.equal_to(r.value.first,e)?this.end():r.value},r.prototype.count=function(e){for(var r=this.find(e),n=0;!r.equal_to(this.end())&&t.equal_to(r.first,e);r=r.next())n++;return n},r.prototype.key_comp=function(){return this.tree_.key_comp()},r.prototype.value_comp=function(){return this.tree_.value_comp()},r.prototype.lower_bound=function(t){return this.tree_.lower_bound(t)},r.prototype.upper_bound=function(t){return this.tree_.upper_bound(t)},r.prototype.equal_range=function(t){return this.tree_.equal_range(t)},r.prototype._Insert_by_pair=function(e){var r,n=this.tree_.find(e.first);if(null==n)r=this.end();else if(1==t.equal_to(n.value.first,e.first))r=n.value.next();else if(1==this.key_comp()(n.value.first,e.first))for(r=n.value.next();0==r.equal_to(this.end())&&this.key_comp()(r.first,e.first);)r=r.next();else r=n.value;return r=new t.MapIterator(this,this.data_.insert(r.get_list_iterator(),e)),this._Handle_insert(r,r.next()),r},r.prototype._Insert_by_hint=function(e,r){if(1==this.has(r.first))return this.end();var n,i=this.key_comp();return(i(e.first,r.first)||t.equal_to(e.first,r.first))&&(e.next().equal_to(this.end())||i(r.first,e.next().first)||t.equal_to(r.first,e.next().first))?(n=new t.MapIterator(this,this.data_.insert(e.get_list_iterator(),r)),this._Handle_insert(n,n.next())):n=this._Insert_by_pair(r),n},r.prototype._Insert_by_range=function(e,r){for(;!e.equal_to(r);e=e.next())this._Insert_by_pair(t.make_pair(e.value.first,e.value.second))},r.prototype._Handle_insert=function(t,e){this.tree_.insert(t)},r.prototype._Handle_erase=function(t,e){for(;!t.equal_to(e);t=t.next())this.tree_.erase(e)},r.prototype.swap=function(t){t instanceof r&&this.key_comp()==t.key_comp()?(this._Swap(t),n=[t.tree_,this.tree_],this.tree_=n[0],t.tree_=n[1]):e.prototype.swap.call(this,t);var n},r}(t.base.MultiMap);t.TreeMultiMap=e}(std||(std={}));var std;!function(t){var e=function(t){function e(){for(var e=[],r=0;r=1&&e[0]instanceof t.base.Container){var n=e[0];2==e.length&&(this.container_.tree_.compare_=e[1]),this.container_.assign(n.begin(),n.end())}else if(e.length>=1&&e[0]instanceof Array){var i=e[0];2==e.length&&(this.container_.tree_.compare_=e[1]),(a=this.container_).push.apply(a,i)}else if(e.length>=2&&e[0]instanceof t.Iterator&&e[1]instanceof t.Iterator){var o=e[0],s=e[1];2==e.length&&(this.container_.tree_.compare_=e[2]),this.container_.assign(o,s)}else 1==e.length&&(this.container_.tree_.compare_=e[0]);var a}return e.prototype.size=function(){return this.container_.size()},e.prototype.empty=function(){return this.container_.empty()},e.prototype.top=function(){return this.container_.begin().value},e.prototype.push=function(t){this.container_.insert(t)},e.prototype.pop=function(){this.container_.erase(this.container_.begin())},e.prototype.swap=function(t){this.container_.swap(t.container_)},e}();t.PriorityQueue=e}(std||(std={})); \ No newline at end of file +var __extends=this&&this.__extends||function(t,e){function r(){this.constructor=t}for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n]);t.prototype=null===e?Object.create(e):(r.prototype=e.prototype,new r)},std;!function(t){t.vector=t.Vector,t.list=t.List,t.deque=t.Deque,t.stack=t.Stack,t.queue=t.Queue,t.priority_queue=t.PriorityQueue,t.set=t.TreeSet,t.multiset=t.TreeMultiSet,t.unordered_set=t.HashSet,t.unordered_multiset=t.HashMultiSet,t.map=t.TreeMap,t.multimap=t.TreeMultiMap,t.unordered_map=t.HashMap,t.unordered_multimap=t.HashMultiMap,t.exception=t.Exception,t.logic_error=t.LogicError,t.domain_error=t.DomainError,t.invalid_argument=t.InvalidArgument,t.length_error=t.LengthError,t.out_of_range=t.OutOfRange,t.runtime_error=t.RuntimeError,t.overflow_error=t.OverflowError,t.underflow_error=t.UnderflowError,t.range_error=t.RangeError,t.system_error=t.SystemError,t.error_category=t.ErrorCategory,t.error_condition=t.ErrorCondition,t.error_code=t.ErrorCode}(std||(std={}));var std;!function(t){function e(t,e,r){for(var n=t;!n.equal_to(e);n=n.next())r(n.value);return r}function r(t,e,r){for(var n=0;nu?t.copy(_.begin(),_.begin().advance(u),i):t.copy(_.begin(),_.end(),i)}function i(e,r,n){if(void 0===n&&(n=t.equal_to),e.equal_to(r))return!0;for(var i=e.next();!i.equal_to(r);i=i.next()){if(t.less(i.value,e.value))return!1;e=e.next()}return!0}function o(e,r,n){if(void 0===n&&(n=t.equal_to),e.equal_to(r))return e;for(var i=e.next();!i.equal_to(r);i=i.next()){if(t.less(i.value,e.value))return i;e=e.next()}return r}function s(t,e,r,n){if(r==-2&&(r=t.size()-1),!(e>=r)){var i=a(t,e,r,n);s(t,e,i-1,n),s(t,i+1,r,n)}}function a(t,e,r,n){for(var i=t.at(e),o=e,s=r+1;;){for(;n(t.at(++o),i)&&o!=r;);for(;n(i,t.at(--s))&&s!=e;);if(o>=s)break;var a=t.at(o);t.set(o,t.at(s)),t.set(s,a)}var u=t.at(e);return t.set(e,t.at(s)),t.set(s,u),s}function u(t,e,r,n,i){n==-1&&(n=t.size());for(var o=e;o0;){var s=Math.floor(o/2),a=e.advance(s);i(a.value,n)?o=s:(e=a.next(),o-=s+1)}return e}function r(e,r,n,i){void 0===i&&(i=t.less);for(var o=t.distance(e,r);o>0;){var s=Math.floor(o/2),a=e.advance(s);i(n,a.value)?o=s:(e=a.next(),o-=s+1)}return e}function n(n,i,o,s){void 0===s&&(s=t.less);var a=e(n,i,o,s);return t.make_pair(a,r(a,i,o,s))}function i(r,n,i,o){return void 0===o&&(o=t.less),r=e(r,n,i,o),!r.equal_to(n)&&!o(i,r.value)}t.lower_bound=e,t.upper_bound=r,t.equal_range=n,t.binary_search=i}(std||(std={}));var std;!function(t){function e(t,e,r){for(;!t.equal_to(e)&&r(t.value);)t=t.next();for(;!t.equal_to(e);t=t.next())if(r(t.value))return!1;return!0}function r(t,e,r){for(;!t.equal_to(e);){for(;r(t.value);)if(t=t.next(),t.equal_to(e))return t;do if(e=e.prev(),t.equal_to(e))return t;while(!r(e.value));t.swap(e),t=t.next()}return e}function n(t,e,n){return r(t,e,n)}function i(e,r,n,i,o){for(;!e.equal_to(r);e=e.next())o(e.value)?(n.value=e.value,n=n.next()):(i.value=e.value,i=i.next());return t.make_pair(n,i)}function o(e,r,n){for(var i=t.distance(e,r);i>0;){var o=Math.floor(i/2),s=e.advance(o);n(s.value)?(e=s.next(),i-=o+1):i=o}return e}t.is_partitioned=e,t.partition=r,t.stable_partition=n,t.partition_copy=i,t.partition_point=o}(std||(std={}));var std;!function(t){function e(e,r,n,i,o,s){for(void 0===s&&(s=t.less);;){if(e.equal_to(r))return t.copy(n,i,o);if(n.equal_to(i))return t.copy(e,r,o);s(e.value,n.value)?(o.value=e.value,e=e.next()):(o.value=n.value,n=n.next()),o=o.next()}}function r(r,n,i,o){void 0===o&&(o=t.less);var s=new t.Vector(t.distance(r,i),null);e(r,n,n,i,s.begin()),t.copy(s.begin(),s.end(),r)}function n(e,r,n,i,o){for(void 0===o&&(o=t.less);!n.equal_to(i);){if(e.equal_to(i)||o(n.value,e.value))return!1;o(e.value,n.value)||(n=n.next()),e=e.next()}return!0}function i(e,r,n,i,o,s){for(void 0===s&&(s=t.less);;){if(e.equal_to(r))return t.copy(n,i,o);if(n.equal_to(i))return t.copy(e,r,o);s(e.value,n.value)?(o.value=e.value,e=e.next()):s(n.value,e.value)?(o.value=n.value,n=n.next()):(o.value=e.value,e=e.next(),n=n.next()),o=o.next()}}function o(e,r,n,i,o,s){for(void 0===s&&(s=t.less);;){if(e.equal_to(r))return t.copy(n,i,o);if(n.equal_to(i))return t.copy(e,r,o);s(e.value,n.value)?e=e.next():s(n.value,e.value)?n=n.next():(o.value=e.value,o=o.next(),e=e.next(),n=n.next())}}function s(e,r,n,i,o,s){for(void 0===s&&(s=t.less);!e.equal_to(r)&&!n.equal_to(i);)t.less(e.value,n.value)?(o.value=e.value,o=o.next(),e=e.next()):t.less(n.value,e.value)?n=n.next():(e=e.next(),n=n.next());return t.copy(e,r,o)}function a(e,r,n,i,o,s){for(void 0===s&&(s=t.less);;){if(e.equal_to(r))return t.copy(n,i,o);if(n.equal_to(i))return t.copy(e,r,o);s(e.value,n.value)?(o.value=e.value,o=o.next(),e=e.next()):s(n.value,e.value)?(o.value=n.value,o=o.next(),n=n.next()):(e=e.next(),n=n.next())}}t.merge=e,t.inplace_merge=r,t.includes=n,t.set_union=i,t.set_intersection=o,t.set_difference=s,t.set_symmetric_difference=a}(std||(std={}));var std;!function(t){function e(){for(var e=[],r=0;r=0)for(e=0;e=this.get_col_size()&&(a=new Array,this.matrix_.push(a)),a.push(s.value)}else{var o=e,u=r;this.reserve(o),this.size_=o;for(var a=this.matrix_[0],_=0;_=this.get_col_size()&&(a=new Array,this.matrix_.push(a)),a.push(u)}},r.prototype.reserve=function(t){var e=this.matrix_;this.size_;this.matrix_=new Array,this.matrix_.push(new Array);for(var r=this.matrix_[0],n=0;n=this.get_col_size()&&(r=new Array,this.matrix_.push(r)),r.push(e[n][i])},r.prototype.clear=function(){this.matrix_=new Array,this.matrix_.push(new Array),this.size_=0,this.capacity_=r.MIN_CAPACITY},r.prototype.begin=function(){return 1==this.empty()?this.end():new t.DequeIterator(this,0)},r.prototype.end=function(){return new t.DequeIterator(this,-1)},r.prototype.rbegin=function(){return new t.DequeReverseIterator(this.end())},r.prototype.rend=function(){return new t.DequeReverseIterator(this.begin())},r.prototype.size=function(){return this.size_},r.prototype.empty=function(){return 0==this.size_},r.prototype.capacity=function(){return this.capacity_},r.prototype.at=function(e){if(e>this.size())throw new t.OutOfRange("Target index is greater than Deque's size.");var r=this.fetch_index(e);return this.matrix_[r.first][r.second]},r.prototype.set=function(e,r){if(e>this.size())throw new t.OutOfRange("Target index is greater than Deque's size.");var n=this.fetch_index(e);this.matrix_[n.first][n.second]=r},r.prototype.front=function(){return this.matrix_[0][0]},r.prototype.back=function(){var t=this.matrix_[this.matrix_.length-1];return t[t.length-1]},r.prototype.fetch_index=function(e){var r;for(r=0;rthis.capacity_&&this.reserve(this.size_+t.length);for(var r=this.matrix_[this.matrix_.length-1],n=0;n=this.get_col_size()&&(r=new Array,this.matrix_.push(r)),r.push(t[n]);return this.size_+=t.length,this.size_},r.prototype.push_front=function(t){this.matrix_[0].unshift(t),this.size_++,this.size_>this.capacity_&&this.reserve(2*this.size_)},r.prototype.push_back=function(t){var e=this.matrix_[this.matrix_.length-1];e.length>=this.get_col_size()&&this.matrix_.lengththis.capacity_&&this.reserve(2*this.size_)},r.prototype.pop_front=function(){1!=this.empty()&&(this.matrix_[0].shift(),this.size_--,0==this.matrix_[0].length&&this.matrix_.length>1&&this.matrix_.shift())},r.prototype.pop_back=function(){if(1!=this.empty()){var t=this.matrix_[this.matrix_.length-1];t.splice(t.length-1,1),this.size_--,0==t.length&&this.matrix_.length>1&&this.matrix_.splice(this.matrix_.length-1,1)}},r.prototype.insert=function(){for(var e=[],r=0;r1&&this.matrix_.splice(n.first,1),r-=o}return e.index==-1?this.end():t},r.prototype.swap=function(t){t instanceof r?(n=[t.matrix_,this.matrix_],this.matrix_=n[0],t.matrix_=n[1],i=[t.size_,this.size_],this.size_=i[0],t.size_=i[1],o=[t.capacity_,this.capacity_],this.capacity_=o[0],t.capacity_=o[1]):e.prototype.swap.call(this,t);var n,i,o},r}(t.base.Container);t.Deque=e}(std||(std={}));var std;!function(t){var e=function(t){function e(e,r){t.call(this,e),this.index_=r}return __extends(e,t),Object.defineProperty(e.prototype,"deque",{get:function(){return this.source_},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"value",{get:function(){return this.deque.at(this.index_)},set:function(t){this.deque.set(this.index_,t)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"index",{get:function(){return this.index_},enumerable:!0,configurable:!0}),e.prototype.prev=function(){return this.index_==-1?new e(this.deque,this.deque.size()-1):this.index_-1<0?this.deque.end():new e(this.deque,this.index_-1)},e.prototype.next=function(){return this.index_>=this.source_.size()-1?this.deque.end():new e(this.deque,this.index_+1)},e.prototype.advance=function(t){var r;return r=t<0&&this.index_==-1?this.deque.size()+t:this.index_+t,r<0||r>=this.deque.size()?this.deque.end():new e(this.deque,r)},e.prototype.equal_to=function(e){return t.prototype.equal_to.call(this,e)&&this.index_==e.index_},e.prototype.swap=function(t){e=[t.value,this.value],this.value=e[0],t.value=e[1];var e},e}(t.Iterator);t.DequeIterator=e}(std||(std={}));var std;!function(t){var e=function(t){function e(e){t.call(this,e)}return __extends(e,t),e.prototype.create_neighbor=function(t){return new e(t)},Object.defineProperty(e.prototype,"value",{get:function(){return this.base_.value},set:function(t){this.base_.value=t},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"index",{get:function(){return this.base_.index},enumerable:!0,configurable:!0}),e}(t.ReverseIterator);t.DequeReverseIterator=e}(std||(std={}));var std;!function(t){function e(){null!=f&&f(),1==t.is_node()?process.exit():(window.open("","_self",""),window.close())}function r(e){f=e,1==t.is_node()?process.on("uncaughtException",function(t){f()}):window.onerror=function(t,e,r,n,i){f()}}function n(){return f}t.terminate=e,t.set_terminate=r,t.get_terminate=n;var i=function(t){function e(e){void 0===e&&(e=""),t.call(this),this.description=e}return __extends(e,t),e.prototype.what=function(){return this.description},Object.defineProperty(e.prototype,"message",{get:function(){return this.description},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"name",{get:function(){return this.constructor.name},enumerable:!0,configurable:!0}),e}(Error);t.Exception=i;var o=function(t){function e(e){t.call(this,e)}return __extends(e,t),e}(i);t.LogicError=o;var s=function(t){function e(e){t.call(this,e)}return __extends(e,t),e}(o);t.DomainError=s;var a=function(t){function e(e){t.call(this,e)}return __extends(e,t),e}(o);t.InvalidArgument=a;var u=function(t){function e(e){t.call(this,e)}return __extends(e,t),e}(o);t.LengthError=u;var _=function(t){function e(e){t.call(this,e)}return __extends(e,t),e}(o);t.OutOfRange=_;var h=function(t){function e(e){t.call(this,e)}return __extends(e,t),e}(i);t.RuntimeError=h;var c=function(t){function e(e){t.call(this,e)}return __extends(e,t),e}(h);t.OverflowError=c;var l=function(t){function e(e){t.call(this,e)}return __extends(e,t),e}(h);t.UnderflowError=l;var p=function(t){function e(e){t.call(this,e)}return __extends(e,t),e}(h);t.RangeError=p;var f=null}(std||(std={}));var std;!function(t){function e(t,e){return t instanceof Object&&void 0!=t.equal_to?t.equal_to(e):t==e}function r(e,r){return!t.equal_to(e,r)}function n(t,e){return t instanceof Object?void 0!=t.less?t.less(e):t.__get_m_iUID()s)for(var h=s;hthis.hash_buckets_.size()*t.base.Hash.MAX_RATIO&&this.hash_buckets_.rehash((this.size()+i)*t.base.Hash.RATIO),this._Handle_insert(n,this.end())},r.prototype._Handle_insert=function(t,e){for(;!t.equal_to(e);t=t.next())this.hash_buckets_.insert(t)},r.prototype._Handle_erase=function(t,e){for(;!t.equal_to(e);t=t.next())this.hash_buckets_.erase(t)},r.prototype.swap=function(t){t instanceof r?(this._Swap(t),n=[t.hash_buckets_,this.hash_buckets_],this.hash_buckets_=n[0],t.hash_buckets_=n[1]):e.prototype.swap.call(this,t);var n},r}(t.base.UniqueMap);t.HashMap=e}(std||(std={}));var std;!function(t){var e=function(e){function r(){for(var n=[],i=0;ithis.hash_buckets_.item_size()*t.base.Hash.MAX_RATIO&&this.hash_buckets_.rehash(this.size()*t.base.Hash.RATIO),this._Handle_insert(i,this.end())},r.prototype._Handle_insert=function(t,e){for(;!t.equal_to(e);t=t.next())this.hash_buckets_.insert(t)},r.prototype._Handle_erase=function(t,e){for(;!t.equal_to(e);t=t.next())this.hash_buckets_.erase(t)},r.prototype.swap=function(t){t instanceof r?(this._Swap(t),n=[t.hash_buckets_,this.hash_buckets_],this.hash_buckets_=n[0],t.hash_buckets_=n[1]):e.prototype.swap.call(this,t);var n},r}(t.base.MultiMap);t.HashMultiMap=e}(std||(std={}));var std;!function(t){var e;!function(e){var r=function(e){function r(){e.call(this),this.data_=new t.List}return __extends(r,e),r.prototype.assign=function(t,e){this.clear(),this.insert(t,e)},r.prototype.clear=function(){this.data_.clear()},r.prototype.begin=function(){return new t.SetIterator(this,this.data_.begin())},r.prototype.end=function(){return new t.SetIterator(this,this.data_.end())},r.prototype.rbegin=function(){return new t.SetReverseIterator(this.end())},r.prototype.rend=function(){return new t.SetReverseIterator(this.begin())},r.prototype.has=function(t){return!this.find(t).equal_to(this.end())},r.prototype.size=function(){return this.data_.size()},r.prototype.push=function(){for(var t=[],e=0;ethis.hash_buckets_.item_size()*t.base.Hash.MAX_RATIO&&this.hash_buckets_.rehash(this.size()*t.base.Hash.RATIO),this._Handle_insert(i,this.end())},r.prototype._Handle_insert=function(t,e){for(;!t.equal_to(e);t=t.next())this.hash_buckets_.insert(t)},r.prototype._Handle_erase=function(t,e){for(;!t.equal_to(e);t=t.next())this.hash_buckets_.erase(t)},r.prototype.swap=function(t){t instanceof r?(this._Swap(t),n=[t.hash_buckets_,this.hash_buckets_],this.hash_buckets_=n[0],t.hash_buckets_=n[1]):e.prototype.swap.call(this,t);var n},r}(t.base.MultiSet);t.HashMultiSet=e}(std||(std={}));var std;!function(t){var e;!function(e){var r=function(e){function r(){e.apply(this,arguments)}return __extends(r,e),r.prototype.count=function(t){return this.find(t).equal_to(this.end())?0:1},r.prototype.extract=function(e){return e instanceof t.SetIterator?this.extract_by_iterator(e):e instanceof t.SetReverseIterator?this.extract_by_reverse_iterator(e):this.extract_by_key(e)},r.prototype.extract_by_key=function(e){var r=this.find(e);if(1==r.equal_to(this.end()))throw new t.OutOfRange("No such key exists.");return this.erase(e),e},r.prototype.extract_by_iterator=function(t){return 1==t.equal_to(this.end())||0==this.has(t.value)?this.end():(this.erase(t),t)},r.prototype.extract_by_reverse_iterator=function(t){return this.extract_by_iterator(t.base().next()),t},r.prototype.insert=function(){for(var t=[],r=0;rthis.hash_buckets_.size()*t.base.Hash.MAX_RATIO&&this.hash_buckets_.rehash((this.size()+i)*t.base.Hash.RATIO),this._Handle_insert(n,this.end())},r.prototype._Handle_insert=function(t,e){for(;!t.equal_to(e);t=t.next())this.hash_buckets_.insert(t)},r.prototype._Handle_erase=function(t,e){for(;!t.equal_to(e);t=t.next())this.hash_buckets_.erase(t)},r.prototype.swap=function(t){t instanceof r?(this._Swap(t),n=[t.hash_buckets_,this.hash_buckets_],this.hash_buckets_=n[0],t.hash_buckets_=n[1]):e.prototype.swap.call(this,t);var n},r}(t.base.UniqueSet);t.HashSet=e}(std||(std={}));var std;!function(t){var e=function(e){function r(){for(var n=[],i=0;i=0){for(var r=0;r=1&&e[0]instanceof t.base.Container){var n=e[0];2==e.length&&(this.container_.tree_.compare_=e[1]),this.container_.assign(n.begin(),n.end())}else if(e.length>=1&&e[0]instanceof Array){var i=e[0];2==e.length&&(this.container_.tree_.compare_=e[1]),(a=this.container_).push.apply(a,i)}else if(e.length>=2&&e[0]instanceof t.Iterator&&e[1]instanceof t.Iterator){var o=e[0],s=e[1];2==e.length&&(this.container_.tree_.compare_=e[2]),this.container_.assign(o,s)}else 1==e.length&&(this.container_.tree_.compare_=e[0]);var a}return e.prototype.size=function(){return this.container_.size()},e.prototype.empty=function(){return this.container_.empty()},e.prototype.top=function(){return this.container_.begin().value},e.prototype.push=function(t){this.container_.insert(t)},e.prototype.pop=function(){this.container_.erase(this.container_.begin())},e.prototype.swap=function(t){this.container_.swap(t.container_)},e}();t.PriorityQueue=e}(std||(std={}));var std;!function(t){var e=function(){function e(e){void 0===e&&(e=null),this.container_=new t.List,null!=e&&this.container_.assign(e.container_.begin(),e.container_.end())}return e.prototype.size=function(){return this.container_.size()},e.prototype.empty=function(){return this.container_.empty()},e.prototype.front=function(){return this.container_.front()},e.prototype.back=function(){return this.container_.back()},e.prototype.push=function(t){this.container_.push_back(t)},e.prototype.pop=function(){this.container_.pop_front()},e.prototype.swap=function(t){this.container_.swap(t.container_)},e}();t.Queue=e}(std||(std={}));var std;!function(t){var e=function(){function e(e){void 0===e&&(e=null),this.container_=new t.List,null!=e&&this.container_.assign(e.container_.begin(),e.container_.end())}return e.prototype.size=function(){return this.container_.size()},e.prototype.empty=function(){return this.container_.empty()},e.prototype.top=function(){return this.container_.back()},e.prototype.push=function(t){this.container_.push_back(t)},e.prototype.pop=function(){this.container_.pop_back()},e.prototype.swap=function(t){this.container_.swap(t.container_)},e}();t.Stack=e}(std||(std={}));var std;!function(t){var e;!function(t){var e=function(){function t(t,e){void 0===t&&(t=0),void 0===e&&(e=null),this.assign(t,e)}return t.prototype.assign=function(t,e){this.category_=e,this.value_=t},t.prototype.clear=function(){this.value_=0},t.prototype.category=function(){return this.category_},t.prototype.value=function(){return this.value_},t.prototype.message=function(){return null==this.category_||0==this.value_?"":this.category_.message(this.value_)},t.prototype.default_error_condition=function(){return null==this.category_||0==this.value_?null:this.category_.default_error_condition(this.value_)},t.prototype.to_bool=function(){return 0!=this.value_},t}();t.ErrorInstance=e}(e=t.base||(t.base={}))}(std||(std={}));var std;!function(t){var e=function(t){function e(){for(var e=[],r=0;r=1&&n[0]instanceof r){var o=n[0];2==n.length&&(this.tree_.compare_=n[1]),this.assign(o.begin(),o.end())}else if(n.length>=1&&n[0]instanceof Array){var s=n[0];2==n.length&&(this.tree_.compare_=n[1]),this.push.apply(this,s)}else if(n.length>=2&&n[0]instanceof t.Iterator&&n[1]instanceof t.Iterator){var a=n[0],u=n[1];2==n.length&&(this.tree_.compare_=n[2]),this.assign(a,u)}else 1==n.length&&(this.tree_.compare_=n[0])}return __extends(r,e),r.prototype.clear=function(){e.prototype.clear.call(this),this.tree_.clear()},r.prototype.find=function(e){var r=this.tree_.find(e);return null==r||0==t.equal_to(r.value.first,e)?this.end():r.value},r.prototype.key_comp=function(){return this.tree_.key_comp()},r.prototype.value_comp=function(){return this.tree_.value_comp()},r.prototype.lower_bound=function(t){return this.tree_.lower_bound(t)},r.prototype.upper_bound=function(t){return this.tree_.upper_bound(t)},r.prototype.equal_range=function(t){return this.tree_.equal_range(t)},r.prototype._Insert_by_pair=function(e){var r=this.tree_.find(e.first);if(null!=r&&1==t.equal_to(r.value.first,e.first))return t.make_pair(r.value,!1);var n;return n=null==r?this.end():1==this.key_comp()(r.value.first,e.first)?r.value.next():r.value,n=new t.MapIterator(this,this.data_.insert(n.get_list_iterator(),e)),this._Handle_insert(n,n.next()),t.make_pair(n,!0)},r.prototype._Insert_by_hint=function(e,r){if(1==this.has(r.first))return this.end();var n,i=this.key_comp();return 1!=i(e.first,r.first)||!e.next().equal_to(this.end())&&1!=i(r.first,e.next().first)?n=this._Insert_by_pair(r).first:(n=new t.MapIterator(this,this.data_.insert(e.get_list_iterator(),r)), +this._Handle_insert(n,n.next())),n},r.prototype._Insert_by_range=function(e,r){for(;!e.equal_to(r);e=e.next())this._Insert_by_pair(t.make_pair(e.value.first,e.value.second))},r.prototype._Handle_insert=function(t,e){this.tree_.insert(t)},r.prototype._Handle_erase=function(t,e){for(;!t.equal_to(e);t=t.next())this.tree_.erase(e)},r.prototype.swap=function(t){t instanceof r&&this.key_comp()==t.key_comp()?(this._Swap(t),n=[t.tree_,this.tree_],this.tree_=n[0],t.tree_=n[1]):e.prototype.swap.call(this,t);var n},r}(t.base.UniqueMap);t.TreeMap=e}(std||(std={}));var std;!function(t){var e=function(e){function r(){for(var n=[],i=0;i=1&&n[0]instanceof r){var o=n[0];2==n.length&&(this.tree_.compare_=n[1]),this.assign(o.begin(),o.end())}else if(n.length>=1&&n[0]instanceof Array){var s=n[0];2==n.length&&(this.tree_.compare_=n[1]),this.push.apply(this,s)}else if(n.length>=2&&n[0]instanceof t.Iterator&&n[1]instanceof t.Iterator){var a=n[0],u=n[1];2==n.length&&(this.tree_.compare_=n[2]),this.assign(a,u)}else 1==n.length&&(this.tree_.compare_=n[0])}return __extends(r,e),r.prototype.clear=function(){e.prototype.clear.call(this),this.tree_.clear()},r.prototype.find=function(e){var r=this.tree_.find(e);return null==r||0==t.equal_to(r.value.first,e)?this.end():r.value},r.prototype.count=function(e){for(var r=this.find(e),n=0;!r.equal_to(this.end())&&t.equal_to(r.first,e);r=r.next())n++;return n},r.prototype.key_comp=function(){return this.tree_.key_comp()},r.prototype.value_comp=function(){return this.tree_.value_comp()},r.prototype.lower_bound=function(t){return this.tree_.lower_bound(t)},r.prototype.upper_bound=function(t){return this.tree_.upper_bound(t)},r.prototype.equal_range=function(t){return this.tree_.equal_range(t)},r.prototype._Insert_by_pair=function(e){var r,n=this.tree_.find(e.first);if(null==n)r=this.end();else if(1==t.equal_to(n.value.first,e.first))r=n.value.next();else if(1==this.key_comp()(n.value.first,e.first))for(r=n.value.next();0==r.equal_to(this.end())&&this.key_comp()(r.first,e.first);)r=r.next();else r=n.value;return r=new t.MapIterator(this,this.data_.insert(r.get_list_iterator(),e)),this._Handle_insert(r,r.next()),r},r.prototype._Insert_by_hint=function(e,r){if(1==this.has(r.first))return this.end();var n,i=this.key_comp();return(i(e.first,r.first)||t.equal_to(e.first,r.first))&&(e.next().equal_to(this.end())||i(r.first,e.next().first)||t.equal_to(r.first,e.next().first))?(n=new t.MapIterator(this,this.data_.insert(e.get_list_iterator(),r)),this._Handle_insert(n,n.next())):n=this._Insert_by_pair(r),n},r.prototype._Insert_by_range=function(e,r){for(;!e.equal_to(r);e=e.next())this._Insert_by_pair(t.make_pair(e.value.first,e.value.second))},r.prototype._Handle_insert=function(t,e){this.tree_.insert(t)},r.prototype._Handle_erase=function(t,e){for(;!t.equal_to(e);t=t.next())this.tree_.erase(e)},r.prototype.swap=function(t){t instanceof r&&this.key_comp()==t.key_comp()?(this._Swap(t),n=[t.tree_,this.tree_],this.tree_=n[0],t.tree_=n[1]):e.prototype.swap.call(this,t);var n},r}(t.base.MultiMap);t.TreeMultiMap=e}(std||(std={}));var std;!function(t){var e=function(e){function r(){for(var n=[],i=0;i=1&&n[0]instanceof r){var o=n[0];2==n.length&&(this.tree_.compare_=n[1]),this.assign(o.begin(),o.end())}else if(n.length>=1&&n[0]instanceof Array){var s=n[0];2==n.length&&(this.tree_.compare_=n[1]),this.push.apply(this,s)}else if(n.length>=2&&n[0]instanceof t.Iterator&&n[1]instanceof t.Iterator){var a=n[0],u=n[1];2==n.length&&(this.tree_.compare_=n[2]),this.assign(a,u)}else 1==n.length&&(this.tree_.compare_=n[0])}return __extends(r,e),r.prototype.clear=function(){e.prototype.clear.call(this),this.tree_.clear()},r.prototype.find=function(e){var r=this.tree_.find(e);return null==r||0==t.equal_to(e,r.value.value)?this.end():r.value},r.prototype.count=function(e){for(var r=this.find(e),n=0;!r.equal_to(this.end())&&t.equal_to(r.value,e);r=r.next())n++;return n},r.prototype.key_comp=function(){return this.tree_.key_comp()},r.prototype.value_comp=function(){return this.tree_.key_comp()},r.prototype.lower_bound=function(t){return this.tree_.lower_bound(t)},r.prototype.upper_bound=function(t){return this.tree_.upper_bound(t)},r.prototype.equal_range=function(t){return this.tree_.equal_range(t)},r.prototype._Insert_by_val=function(e){var r,n=this.tree_.find(e);if(null==n)r=this.end();else if(1==t.equal_to(n.value.value,e))r=n.value.next();else if(1==this.key_comp()(n.value.value,e))for(r=n.value.next();0==r.equal_to(this.end())&&this.key_comp()(r.value,e);)r=r.next();else r=n.value;return r=new t.SetIterator(this,this.data_.insert(r.get_list_iterator(),e)),this._Handle_insert(r,r.next()),r},r.prototype._Insert_by_hint=function(e,r){var n,i=this.tree_.key_comp();return(i(e.value,r)||t.equal_to(e.value,r))&&(e.next().equal_to(this.end())||i(r,e.next().value)||t.equal_to(r,e.next().value))?(n=new t.SetIterator(this,this.data_.insert(e.get_list_iterator(),r)),this._Handle_insert(n,n.next())):n=this._Insert_by_val(r),n},r.prototype._Insert_by_range=function(t,e){for(;!t.equal_to(e);t=t.next())this._Insert_by_val(t.value)},r.prototype._Handle_insert=function(t,e){this.tree_.insert(t)},r.prototype._Handle_erase=function(t,e){for(;!t.equal_to(e);t=t.next())this.tree_.erase(e)},r.prototype.swap=function(t){t instanceof r&&this.key_comp()==t.key_comp()?(this._Swap(t),n=[t.tree_,this.tree_],this.tree_=n[0],t.tree_=n[1]):e.prototype.swap.call(this,t);var n},r}(t.base.MultiSet);t.TreeMultiSet=e}(std||(std={}));var std;!function(t){var e=function(e){function r(){for(var n=[],i=0;i=1&&n[0]instanceof r){var o=n[0];2==n.length&&(this.tree_.compare_=n[1]),this.assign(o.begin(),o.end())}else if(n.length>=1&&n[0]instanceof Array){var s=n[0];2==n.length&&(this.tree_.compare_=n[1]),this.push.apply(this,s)}else if(n.length>=2&&n[0]instanceof t.Iterator&&n[1]instanceof t.Iterator){var a=n[0],u=n[1];2==n.length&&(this.tree_.compare_=n[2]),this.assign(a,u)}else 1==n.length&&(this.tree_.compare_=n[0])}return __extends(r,e),r.prototype.clear=function(){e.prototype.clear.call(this),this.tree_.clear()},r.prototype.find=function(e){var r=this.tree_.find(e);return null==r||0==t.equal_to(r.value.value,e)?this.end():r.value},r.prototype.key_comp=function(){return this.tree_.key_comp()},r.prototype.value_comp=function(){return this.tree_.key_comp()},r.prototype.lower_bound=function(t){return this.tree_.lower_bound(t)},r.prototype.upper_bound=function(t){return this.tree_.upper_bound(t)},r.prototype.equal_range=function(t){return this.tree_.equal_range(t)},r.prototype._Insert_by_val=function(e){var r=this.tree_.find(e);if(null!=r&&1==t.equal_to(r.value.value,e))return t.make_pair(r.value,!1);var n;return n=null==r?this.end():1==this.key_comp()(r.value.value,e)?r.value.next():r.value,n=new t.SetIterator(this,this.data_.insert(n.get_list_iterator(),e)),this._Handle_insert(n,n.next()),t.make_pair(n,!0)},r.prototype._Insert_by_hint=function(e,r){if(1==this.has(r))return this.end();var n,i=this.tree_.key_comp();return 1!=i(e.value,r)||!e.next().equal_to(this.end())&&1!=i(r,e.next().value)?n=this._Insert_by_val(r).first:(n=new t.SetIterator(this,this.data_.insert(e.get_list_iterator(),r)),this._Handle_insert(n,n.next())),n},r.prototype._Insert_by_range=function(t,e){for(;!t.equal_to(e);t=t.next())this._Insert_by_val(t.value)},r.prototype._Handle_insert=function(t,e){this.tree_.insert(t)},r.prototype._Handle_erase=function(t,e){for(;!t.equal_to(e);t=t.next())this.tree_.erase(e)},r.prototype.swap=function(t){t instanceof r&&this.key_comp()==t.key_comp()?(this._Swap(t),n=[t.tree_,this.tree_],this.tree_=n[0],t.tree_=n[1]):e.prototype.swap.call(this,t);var n},r}(t.base.UniqueSet);t.TreeSet=e}(std||(std={}));var std;!function(t){function e(){return"object"==typeof process&&"object"==typeof process.versions&&"undefined"!=typeof process.versions.node}function r(t,e){return new n(t,e)}t.is_node=e;var n=function(){function e(t,e){this.first=t,this.second=e}return e.prototype.equal_to=function(e){return t.equal_to(this.first,e.first)&&t.equal_to(this.second,e.second)},e.prototype.less=function(e){return 0==t.equal_to(this.first,e.first)?t.less(this.first,e.first):t.less(this.second,e.second)},e}();t.Pair=n,t.make_pair=r}(std||(std={}));var std;!function(t){var e=function(e){function r(){for(var r=[],n=0;nthis.length)throw new t.OutOfRange("Target index is greater than Vector's size.");var n=this[e];return this[e]=r,n},r.prototype.front=function(){return this.at(0)},r.prototype.back=function(){return this.at(this.length-1)},r.prototype.push_back=function(t){e.prototype.push.call(this,t)},r.prototype.insert=function(){for(var e=[],r=0;r=this.source_.size()-1?this.vector.end():new e(this.vector,this.index_+1)},e.prototype.advance=function(t){var r;return r=t<0&&this.index_==-1?this.vector.size()+t:this.index_+t,r<0||r>=this.vector.size()?this.vector.end():new e(this.vector,r)},e.prototype.equal_to=function(e){return t.prototype.equal_to.call(this,e)&&this.index_==e.index_},e.prototype.swap=function(t){e=[t.value,this.value],this.value=e[0],t.value=e[1];var e},e}(t.Iterator);t.VectorIterator=e}(std||(std={}));var std;!function(t){var e=function(t){function e(e){t.call(this,e)}return __extends(e,t),e.prototype.create_neighbor=function(t){return new e(t)},Object.defineProperty(e.prototype,"value",{get:function(){return this.base_.value},set:function(t){this.base_.value=t},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"index",{get:function(){return this.base_.index},enumerable:!0,configurable:!0}),e}(t.ReverseIterator);t.VectorReverseIterator=e}(std||(std={}));var std;!function(t){var e;!function(t){!function(t){t[t.BLACK=0]="BLACK",t[t.RED=1]="RED"}(t.Color||(t.Color={}));t.Color}(e=t.base||(t.base={}))}(std||(std={}));var std;!function(t){var e;!function(e){!function(t){t[t.MIN_SIZE=10]="MIN_SIZE",t[t.RATIO=1]="RATIO",t[t.MAX_RATIO=2]="MAX_RATIO"}(e.Hash||(e.Hash={}));var r=e.Hash,n=function(){function e(){this.clear()}return e.prototype.rehash=function(e){ethis.capacity()&&this.rehash(this.item_size_*r.RATIO)},e.prototype.erase=function(t){for(var e=this.buckets_.at(this.hash_index(t)),r=0;r\r\n\r\nimport std = require("typescript-stl");\r\nlet map: std.TreeMap = new std.TreeMap();\r\n\r\nmap.insert(std.make_pair("First", 1));\r\nmap.insert(["Second", 2]);\r\nmap.insert_or_assign("Third", 3); // C++17 Feature.\r\nmap.set("Fourth", 4); // Non-standard Feature.\r\n\r\nfor (let it = map.begin(); !it.equal_to(map.end()); it = it.next())\r\n\tconsole.log(it.first, it.second); // key => string, value => number\r\n```\r\n\r\n#### Browser\r\n*TypeScript-STL* follows *CommonJS* module. You can\'t use ```require``` statement of *RequireJS*, which is following *AMD* module. Just include *TypeScript-STL*\'s *js file* with ```\r\n```\r\n\r\n\r\n\r\n## Index of Guidance, Wiki.\r\n\r\n - [**Outline**](https://github.com/samchon/typescript-stl/wiki/Home)\r\n - [Introduction](https://github.com/samchon/typescript-stl/wiki/Home#introduction)\r\n - [References](https://github.com/samchon/typescript-stl/wiki/Home#references)\r\n - [Installation](https://github.com/samchon/typescript-stl/wiki/Home#installation)\r\n - [**Differences between C++**](https://github.com/samchon/typescript-stl/wiki/Differences)\r\n - [Naming Convention](https://github.com/samchon/typescript-stl/wiki/Differences#naming-convention)\r\n - [Operator Overriding](https://github.com/samchon/typescript-stl/wiki/Differences#operator-overriding)\r\n - [Iterator](https://github.com/samchon/typescript-stl/wiki/Differences#iterator)\r\n - [Tree Container](https://github.com/samchon/typescript-stl/wiki/Differences#tree-container)\r\n - [Hash Container](https://github.com/samchon/typescript-stl/wiki/Differences#hash-container)\r\n - [**Tutorial**](https://github.com/samchon/typescript-stl/wiki/Tutorial)\r\n - [Linear Container](https://github.com/samchon/typescript-stl/wiki/Tutorial#linear-container)\r\n - [Tree Container](https://github.com/samchon/typescript-stl/wiki/Tutorial#tree-container)\r\n - [Hash Container](https://github.com/samchon/typescript-stl/wiki/Tutorial#hash-container)\r\n - [Miscellaneous](https://github.com/samchon/typescript-stl/wiki/Tutorial-Miscellaneous)\r\n - [Algorithm](https://github.com/samchon/typescript-stl/wiki/Tutorial-Miscellaneous#algorithm)\r\n - [Functional](https://github.com/samchon/typescript-stl/wiki/Tutorial-Miscellaneous#functional)', +21 silly install resolved readmeFilename: 'README.md', +21 silly install resolved gitHead: 'b6a4b360a8f654ca1c162fdedab25def5a521235', +21 silly install resolved _id: 'typescript-stl@1.1.0', +21 silly install resolved scripts: {}, +21 silly install resolved _shasum: 'd99b100d571c916d06a4adbe82db0628eb510e7a', +21 silly install resolved _from: 'D:\\OneDrive\\Project\\Samchon\\typescript-stl', +21 silly install resolved _resolved: 'file:D:\\OneDrive\\Project\\Samchon\\typescript-stl' } ] +22 info install typescript-stl@1.1.0 into C:\Users\Jeongho Nam\AppData\Roaming\npm +23 info installOne typescript-stl@1.1.0 +24 verbose installOne of typescript-stl to C:\Users\Jeongho Nam\AppData\Roaming\npm not in flight; installing +25 verbose correctMkdir C:\Users\Jeongho Nam\AppData\Roaming\npm-cache\_locks correctMkdir not in flight; initializing +26 verbose lock using C:\Users\Jeongho Nam\AppData\Roaming\npm-cache\_locks\typescript-stl-66745383a23b386c.lock for C:\Users\Jeongho Nam\AppData\Roaming\npm\node_modules\typescript-stl +27 silly install write writing typescript-stl 1.1.0 to C:\Users\Jeongho Nam\AppData\Roaming\npm\node_modules\typescript-stl +28 verbose unbuild node_modules\typescript-stl +29 silly gentlyRm C:\Users\Jeongho Nam\AppData\Roaming\npm\node_modules\typescript-stl is being purged from base C:\Users\Jeongho Nam\AppData\Roaming\npm +30 verbose gentlyRm don't care about contents; nuking C:\Users\Jeongho Nam\AppData\Roaming\npm\node_modules\typescript-stl +31 verbose tar unpack C:\Users\Jeongho Nam\AppData\Roaming\npm-cache\typescript-stl\1.1.0\package.tgz +32 verbose tar unpacking to C:\Users\Jeongho Nam\AppData\Roaming\npm\node_modules\typescript-stl +33 silly gentlyRm C:\Users\Jeongho Nam\AppData\Roaming\npm\node_modules\typescript-stl is being purged +34 verbose gentlyRm don't care about contents; nuking C:\Users\Jeongho Nam\AppData\Roaming\npm\node_modules\typescript-stl +35 silly gunzTarPerm modes [ '777', '666' ] +36 silly gunzTarPerm extractEntry package.json +37 silly gunzTarPerm extractEntry README.md +38 silly gunzTarPerm extractEntry LICENSE +39 silly gunzTarPerm extractEntry lib/typescript-stl.js +40 silly gunzTarPerm extractEntry lib/typescript-stl.min.js +41 verbose write writing to C:\Users\Jeongho Nam\AppData\Roaming\npm\node_modules\typescript-stl\package.json +42 info preinstall typescript-stl@1.1.0 +43 verbose readDependencies loading dependencies from C:\Users\Jeongho Nam\AppData\Roaming\npm\node_modules\typescript-stl\package.json +44 verbose readDependencies loading dependencies from C:\Users\Jeongho Nam\AppData\Roaming\npm\node_modules\typescript-stl\package.json +45 silly install resolved [] +46 verbose about to build C:\Users\Jeongho Nam\AppData\Roaming\npm\node_modules\typescript-stl +47 info build C:\Users\Jeongho Nam\AppData\Roaming\npm\node_modules\typescript-stl +48 info linkStuff typescript-stl@1.1.0 +49 silly linkStuff typescript-stl@1.1.0 has C:\Users\Jeongho Nam\AppData\Roaming\npm\node_modules as its parent node_modules +50 silly linkStuff typescript-stl@1.1.0 is part of a global install +51 silly linkStuff typescript-stl@1.1.0 is installed into a global node_modules +52 silly linkStuff typescript-stl@1.1.0 is installed into the top-level global node_modules +53 verbose linkBins typescript-stl@1.1.0 +54 verbose linkMans typescript-stl@1.1.0 +55 verbose rebuildBundles typescript-stl@1.1.0 +56 info install typescript-stl@1.1.0 +57 info postinstall typescript-stl@1.1.0 +58 verbose unlock done using C:\Users\Jeongho Nam\AppData\Roaming\npm-cache\_locks\typescript-stl-66745383a23b386c.lock for C:\Users\Jeongho Nam\AppData\Roaming\npm\node_modules\typescript-stl +59 verbose validateInstall loading C:\Users\Jeongho Nam\AppData\Roaming\npm\package.json for validation +60 verbose stack Error: The package react@15.3.1 does not satisfy its siblings' peerDependencies requirements! +60 verbose stack at C:\Program Files\nodejs\node_modules\npm\lib\install.js:125:32 +60 verbose stack at C:\Program Files\nodejs\node_modules\npm\lib\install.js:268:7 +60 verbose stack at C:\Program Files\nodejs\node_modules\npm\node_modules\read-installed\read-installed.js:142:5 +60 verbose stack at C:\Program Files\nodejs\node_modules\npm\node_modules\read-installed\read-installed.js:263:14 +60 verbose stack at cb (C:\Program Files\nodejs\node_modules\npm\node_modules\slide\lib\async-map.js:47:24) +60 verbose stack at C:\Program Files\nodejs\node_modules\npm\node_modules\read-installed\read-installed.js:263:14 +60 verbose stack at cb (C:\Program Files\nodejs\node_modules\npm\node_modules\slide\lib\async-map.js:47:24) +60 verbose stack at C:\Program Files\nodejs\node_modules\npm\node_modules\read-installed\read-installed.js:263:14 +60 verbose stack at cb (C:\Program Files\nodejs\node_modules\npm\node_modules\slide\lib\async-map.js:47:24) +60 verbose stack at C:\Program Files\nodejs\node_modules\npm\node_modules\read-installed\read-installed.js:263:14 +61 verbose cwd D:\OneDrive\Project\Samchon\typescript-stl +62 error Windows_NT 10.0.14393 +63 error argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "-g" +64 error node v4.4.4 +65 error npm v2.15.1 +66 error code EPEERINVALID +67 error peerinvalid The package react@15.3.1 does not satisfy its siblings' peerDependencies requirements! +67 error peerinvalid Peer react-contextmenu@1.6.2 wants react@^0.14.0 || ^15.0.0 +67 error peerinvalid Peer react-dnd@2.1.4 wants react@^0.14.0 || ^15.0.0-0 +67 error peerinvalid Peer react-select@1.0.0-rc.1 wants react@^0.14 || ^15.0.0-rc || ^15.0 +67 error peerinvalid Peer ron-react-autocomplete@3.0.1 wants react@~0.14.6 +67 error peerinvalid Peer react-dom@0.14.8 wants react@^0.14.8 +68 verbose exit [ 1, true ]

This namespace declares an unspecified number of objects: _1, _2, _3, ..., which are - * used to specify placeholders in calls to function {@link std.bind}.