22 Containers library [containers]

22.2 Container requirements [container.requirements]

22.2.7 Unordered associative containers [unord.req]

22.2.7.1 General [unord.req.general]

Unordered associative containers provide an ability for fast retrieval of data based on keys.
The worst-case complexity for most operations is linear, but the average case is much faster.
The library provides four unordered associative containers: unordered_­set, unordered_­map, unordered_­multiset, and unordered_­multimap.
Unordered associative containers conform to the requirements for Containers, except that the expressions a == b and a != b have different semantics than for the other container types.
Each unordered associative container is parameterized by Key, by a function object type Hash that meets the Cpp17Hash requirements ([hash.requirements]) and acts as a hash function for argument values of type Key, and by a binary predicate Pred that induces an equivalence relation on values of type Key.
Additionally, unordered_­map and unordered_­multimap associate an arbitrary mapped type T with the Key.
The container's object of type Hash — denoted by hash — is called the hash function of the container.
The container's object of type Pred — denoted by pred — is called the key equality predicate of the container.
Two values k1 and k2 are considered equivalent if the container's key equality predicate pred(k1, k2) is valid and returns true when passed those values.
If k1 and k2 are equivalent, the container's hash function shall return the same value for both.
[Note 1:
Thus, when an unordered associative container is instantiated with a non-default Pred parameter it usually needs a non-default Hash parameter as well.
— end note]
For any two keys k1 and k2 in the same container, calling pred(k1, k2) shall always return the same value.
For any key k in a container, calling hash(k) shall always return the same value.
An unordered associative container supports unique keys if it may contain at most one element for each key.
Otherwise, it supports equivalent keys.
unordered_­set and unordered_­map support unique keys.
unordered_­multiset and unordered_­multimap support equivalent keys.
In containers that support equivalent keys, elements with equivalent keys are adjacent to each other in the iteration order of the container.
Thus, although the absolute order of elements in an unordered container is not specified, its elements are grouped into equivalent-key groups such that all elements of each group have equivalent keys.
Mutating operations on unordered containers shall preserve the relative order of elements within each equivalent-key group unless otherwise specified.
For unordered_­set and unordered_­multiset the value type is the same as the key type.
For unordered_­map and unordered_­multimap it is pair<const Key, T>.
For unordered containers where the value type is the same as the key type, both iterator and const_­iterator are constant iterators.
It is unspecified whether or not iterator and const_­iterator are the same type.
[Note 2:
iterator and const_­iterator have identical semantics in this case, and iterator is convertible to const_­iterator.
Users can avoid violating the one-definition rule by always using const_­iterator in their function parameter lists.
— end note]
The elements of an unordered associative container are organized into buckets.
Keys with the same hash code appear in the same bucket.
The number of buckets is automatically increased as elements are added to an unordered associative container, so that the average number of elements per bucket is kept below a bound.
Rehashing invalidates iterators, changes ordering between elements, and changes which buckets elements appear in, but does not invalidate pointers or references to elements.
For unordered_­multiset and unordered_­multimap, rehashing preserves the relative ordering of equivalent elements.
The unordered associative containers meet all the requirements of Allocator-aware containers, except that for unordered_­map and unordered_­multimap, the requirements placed on value_­type in Table 76 apply instead to key_­type and mapped_­type.
[Note 3:
For example, key_­type and mapped_­type are sometimes required to be Cpp17CopyAssignable even though the associated value_­type, pair<const key_­type, mapped_­type>, is not Cpp17CopyAssignable.
— end note]
In Table 81:
  • X denotes an unordered associative container class,
  • a denotes a value of type X,
  • a2 denotes a value of a type with nodes compatible with type X (Table 79),
  • b denotes a possibly const value of type X,
  • a_­uniq denotes a value of type X when X supports unique keys,
  • a_­eq denotes a value of type X when X supports equivalent keys,
  • a_­tran denotes a possibly const value of type X when the qualified-ids X​::​key_­equal​::​is_­transparent and X​::​hasher​::​is_­transparent are both valid and denote types ([temp.deduct]),
  • i and j denote input iterators that refer to value_­type,
  • [i, j) denotes a valid range,
  • p and q2 denote valid constant iterators to a,
  • q and q1 denote valid dereferenceable constant iterators to a,
  • r denotes a valid dereferenceable iterator to a,
  • [q1, q2) denotes a valid range in a,
  • il denotes a value of type initializer_­list<value_­type>,
  • t denotes a value of type X​::​value_­type,
  • k denotes a value of type key_­type,
  • hf denotes a possibly const value of type hasher,
  • eq denotes a possibly const value of type key_­equal,
  • ke is a value such that where r1 and r2 are keys of elements in a_­tran,
  • n denotes a value of type size_­type,
  • z denotes a value of type float, and
  • nh denotes a non-const rvalue of type X​::​node_­type.
Table 81: Unordered associative container requirements (in addition to container) [tab:container.hash.req]
Expression
Return type
Assertion/note
Complexity
pre-/post-condition
X​::​key_­type
Key
compile time
X​::​mapped_­type (unordered_­map and unordered_­multimap only)
T
compile time
X​::​value_­type (unordered_­set and unordered_­multiset only)
Key
Preconditions: value_­type is Cpp17Erasable from X
compile time
X​::​value_­type (unordered_­map and unordered_­multimap only)
pair<const Key, T>
Preconditions: value_­type is Cpp17Erasable from X
compile time
X​::​hasher
Hash
Preconditions: Hash is a unary function object type such that the expression hf(k) has type size_­t.
compile time
X​::​key_­equal
Pred
Preconditions: Pred meets the Cpp17CopyConstructible requirements.

Pred is a binary predicate that takes two arguments of type Key.
Pred is an equivalence relation.
compile time
X​::​local_­iterator
An iterator type whose category, value type, difference type, and pointer and reference types are the same as X​::​iterator's.
A local_­iterator object may be used to iterate through a single bucket, but may not be used to iterate across buckets.
compile time
X​::​const_­local_­iterator
An iterator type whose category, value type, difference type, and pointer and reference types are the same as X​::​const_­iterator's.
A const_­local_­iterator object may be used to iterate through a single bucket, but may not be used to iterate across buckets.
compile time
X​::​node_­type
a specialization of a node-handle class template, such that the public nested types are the same types as the corresponding types in X.
compile time
X(n, hf, eq)
X a(n, hf, eq);
X
Effects:  Constructs an empty container with at least n buckets, using hf as the hash function and eq as the key equality predicate.
X(n, hf)
X a(n, hf);
X
Preconditions: key_­equal meets the Cpp17DefaultConstructible requirements.

Effects:  Constructs an empty container with at least n buckets, using hf as the hash function and key_­equal() as the key equality predicate.
X(n)
X a(n);
X
Preconditions: hasher and key_­equal meet the Cpp17DefaultConstructible requirements.

Effects:  Constructs an empty container with at least n buckets, using hasher() as the hash function and key_­equal() as the key equality predicate.
X()
X a;
X
Preconditions: hasher and key_­equal meet the Cpp17DefaultConstructible requirements.

Effects:  Constructs an empty container with an unspecified number of buckets, using hasher() as the hash function and key_­equal() as the key equality predicate.
constant
X(i, j, n, hf, eq)
X a(i, j, n, hf, eq);
X
Preconditions: value_­type is Cpp17EmplaceConstructible into X from *i.

Effects:  Constructs an empty container with at least n buckets, using hf as the hash function and eq as the key equality predicate, and inserts elements from [i, j) into it.
Average case (N is distance(i, j)), worst case
X(i, j, n, hf)
X a(i, j, n, hf);
X
Preconditions: key_­equal meets the Cpp17DefaultConstructible requirements.
value_­type is Cpp17EmplaceConstructible into X from *i.

Effects:  Constructs an empty container with at least n buckets, using hf as the hash function and key_­equal() as the key equality predicate, and inserts elements from [i, j) into it.
Average case (N is distance(i, j)), worst case
X(i, j, n)
X a(i, j, n);
X
Preconditions: hasher and key_­equal meet the Cpp17DefaultConstructible requirements.
value_­type is Cpp17EmplaceConstructible into X from *i.

Effects:  Constructs an empty container with at least n buckets, using hasher() as the hash function and key_­equal() as the key equality predicate, and inserts elements from [i, j) into it.
Average case (N is distance(i, j)), worst case
X(i, j)
X a(i, j);
X
Preconditions: hasher and key_­equal meet the Cpp17DefaultConstructible requirements.
value_­type is Cpp17EmplaceConstructible into X from *i.

Effects:  Constructs an empty container with an unspecified number of buckets, using hasher() as the hash function and key_­equal() as the key equality predicate, and inserts elements from [i, j) into it.
Average case (N is distance(i, j)), worst case
X(il)
X
Same as X(il.begin(), il.end()).
Same as X(il.begin(), il.end()).
X(il, n)
X
Same as X(il.begin(), il.end(), n).
Same as X(il.begin(), il.end(), n).
X(il, n, hf)
X
Same as X(il.begin(), il.end(), n, hf).
Same as X(il.begin(), il.end(), n, hf).
X(il, n, hf, eq)
X
Same as X(il.begin(), il.end(), n, hf, eq).
Same as X(il.begin(), il.end(), n, hf, eq).
X(b)
X a(b);
X
Copy constructor.
In addition to the requirements of Table 73, copies the hash function, predicate, and maximum load factor.
Average case linear in b.size(), worst case quadratic.
a = b
X&
Copy assignment operator.
In addition to the requirements of Table 73, copies the hash function, predicate, and maximum load factor.
Average case linear in b.size(), worst case quadratic.
a = il
X&
Preconditions: value_­type is Cpp17CopyInsertable into X and Cpp17CopyAssignable.

Effects:  Assigns the range [il.begin(), il.end()) into a.
All existing elements of a are either assigned to or destroyed.
Same as a = X(il).
b.hash_­function()
hasher
Returns: b's hash function.
constant
b.key_­eq()
key_­equal
Returns: b's key equality predicate.
constant
a_­uniq. emplace(args)
pair<iterator, bool>
Preconditions: value_­type is Cpp17EmplaceConstructible into X from args.

Effects:  Inserts a value_­type object t constructed with std​::​forward<​Args​>(​args)... if and only if there is no element in the container with key equivalent to the key of t.
The bool component of the returned pair is true if and only if the insertion takes place, and the iterator component of the pair points to the element with key equivalent to the key of t.
Average case , worst case .
a_­eq.emplace(args)
iterator
Preconditions: value_­type is Cpp17EmplaceConstructible into X from args.

Effects:  Inserts a value_­type object t constructed with std​::​forward<​Args>(​args)... and returns the iterator pointing to the newly inserted element.
Average case , worst case .
a.emplace_­hint(p, args)
iterator
Preconditions: value_­type is Cpp17EmplaceConstructible into X from args.

Effects:  Equivalent to a.emplace( std​::​forward<​Args>(​args)...).
Return value is an iterator pointing to the element with the key equivalent to the newly inserted element.
The const_­iterator p is a hint pointing to where the search should start.
Implementations are permitted to ignore the hint.
Average case , worst case .
a_­uniq.insert(t)
pair<iterator, bool>
Preconditions: If t is a non-const rvalue, value_­type is Cpp17MoveInsertable into X; otherwise, value_­type is Cpp17CopyInsertable into X.

Effects:  Inserts t if and only if there is no element in the container with key equivalent to the key of t.
The bool component of the returned pair indicates whether the insertion takes place, and the iterator component points to the element with key equivalent to the key of t.
Average case , worst case .
a_­eq.insert(t)
iterator
Preconditions: If t is a non-const rvalue, value_­type is Cpp17MoveInsertable into X; otherwise, value_­type is Cpp17CopyInsertable into X.

Effects:  Inserts t, and returns an iterator pointing to the newly inserted element.
Average case , worst case .
a.insert(p, t)
iterator
Preconditions: If t is a non-const rvalue, value_­type is Cpp17MoveInsertable into X; otherwise, value_­type is Cpp17CopyInsertable into X.

Effects: Equivalent to a.insert(t).
Return value is an iterator pointing to the element with the key equivalent to that of t.
The iterator p is a hint pointing to where the search should start.
Implementations are permitted to ignore the hint.
Average case , worst case .
a.insert(i, j)
void
Preconditions: value_­type is Cpp17EmplaceConstructible into X from *i.
Neither i nor j are iterators into a.

Effects: Equivalent to a.insert(t) for each element in [i,j).
Average case , where N is distance(i, j), worst case .
a.insert(il)
void
Same as a.insert(il.begin(), il.end()).
Same as a.insert( il.begin(), il.end()).
a_­uniq.
insert(nh)
insert_­return_­type
Preconditions: nh is empty or a_­uniq.get_­allocator() == nh.get_­allocator().

Effects: If nh is empty, has no effect.
Otherwise, inserts the element owned by nh if and only if there is no element in the container with a key equivalent to nh.key().

Postconditions: If nh is empty, inserted is false, position is end(), and node is empty.
Otherwise if the insertion took place, inserted is true, position points to the inserted element, and node is empty; if the insertion failed, inserted is false, node has the previous value of nh, and position points to an element with a key equivalent to nh.key().
Average case , worst case .
a_­eq.
insert(nh)
iterator
Preconditions: nh is empty or a_­eq.get_­allocator() == nh.get_­allocator().

Effects: If nh is empty, has no effect and returns a_­eq.end().
Otherwise, inserts the element owned by nh and returns an iterator pointing to the newly inserted element.

Postconditions: nh is empty.
Average case , worst case .
a.insert(q, nh)
iterator
Preconditions: nh is empty or a.get_­allocator() == nh.get_­allocator().

Effects: If nh is empty, has no effect and returns a.end().
Otherwise, inserts the element owned by nh if and only if there is no element with key equivalent to nh.key() in containers with unique keys; always inserts the element owned by nh in containers with equivalent keys.
Always returns the iterator pointing to the element with key equivalent to nh.key().
The iterator q is a hint pointing to where the search should start.
Implementations are permitted to ignore the hint.

Postconditions: nh is empty if insertion succeeds, unchanged if insertion fails.
Average case , worst case .
a.extract(k)
node_­type
Effects: Removes an element in the container with key equivalent to k.

Returns: A node_­type owning the element if found, otherwise an empty node_­type.
Average case , worst case .
a.extract(q)
node_­type
Effects: Removes the element pointed to by q.

Returns: A node_­type owning that element.
Average case , worst case .
a.merge(a2)
void
Preconditions: a.get_­allocator() == a2.get_­allocator().

Attempts to extract each element in a2 and insert it into a using the hash function and key equality predicate of a.
In containers with unique keys, if there is an element in a with key equivalent to the key of an element from a2, then that element is not extracted from a2.
Postconditions: Pointers and references to the transferred elements of a2 refer to those same elements but as members of a.
Iterators referring to the transferred elements and all iterators referring to a will be invalidated, but iterators to elements remaining in a2 will remain valid.
Average case , where N is a2.size(), worst case .
a.erase(k)
size_­type
Effects: Erases all elements with key equivalent to k.

Returns: The number of elements erased.
Average case , worst case .
a.erase(q)
iterator
Effects: Erases the element pointed to by q.

Returns: The iterator immediately following q prior to the erasure.
Average case , worst case .
a.erase(r)
iterator
Effects: Erases the element pointed to by r.

Returns: The iterator immediately following r prior to the erasure.
Average case , worst case .
a.erase(q1, q2)
iterator
Effects: Erases all elements in the range [q1, q2).

Returns: The iterator immediately following the erased elements prior to the erasure.
Average case linear in distance(q1, q2), worst case .
a.clear()
void
Effects: Erases all elements in the container.

Postconditions: a.empty() is true
Linear in a.size().
b.find(k)
iterator;
const_­iterator for const b.
Returns: An iterator pointing to an element with key equivalent to k, or b.end() if no such element exists.
Average case , worst case .
a_­tran.find(ke)
iterator;
const_­iterator for const a_­tran.
Returns: An iterator pointing to an element with key equivalent to ke, or a_­tran.end() if no such element exists.
Average case , worst case .
b.count(k)
size_­type
Returns: The number of elements with key equivalent to k.
Average case , worst case .
a_­tran.count(ke)
size_­type
Returns: The number of elements with key equivalent to ke.
Average case , worst case .
b.contains(k)
bool
Effects: Equivalent to b.find(k) != b.end()
Average case , worst case .
a_­tran.contains(ke)
bool
Effects: Equivalent to a_­tran.find(ke) != a_­tran.end()
Average case , worst case .
b.equal_­range(k)
pair<iterator, iterator>;
pair<const_­iterator, const_­iterator> for const b.
Returns: A range containing all elements with keys equivalent to k.
Returns make_­pair(b.end(), b.end()) if no such elements exist.
Average case , worst case .
a_­tran.equal_­range(ke)
pair<iterator, iterator>;
pair<const_­iterator, const_­iterator> for const a_­tran.
Returns: A range containing all elements with keys equivalent to ke.
Returns make_­pair(a_­tran.end(), a_­tran.end()) if no such elements exist.
Average case , worst case .
b.bucket_­count()
size_­type
Returns: The number of buckets that b contains.
Constant
b.max_­bucket_­count()
size_­type
Returns: An upper bound on the number of buckets that b can ever contain.
Constant
b.bucket(k)
size_­type
Preconditions: b.bucket_­count() > 0.

Returns: The index of the bucket in which elements with keys equivalent to k would be found, if any such element existed.

Postconditions: The return value shall be in the range [0, b.bucket_­count()).
Constant
b.bucket_­size(n)
size_­type
Preconditions: n shall be in the range [0, b.bucket_­count()).
Returns: The number of elements in the bucket.
b.begin(n)
local_­iterator;
const_­local_­iterator for const b.
Preconditions: n is in the range [0, b.bucket_­count()).

Returns: An iterator referring to the first element in the bucket.
If the bucket is empty, then b.begin(n) == b.end(n).
Constant
b.end(n)
local_­iterator;
const_­local_­iterator for const b.
Preconditions: n is in the range [0, b.bucket_­count()).

Returns: An iterator which is the past-the-end value for the bucket.
Constant
b.cbegin(n)
const_­local_­iterator
Preconditions: n shall be in the range [0, b.bucket_­count()).

Returns: An iterator referring to the first element in the bucket.
If the bucket is empty, then b.cbegin(n) == b.cend(n).
Constant
b.cend(n)
const_­local_­iterator
Preconditions: n is in the range [0, b.bucket_­count()).

Returns: An iterator which is the past-the-end value for the bucket.
Constant
b.load_­factor()
float
Returns: The average number of elements per bucket.
Constant
b.max_­load_­factor()
float
Returns: A positive number that the container attempts to keep the load factor less than or equal to.
The container automatically increases the number of buckets as necessary to keep the load factor below this number.
Constant
a.max_­load_­factor(z)
void
Preconditions: z is positive.
May change the container's maximum load factor, using z as a hint.
Constant
a.rehash(n)
void
Postconditions: a.bucket_­count() >= a.size() / a.max_­load_­factor() and a.bucket_­count() >= n.
Average case linear in a.size(), worst case quadratic.
a.reserve(n)
void
Same as a.rehash(ceil(n / a.max_­load_­factor())).
Average case linear in a.size(), worst case quadratic.
Two unordered containers a and b compare equal if a.size() == b.size() and, for every equivalent-key group [Ea1, Ea2) obtained from a.equal_­range(Ea1), there exists an equivalent-key group [Eb1, Eb2) obtained from b.equal_­range(Ea1), such that is_­permutation(Ea1, Ea2, Eb1, Eb2) returns true.
For unordered_­set and unordered_­map, the complexity of operator== (i.e., the number of calls to the == operator of the value_­type, to the predicate returned by key_­eq(), and to the hasher returned by hash_­function()) is proportional to N in the average case and to in the worst case, where N is a.size().
For unordered_­multiset and unordered_­multimap, the complexity of operator== is proportional to in the average case and to in the worst case, where N is a.size(), and is the size of the equivalent-key group in a.
However, if the respective elements of each corresponding pair of equivalent-key groups and are arranged in the same order (as is commonly the case, e.g., if a and b are unmodified copies of the same container), then the average-case complexity for unordered_­multiset and unordered_­multimap becomes proportional to N (but worst-case complexity remains , e.g., for a pathologically bad hash function).
The behavior of a program that uses operator== or operator!= on unordered containers is undefined unless the Pred function object has the same behavior for both containers and the equality comparison function for Key is a refinement230 of the partition into equivalent-key groups produced by Pred.
The iterator types iterator and const_­iterator of an unordered associative container are of at least the forward iterator category.
For unordered associative containers where the key type and value type are the same, both iterator and const_­iterator are constant iterators.
The insert and emplace members shall not affect the validity of references to container elements, but may invalidate all iterators to the container.
The erase members shall invalidate only iterators and references to the erased elements, and preserve the relative order of the elements that are not erased.
The insert and emplace members shall not affect the validity of iterators if (N+n) <= z * B, where N is the number of elements in the container prior to the insert operation, n is the number of elements inserted, B is the container's bucket count, and z is the container's maximum load factor.
The extract members invalidate only iterators to the removed element, and preserve the relative order of the elements that are not erased; pointers and references to the removed element remain valid.
However, accessing the element through such pointers and references while the element is owned by a node_­type is undefined behavior.
References and pointers to an element obtained while it is owned by a node_­type are invalidated if the element is successfully inserted.
The member function templates find, count, equal_­range, and contains shall not participate in overload resolution unless the qualified-ids Pred​::​is_­transparent and Hash​::​is_­transparent are both valid and denote types ([temp.deduct]).
A deduction guide for an unordered associative container shall not participate in overload resolution if any of the following are true:
  • It has an InputIterator template parameter and a type that does not qualify as an input iterator is deduced for that parameter.
  • It has an Allocator template parameter and a type that does not qualify as an allocator is deduced for that parameter.
  • It has a Hash template parameter and an integral type or a type that qualifies as an allocator is deduced for that parameter.
  • It has a Pred template parameter and a type that qualifies as an allocator is deduced for that parameter.
Equality comparison is a refinement of partitioning if no two objects that compare equal fall into different partitions.
 

22.2.7.2 Exception safety guarantees [unord.req.except]

For unordered associative containers, no clear() function throws an exception.
erase(k) does not throw an exception unless that exception is thrown by the container's Hash or Pred object (if any).
For unordered associative containers, if an exception is thrown by any operation other than the container's hash function from within an insert or emplace function inserting a single element, the insertion has no effect.
For unordered associative containers, no swap function throws an exception unless that exception is thrown by the swap of the container's Hash or Pred object (if any).
For unordered associative containers, if an exception is thrown from within a rehash() function other than by the container's hash function or comparison function, the rehash() function has no effect.