22 Containers library [containers]

22.2 Container requirements [container.requirements]

22.2.1 General container requirements [container.requirements.general]

Containers are objects that store other objects.
They control allocation and deallocation of these objects through constructors, destructors, insert and erase operations.
All of the complexity requirements in this Clause are stated solely in terms of the number of operations on the contained objects.
[Example 1:
The copy constructor of type vector<vector<int>> has linear complexity, even though the complexity of copying each contained vector<int> is itself linear.
— end example]
For the components affected by this subclause that declare an allocator_­type, objects stored in these components shall be constructed using the function allocator_­traits<allocator_­type>​::​rebind_­traits<U>​::​​construct and destroyed using the function allocator_­traits<allocator_­type>​::​rebind_­traits<U>​::​​destroy, where U is either allocator_­type​::​value_­type or an internal type used by the container.
These functions are called only for the container's element type, not for internal types used by the container.
[Note 1:
This means, for example, that a node-based container might need to construct nodes containing aligned buffers and call construct to place the element into the buffer.
— end note]
In Tables 73, 74, and 75 X denotes a container class containing objects of type T, a and b denote values of type X, i and j denote values of type (possibly const) X​::​iterator, u denotes an identifier, r denotes a non-const value of type X, and rv denotes a non-const rvalue of type X.
Table 73: Container requirements [tab:container.req]
Expression
Return type
Operational
Assertion/note
Complexity
semantics
pre-/post-condition
X​::​value_­type
T
Preconditions: T is Cpp17Erasable from X (see [container.requirements.general], below)
compile time
X​::​reference
T&
compile time
X​::​const_­reference
const T&
compile time
X​::​iterator
iterator type whose value type is T
any iterator category that meets the forward iterator requirements.
convertible to X​::​const_­iterator.
compile time
X​::​const_­iterator
constant iterator type whose value type is T
any iterator category that meets the forward iterator requirements.
compile time
X​::​difference_­type
signed integer type
is identical to the difference type of X​::​iterator and X​::​const_­iterator
compile time
X​::​size_­type
unsigned integer type
size_­type can represent any non-negative value of difference_­type
compile time
X u;
Postconditions: u.empty()
constant
X()
Postconditions: X().empty()
constant
X(a)
Preconditions: T is Cpp17CopyInsertable into X (see below).

Postconditions: a == X(a).
linear
X u(a);
X u = a;
Preconditions: T is Cpp17CopyInsertable into X (see below).

Postconditions: u == a
linear
X u(rv);
X u = rv;
Postconditions: u is equal to the value that rv had before this construction
(Note B)
a = rv
X&
All existing elements of a are either move assigned to or destroyed
Postconditions: a is equal to the value that rv had before this assignment
linear
a.~X()
void
Effects: destroys every element of a; any memory obtained is deallocated.
linear
a.begin()
iterator; const_­iterator for constant a
constant
a.end()
iterator; const_­iterator for constant a
constant
a.cbegin()
const_­iterator
const_­cast<​X const&>(a).begin();
constant
a.cend()
const_­iterator
const_­cast<​X const&>(a).end();
constant
i <=> j
strong_­ordering
Constraints: X​::​iterator meets the random access iterator requirements.
constant
a == b
convertible to bool
== is an equivalence relation.
equal(​a.begin(), a.end(), b.begin(), b.end())
Preconditions: T meets the Cpp17EqualityComparable requirements
Constant if a.size() != b.size(), linear otherwise
a != b
convertible to bool
Equivalent to !(a == b)
linear
a.swap(b)
void
Effects: exchanges the contents of a and b
(Note A)
swap(a, b)
void
Equivalent to a.swap(b)
(Note A)
r = a
X&
Postconditions: r == a.
linear
a.size()
size_­type
distance(​a.begin(), a.end())
constant
a.max_­size()
size_­type
distance(​begin(), end()) for the largest possible container
constant
a.empty()
convertible to bool
a.begin() == a.end()
constant
Those entries marked “(Note A)” or “(Note B)” have linear complexity for array and have constant complexity for all other standard containers.
[Note 2:
The algorithm equal is defined in [algorithms].
— end note]
The member function size() returns the number of elements in the container.
The number of elements is defined by the rules of constructors, inserts, and erases.
begin() returns an iterator referring to the first element in the container.
end() returns an iterator which is the past-the-end value for the container.
If the container is empty, then begin() == end().
In the expressions i == j i != j i < j i <= j i >= j i > j i <=> j i - j where i and j denote objects of a container's iterator type, either or both may be replaced by an object of the container's const_­iterator type referring to the same element with no change in semantics.
Unless otherwise specified, all containers defined in this Clause obtain memory using an allocator (see [allocator.requirements]).
[Note 3:
In particular, containers and iterators do not store references to allocated elements other than through the allocator's pointer type, i.e., as objects of type P or pointer_­traits<P>​::​template rebind<unspecified>, where P is allocator_­traits<allocator_­type>​::​pointer.
— end note]
Copy constructors for these container types obtain an allocator by calling allocator_­traits<allocator_­type>​::​select_­on_­container_­copy_­construction on the allocator belonging to the container being copied.
Move constructors obtain an allocator by move construction from the allocator belonging to the container being moved.
Such move construction of the allocator shall not exit via an exception.
All other constructors for these container types take a const allocator_­type& argument.
[Note 4:
If an invocation of a constructor uses the default value of an optional allocator argument, then the allocator type must support value-initialization.
— end note]
A copy of this allocator is used for any memory allocation and element construction performed, by these constructors and by all member functions, during the lifetime of each container object or until the allocator is replaced.
The allocator may be replaced only via assignment or swap().
Allocator replacement is performed by copy assignment, move assignment, or swapping of the allocator only if
  • allocator_­traits<allocator_­type>​::​propagate_­on_­container_­copy_­assignment​::​value,
  • allocator_­traits<allocator_­type>​::​propagate_­on_­container_­move_­assignment​::​value, or
  • allocator_­traits<allocator_­type>​::​propagate_­on_­container_­swap​::​value
is true within the implementation of the corresponding container operation.
In all container types defined in this Clause, the member get_­allocator() returns a copy of the allocator used to construct the container or, if that allocator has been replaced, a copy of the most recent replacement.
The expression a.swap(b), for containers a and b of a standard container type other than array, shall exchange the values of a and b without invoking any move, copy, or swap operations on the individual container elements.
Lvalues of any Compare, Pred, or Hash types belonging to a and b shall be swappable and shall be exchanged by calling swap as described in [swappable.requirements].
If allocator_­traits<allocator_­type>​::​propagate_­on_­container_­swap​::​value is true, then lvalues of type allocator_­type shall be swappable and the allocators of a and b shall also be exchanged by calling swap as described in [swappable.requirements].
Otherwise, the allocators shall not be swapped, and the behavior is undefined unless a.get_­allocator() == b.get_­allocator().
Every iterator referring to an element in one container before the swap shall refer to the same element in the other container after the swap.
It is unspecified whether an iterator with value a.end() before the swap will have value b.end() after the swap.
If the iterator type of a container belongs to the bidirectional or random access iterator categories, the container is called reversible and meets the additional requirements in Table 74.
Table 74: Reversible container requirements [tab:container.rev.req]
Expression
Return type
Assertion/note
Complexity
pre-/post-condition
X​::​reverse_­iterator
iterator type whose value type is T
reverse_­iterator<iterator>
compile time
X​::​const_­reverse_­iterator
constant iterator type whose value type is T
reverse_­iterator<const_­iterator>
compile time
a.rbegin()
reverse_­iterator; const_­reverse_­iterator for constant a
reverse_­iterator(end())
constant
a.rend()
reverse_­iterator; const_­reverse_­iterator for constant a
reverse_­iterator(begin())
constant
a.crbegin()
const_­reverse_­iterator
const_­cast<X const&>(a).rbegin()
constant
a.crend()
const_­reverse_­iterator
const_­cast<X const&>(a).rend()
constant
Unless otherwise specified (see [associative.reqmts.except], [unord.req.except], [deque.modifiers], and [vector.modifiers]) all container types defined in this Clause meet the following additional requirements:
  • if an exception is thrown by an insert() or emplace() function while inserting a single element, that function has no effects.
  • if an exception is thrown by a push_­back(), push_­front(), emplace_­back(), or emplace_­front() function, that function has no effects.
  • no erase(), clear(), pop_­back() or pop_­front() function throws an exception.
  • no copy constructor or assignment operator of a returned iterator throws an exception.
  • no swap() function throws an exception.
  • no swap() function invalidates any references, pointers, or iterators referring to the elements of the containers being swapped.
    [Note 5:
    The end() iterator does not refer to any element, so it can be invalidated.
    — end note]
Unless otherwise specified (either explicitly or by defining a function in terms of other functions), invoking a container member function or passing a container as an argument to a library function shall not invalidate iterators to, or change the values of, objects within that container.
A contiguous container is a container whose member types iterator and const_­iterator meet the Cpp17RandomAccessIterator requirements ([random.access.iterators]) and model contiguous_­iterator ([iterator.concept.contiguous]).
Table 75 lists operations that are provided for some types of containers but not others.
Those containers for which the listed operations are provided shall implement the semantics described in Table 75 unless otherwise stated.
If the iterators passed to lexicographical_­compare_­three_­way meet the constexpr iterator requirements ([iterator.requirements.general]) then the operations described in Table 75 are implemented by constexpr functions.
Table 75: Optional container operations [tab:container.opt]
Expression
Return type
Operational
Assertion/note
Complexity
semantics
pre-/post-condition
a <=> b
synth-three-​way-result<value_­type>
lexicographical_­compare_­three_­way(a.begin(), a.end(), b.begin(), b.end(), synth-three-way)
Preconditions: Either <=> is defined for values of type (possibly const) T, or < is defined for values of type (possibly const) T and < is a total ordering relationship.
linear
[Note 6:
The algorithm lexicographical_­compare_­three_­way is defined in [algorithms].
— end note]
All of the containers defined in this Clause and in [basic.string] except array meet the additional requirements of an allocator-aware container, as described in Table 76.
Given an allocator type A and given a container type X having a value_­type identical to T and an allocator_­type identical to allocator_­traits<A>​::​rebind_­alloc<T> and given an lvalue m of type A, a pointer p of type T*, an expression v of type (possibly const) T, and an rvalue rv of type T, the following terms are defined.
If X is not allocator-aware, the terms below are defined as if A were allocator<T> — no allocator object needs to be created and user specializations of allocator<T> are not instantiated:
  • T is Cpp17DefaultInsertable into X means that the following expression is well-formed: allocator_traits<A>::construct(m, p)
  • An element of X is default-inserted if it is initialized by evaluation of the expression allocator_traits<A>::construct(m, p) where p is the address of the uninitialized storage for the element allocated within X.
  • T is Cpp17MoveInsertable into X means that the following expression is well-formed: allocator_traits<A>::construct(m, p, rv) and its evaluation causes the following postcondition to hold: The value of *p is equivalent to the value of rv before the evaluation.
    [Note 7:
    rv remains a valid object.
    Its state is unspecified
    — end note]
  • T is Cpp17CopyInsertable into X means that, in addition to T being Cpp17MoveInsertable into X, the following expression is well-formed: allocator_traits<A>::construct(m, p, v) and its evaluation causes the following postcondition to hold: The value of v is unchanged and is equivalent to *p.
  • T is Cpp17EmplaceConstructible into X from args, for zero or more arguments args, means that the following expression is well-formed: allocator_traits<A>::construct(m, p, args)
  • T is Cpp17Erasable from X means that the following expression is well-formed: allocator_traits<A>::destroy(m, p)
[Note 8:
A container calls allocator_­traits<A>​::​construct(m, p, args) to construct an element at p using args, with m == get_­allocator().
The default construct in allocator will call ​::​new((void*)p) T(args), but specialized allocators can choose a different definition.
— end note]
In Table 76, X denotes an allocator-aware container class with a value_­type of T using allocator of type A, u denotes a variable, a and b denote non-const lvalues of type X, t denotes an lvalue or a const rvalue of type X, rv denotes a non-const rvalue of type X, and m is a value of type A.
Table 76: Allocator-aware container requirements [tab:container.alloc.req]
Expression
Return type
Assertion/note
Complexity
pre-/post-condition
allocator_­type
A
Mandates: allocator_­type​::​value_­type is the same as X​::​value_­type.
compile time
get_­- allocator()
A
constant
X()
X u;
Preconditions: A meets the Cpp17DefaultConstructible requirements.

Postconditions: u.empty() returns true, u.get_­allocator() == A()
constant
X(m)
Postconditions: u.empty() returns true,
constant
X u(m);
u.get_­allocator() == m
X(t, m)
X u(t, m);
Preconditions: T is Cpp17CopyInsertable into X.

Postconditions: u == t, u.get_­allocator() == m
linear
X(rv)
X u(rv);
Postconditions: u has the same elements as rv had before this construction; the value of u.get_­allocator() is the same as the value of rv.get_­allocator() before this construction.
constant
X(rv, m)
X u(rv, m);
Preconditions: T is Cpp17MoveInsertable into X.

Postconditions: u has the same elements, or copies of the elements, that rv had before this construction, u.get_­allocator() == m
constant if m == rv.get_­allocator(), otherwise linear
a = t
X&
Preconditions: T is Cpp17CopyInsertable into X and Cpp17CopyAssignable.

Postconditions: a == t
linear
a = rv
X&
Preconditions: If allocator_­-
traits<allocator_­type>
​::​propagate_­on_­container_­-
move_­assignment​::​value is
false, T is Cpp17MoveInsertable into X and Cpp17MoveAssignable.

Effects: All existing elements of a are either move assigned to or destroyed.

Postconditions: a is equal to the value that rv had before this assignment.
linear
a.swap(b)
void
Effects: exchanges the contents of a and b
constant
The behavior of certain container member functions and deduction guides depends on whether types qualify as input iterators or allocators.
The extent to which an implementation determines that a type cannot be an input iterator is unspecified, except that as a minimum integral types shall not qualify as input iterators.
Likewise, the extent to which an implementation determines that a type cannot be an allocator is unspecified, except that as a minimum a type A shall not qualify as an allocator unless it meets both of the following conditions:
  • The qualified-id A​::​value_­type is valid and denotes a type ([temp.deduct]).
  • The expression declval<A&>().allocate(size_­t{}) is well-formed when treated as an unevaluated operand.

22.2.2 Container data races [container.requirements.dataraces]

For purposes of avoiding data races, implementations shall consider the following functions to be const: begin, end, rbegin, rend, front, back, data, find, lower_­bound, upper_­bound, equal_­range, at and, except in associative or unordered associative containers, operator[].
Notwithstanding [res.on.data.races], implementations are required to avoid data races when the contents of the contained object in different elements in the same container, excepting vector<bool>, are modified concurrently.
[Note 1:
For a vector<int> x with a size greater than one, x[1] = 5 and *x.begin() = 10 can be executed concurrently without a data race, but x[0] = 5 and *x.begin() = 10 executed concurrently can result in a data race.
As an exception to the general rule, for a vector<bool> y, y[0] = true can race with y[1] = true.
— end note]

22.2.3 Sequence containers [sequence.reqmts]

A sequence container organizes a finite set of objects, all of the same type, into a strictly linear arrangement.
The library provides four basic kinds of sequence containers: vector, forward_­list, list, and deque.
In addition, array is provided as a sequence container which provides limited sequence operations because it has a fixed number of elements.
The library also provides container adaptors that make it easy to construct abstract data types, such as stacks or queues, out of the basic sequence container kinds (or out of other kinds of sequence containers that the user defines).
[Note 1:
The sequence containers offer the programmer different complexity trade-offs.
vector is appropriate in most circumstances.
array has a fixed size known during translation.
list or forward_­list support frequent insertions and deletions from the middle of the sequence.
deque supports efficient insertions and deletions taking place at the beginning or at the end of the sequence.
When choosing a container, remember vector is best; leave a comment to explain if you choose from the rest!
— end note]
In Tables 77 and 78, X denotes a sequence container class, a denotes a value of type X containing elements of type T, u denotes the name of a variable being declared, A denotes X​::​allocator_­type if the qualified-id X​::​allocator_­type is valid and denotes a type ([temp.deduct]) and allocator<T> if it doesn't, i and j denote iterators that meet the Cpp17InputIterator requirements and refer to elements implicitly convertible to value_­type, [i, j) denotes a valid range, il designates an object of type initializer_­list<value_­type>, n denotes a value of type X​::​size_­type, p denotes a valid constant iterator to a, q denotes a valid dereferenceable constant iterator to a, [q1, q2) denotes a valid range of constant iterators in a, t denotes an lvalue or a const rvalue of X​::​value_­type, and rv denotes a non-const rvalue of X​::​value_­type.
Args denotes a template parameter pack; args denotes a function parameter pack with the pattern Args&&.
The complexities of the expressions are sequence dependent.
Table 77: Sequence container requirements (in addition to container) [tab:container.seq.req]
Expression
Return type
Assertion/note
pre-/post-condition
X(n, t)
X u(n, t);
Preconditions: T is Cpp17CopyInsertable into X.

Postconditions: distance(begin(), end()) == n
Effects: Constructs a sequence container with n copies of t
X(i, j)
X u(i, j);
Preconditions: T is Cpp17EmplaceConstructible into X from *i.
For vector, if the iterator does not meet the Cpp17ForwardIterator requirements ([forward.iterators]), T is also Cpp17MoveInsertable into X.

Postconditions: distance(begin(), end()) == distance(i, j)
Effects: Constructs a sequence container equal to the range [i, j).
Each iterator in the range [i, j) is dereferenced exactly once.
X(il)
Equivalent to X(il.begin(), il.end())
a = il
X&
Preconditions: T 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.

Returns:  *this.
a.emplace(p, args)
iterator
Preconditions: T is Cpp17EmplaceConstructible into X from args.
For vector and deque, T is also Cpp17MoveInsertable into X and Cpp17MoveAssignable.

Effects: Inserts an object of type T constructed with std​::​forward<​Args​>(​args)... before p.
[Note 2:
args can directly or indirectly refer to a value in a.
— end note]
a.insert(p,t)
iterator
Preconditions: T is Cpp17CopyInsertable into X.
For vector and deque, T is also Cpp17CopyAssignable.

Effects:  Inserts a copy of t before p.
a.insert(p,rv)
iterator
Preconditions: T is Cpp17MoveInsertable into X.
For vector and deque, T is also Cpp17MoveAssignable.

Effects:  Inserts a copy of rv before p.
a.insert(p,n,t)
iterator
Preconditions: T is Cpp17CopyInsertable into X and Cpp17CopyAssignable.

Effects: Inserts n copies of t before p.
a.insert(p,i,j)
iterator
Preconditions: T is Cpp17EmplaceConstructible into X from *i.
For vector and deque, T is also Cpp17MoveInsertable into X, Cpp17MoveConstructible, Cpp17MoveAssignable, and swappable ([swappable.requirements]).
Neither i nor j are iterators into a.

Effects: Inserts copies of elements in [i, j) before p.
Each iterator in the range [i, j) shall be dereferenced exactly once.
a.insert(p, il)
iterator
a.insert(p, il.begin(), il.end()).
a.erase(q)
iterator
Preconditions: For vector and deque, T is Cpp17MoveAssignable.

Effects:  Erases the element pointed to by q.
a.erase(q1,q2)
iterator
Preconditions: For vector and deque, T is Cpp17MoveAssignable.

Effects:  Erases the elements in the range [q1, q2).
a.clear()
void
Effects: Destroys all elements in a.
Invalidates all references, pointers, and iterators referring to the elements of a and may invalidate the past-the-end iterator.

Postconditions: a.empty() is true.

Complexity: Linear.
a.assign(i,j)
void
Preconditions: T is Cpp17EmplaceConstructible into X from *i and assignable from *i.
For vector, if the iterator does not meet the forward iterator requirements ([forward.iterators]), T is also Cpp17MoveInsertable into X.
Neither i nor j are iterators into a.

Effects: Replaces elements in a with a copy of [i, j).
Invalidates all references, pointers and iterators referring to the elements of a.
For vector and deque, also invalidates the past-the-end iterator.
Each iterator in the range [i, j) shall be dereferenced exactly once.
a.assign(il)
void
a.assign(il.begin(), il.end()).
a.assign(n,t)
void
Preconditions: T is Cpp17CopyInsertable into X and Cpp17CopyAssignable.
t is not a reference into a.

Effects: Replaces elements in a with n copies of t.
Invalidates all references, pointers and iterators referring to the elements of a.
For vector and deque, also invalidates the past-the-end iterator.
The iterator returned from a.insert(p, t) points to the copy of t inserted into a.
The iterator returned from a.insert(p, rv) points to the copy of rv inserted into a.
The iterator returned from a.insert(p, n, t) points to the copy of the first element inserted into a, or p if n == 0.
The iterator returned from a.insert(p, i, j) points to the copy of the first element inserted into a, or p if i == j.
The iterator returned from a.insert(p, il) points to the copy of the first element inserted into a, or p if il is empty.
The iterator returned from a.emplace(p, args) points to the new element constructed from args into a.
The iterator returned from a.erase(q) points to the element immediately following q prior to the element being erased.
If no such element exists, a.end() is returned.
The iterator returned by a.erase(q1, q2) points to the element pointed to by q2 prior to any elements being erased.
If no such element exists, a.end() is returned.
For every sequence container defined in this Clause and in [strings]:
  • If the constructor template<class InputIterator> X(InputIterator first, InputIterator last, const allocator_type& alloc = allocator_type()); is called with a type InputIterator that does not qualify as an input iterator, then the constructor shall not participate in overload resolution.
  • If the member functions of the forms: template<class InputIterator> return-type F(const_iterator p, InputIterator first, InputIterator last); // such as insert template<class InputIterator> return-type F(InputIterator first, InputIterator last); // such as append, assign template<class InputIterator> return-type F(const_iterator i1, const_iterator i2, InputIterator first, InputIterator last); // such as replace are called with a type InputIterator that does not qualify as an input iterator, then these functions shall not participate in overload resolution.
  • A deduction guide for a sequence container shall not participate in overload resolution if it has an InputIterator template parameter and a type that does not qualify as an input iterator is deduced for that parameter, or if it has an Allocator template parameter and a type that does not qualify as an allocator is deduced for that parameter.
Table 78 lists operations that are provided for some types of sequence containers but not others.
An implementation shall provide these operations for all container types shown in the “container” column, and shall implement them so as to take amortized constant time.
Table 78: Optional sequence container operations [tab:container.seq.opt]
Expression
Return type
Operational semantics
Container
a.front()
reference; const_­reference for constant a
*a.begin()
basic_­string, array, deque, forward_­list, list, vector
a.back()
reference; const_­reference for constant a
{ auto tmp = a.end();
--tmp;
return *tmp; }
basic_­string, array, deque, list, vector
a.emplace_­front(args)
reference
Effects: Prepends an object of type T constructed with std​::​forward<​Args​>(​args)....

Preconditions: T is Cpp17EmplaceConstructible into X from args.

Returns: a.front().
deque, forward_­list, list
a.emplace_­back(args)
reference
Effects: Appends an object of type T constructed with std​::​forward<​Args​>(​args)....

Preconditions: T is Cpp17EmplaceConstructible into X from args.
For vector, T is also Cpp17MoveInsertable into X.
Returns: a.back().
deque, list, vector
a.push_­front(t)
void
Effects: Prepends a copy of t.

Preconditions: T is Cpp17CopyInsertable into X.
deque, forward_­list, list
a.push_­front(rv)
void
Effects: Prepends a copy of rv.

Preconditions: T is Cpp17MoveInsertable into X.
deque, forward_­list, list
a.push_­back(t)
void
Effects: Appends a copy of t.

Preconditions: T is Cpp17CopyInsertable into X.
basic_­string, deque, list, vector
a.push_­back(rv)
void
Effects: Appends a copy of rv.

Preconditions: T is Cpp17MoveInsertable into X.
basic_­string, deque, list, vector
a.pop_­front()
void
Effects: Destroys the first element.

Preconditions: a.empty() is false.
deque, forward_­list, list
a.pop_­back()
void
Effects: Destroys the last element.

Preconditions: a.empty() is false.
basic_­string, deque, list, vector
a[n]
reference; const_­reference for constant a
*(a.begin() + n)
basic_­string, array, deque, vector
a.at(n)
reference; const_­reference for constant a
*(a.begin() + n)
basic_­string, array, deque, vector
The member function at() provides bounds-checked access to container elements.
at() throws out_­of_­range if n >= a.size().

22.2.4 Node handles [container.node]

22.2.4.1 Overview [container.node.overview]

A node handle is an object that accepts ownership of a single element from an associative container ([associative.reqmts]) or an unordered associative container ([unord.req]).
It may be used to transfer that ownership to another container with compatible nodes.
Containers with compatible nodes have the same node handle type.
Elements may be transferred in either direction between container types in the same row of Table 79.
Table 79: Container types with compatible nodes [tab:container.node.compat]
map<K, T, C1, A>
map<K, T, C2, A>
map<K, T, C1, A>
multimap<K, T, C2, A>
set<K, C1, A>
set<K, C2, A>
set<K, C1, A>
multiset<K, C2, A>
unordered_­map<K, T, H1, E1, A>
unordered_­map<K, T, H2, E2, A>
unordered_­map<K, T, H1, E1, A>
unordered_­multimap<K, T, H2, E2, A>
unordered_­set<K, H1, E1, A>
unordered_­set<K, H2, E2, A>
unordered_­set<K, H1, E1, A>
unordered_­multiset<K, H2, E2, A>
If a node handle is not empty, then it contains an allocator that is equal to the allocator of the container when the element was extracted.
If a node handle is empty, it contains no allocator.
Class node-handle is for exposition only.
If a user-defined specialization of pair exists for pair<const Key, T> or pair<Key, T>, where Key is the container's key_­type and T is the container's mapped_­type, the behavior of operations involving node handles is undefined.
template<unspecified> class node-handle { public: // These type declarations are described in Tables 80 and 81. using value_type = see below; // not present for map containers using key_type = see below; // not present for set containers using mapped_type = see below; // not present for set containers using allocator_type = see below; private: using container_node_type = unspecified; using ator_traits = allocator_traits<allocator_type>; typename ator_traits::template rebind_traits<container_node_type>::pointer ptr_; optional<allocator_type> alloc_; public: // [container.node.cons], constructors, copy, and assignment constexpr node-handle() noexcept : ptr_(), alloc_() {} node-handle(node-handle&&) noexcept; node-handle& operator=(node-handle&&); // [container.node.dtor], destructor ~node-handle(); // [container.node.observers], observers value_type& value() const; // not present for map containers key_type& key() const; // not present for set containers mapped_type& mapped() const; // not present for set containers allocator_type get_allocator() const; explicit operator bool() const noexcept; [[nodiscard]] bool empty() const noexcept; // [container.node.modifiers], modifiers void swap(node-handle&) noexcept(ator_traits::propagate_on_container_swap::value || ator_traits::is_always_equal::value); friend void swap(node-handle& x, node-handle& y) noexcept(noexcept(x.swap(y))) { x.swap(y); } };

22.2.4.2 Constructors, copy, and assignment [container.node.cons]

node-handle(node-handle&& nh) noexcept;
Effects: Constructs a node-handle object initializing ptr_­ with nh.ptr_­.
Move constructs alloc_­ with nh.alloc_­.
Assigns nullptr to nh.ptr_­ and assigns nullopt to nh.alloc_­.
node-handle& operator=(node-handle&& nh);
Preconditions: Either !alloc_­, or ator_­traits​::​propagate_­on_­container_­move_­assignment​::​value is true, or alloc_­ == nh.alloc_­.
Effects:
  • If ptr_­ != nullptr, destroys the value_­type subobject in the container_­node_­type object pointed to by ptr_­ by calling ator_­traits​::​destroy, then deallocates ptr_­ by calling ator_­traits​::​template rebind_­traits<container_­node_­type>​::​deallocate.
  • Assigns nh.ptr_­ to ptr_­.
  • If !alloc_­ or ator_­traits​::​propagate_­on_­container_­move_­assignment​::​value is true,
    move assigns nh.alloc_­ to alloc_­.
  • Assigns nullptr to nh.ptr_­ and assigns nullopt to nh.alloc_­.
Returns: *this.
Throws: Nothing.

22.2.4.3 Destructor [container.node.dtor]

~node-handle();
Effects: If ptr_­ != nullptr, destroys the value_­type subobject in the container_­node_­type object pointed to by ptr_­ by calling ator_­traits​::​destroy, then deallocates ptr_­ by calling ator_­traits​::​template rebind_­traits<container_­node_­type>​::​deallocate.

22.2.4.4 Observers [container.node.observers]

value_type& value() const;
Preconditions: empty() == false.
Returns: A reference to the value_­type subobject in the container_­node_­type object pointed to by ptr_­.
Throws: Nothing.
key_type& key() const;
Preconditions: empty() == false.
Returns: A non-const reference to the key_­type member of the value_­type subobject in the container_­node_­type object pointed to by ptr_­.
Throws: Nothing.
Remarks: Modifying the key through the returned reference is permitted.
mapped_type& mapped() const;
Preconditions: empty() == false.
Returns: A reference to the mapped_­type member of the value_­type subobject in the container_­node_­type object pointed to by ptr_­.
Throws: Nothing.
allocator_type get_allocator() const;
Preconditions: empty() == false.
Returns: *alloc_­.
Throws: Nothing.
explicit operator bool() const noexcept;
Returns: ptr_­ != nullptr.
[[nodiscard]] bool empty() const noexcept;
Returns: ptr_­ == nullptr.

22.2.4.5 Modifiers [container.node.modifiers]

void swap(node-handle& nh) noexcept(ator_traits::propagate_on_container_swap::value || ator_traits::is_always_equal::value);
Preconditions: !alloc_­, or !nh.alloc_­, or ator_­traits​::​propagate_­on_­container_­swap​::​value is true, or alloc_­ == nh.alloc_­.
Effects: Calls swap(ptr_­, nh.ptr_­).
If !alloc_­, or !nh.alloc_­, or ator_­traits​::​propagate_­on_­container_­swap​::​value is true calls swap(alloc_­, nh.alloc_­).

22.2.5 Insert return type [container.insert.return]

The associative containers with unique keys and the unordered containers with unique keys have a member function insert that returns a nested type insert_­return_­type.
That return type is a specialization of the template specified in this subclause.
template<class Iterator, class NodeType> struct insert-return-type { Iterator position; bool inserted; NodeType node; };
The name insert-return-type is exposition only.
insert-return-type has the template parameters, data members, and special members specified above.
It has no base classes or members other than those specified.

22.2.6 Associative containers [associative.reqmts]

22.2.6.1 General [associative.reqmts.general]

Associative containers provide fast retrieval of data based on keys.
The library provides four basic kinds of associative containers: set, multiset, map and multimap.
Each associative container is parameterized on Key and an ordering relation Compare that induces a strict weak ordering on elements of Key.
In addition, map and multimap associate an arbitrary mapped type T with the Key.
The object of type Compare is called the comparison object of a container.
The phrase “equivalence of keys” means the equivalence relation imposed by the comparison object.
That is, two keys k1 and k2 are considered to be equivalent if for the comparison object comp, comp(k1, k2) == false && comp(k2, k1) == false.
[Note 1:
This is not necessarily the same as the result of k1 == k2.
— end note]
For any two keys k1 and k2 in the same container, calling comp(k1, k2) shall always return the same value.
An associative container supports unique keys if it may contain at most one element for each key.
Otherwise, it supports equivalent keys.
The set and map classes support unique keys; the multiset and multimap classes support equivalent keys.
For multiset and multimap, insert, emplace, and erase preserve the relative ordering of equivalent elements.
For set and multiset the value type is the same as the key type.
For map and multimap it is equal to pair<const Key, T>.
iterator of an associative container is of the bidirectional iterator category.
For associative 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 associative containers meet all the requirements of Allocator-aware containers, except that for map and multimap, the requirements placed on value_­type in Table 76 apply instead to key_­type and mapped_­type.
[Note 3:
For example, in some cases key_­type and mapped_­type are required to be Cpp17CopyAssignable even though the associated value_­type, pair<const key_­type, mapped_­type>, is not Cpp17CopyAssignable.
— end note]
In Table 80, X denotes an 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, u denotes the name of a variable being declared, a_­uniq denotes a value of type X when X supports unique keys, a_­eq denotes a value of type X when X supports multiple keys, a_­tran denotes a possibly const value of type X when the qualified-id X​::​key_­compare​::​is_­transparent is valid and denotes a type ([temp.deduct]), i and j meet the Cpp17InputIterator requirements and refer to elements implicitly convertible to value_­type, [i, j) denotes a valid range, p denotes a valid constant iterator to a, q denotes a valid dereferenceable constant iterator to a, r denotes a valid dereferenceable iterator to a, [q1, q2) denotes a valid range of constant iterators in a, il designates an object of type initializer_­list<value_­type>, t denotes a value of type X​::​value_­type, k denotes a value of type X​::​key_­type and c denotes a possibly const value of type X​::​key_­compare; kl is a value such that a is partitioned ([alg.sorting]) with respect to c(r, kl), with r the key value of e and e in a; ku is a value such that a is partitioned with respect to !c(ku, r); ke is a value such that a is partitioned with respect to c(r, ke) and !c(ke, r), with c(r, ke) implying !c(ke, r).
A denotes the storage allocator used by X, if any, or allocator<X​::​value_­type> otherwise, m denotes an allocator of a type convertible to A, and nh denotes a non-const rvalue of type X​::​node_­type.
Table 80: Associative container requirements (in addition to container) [tab:container.assoc.req]
Expression
Return type
Assertion/note
Complexity
pre-/post-condition
X​::​key_­type
Key
compile time
X​::​mapped_­type (map and multimap only)
T
compile time
X​::​value_­type (set and multiset only)
Key
Preconditions: value_­type is Cpp17Erasable from X
compile time
X​::​value_­type (map and multimap only)
pair<const Key, T>
Preconditions: value_­type is Cpp17Erasable from X
compile time
X​::​key_­compare
Compare
Preconditions: key_­compare is Cpp17CopyConstructible.
compile time
X​::​value_­compare
a binary predicate type
is the same as key_­compare for set and multiset; is an ordering relation on pairs induced by the first component (i.e., Key) for map and multimap.
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(c)
X u(c);
Effects:  Constructs an empty container.
Uses a copy of c as a comparison object.
constant
X()
X u;
Preconditions: key_­compare meets the Cpp17DefaultConstructible requirements.

Effects:  Constructs an empty container.
Uses Compare() as a comparison object
constant
X(i,j,c)
X u(i,j,c);
Preconditions: value_­type is Cpp17EmplaceConstructible into X from *i.

Effects:  Constructs an empty container and inserts elements from the range [i, j) into it; uses c as a comparison object.
in general, where N has the value distance(i, j); linear if [i, j) is sorted with value_­comp()
X(i,j)
X u(i,j);
Preconditions: key_­compare meets the Cpp17DefaultConstructible requirements.
value_­type is Cpp17EmplaceConstructible into X from *i.

Effects:  Same as above, but uses Compare() as a comparison object.
same as above
X(il)
same as X(il.begin(), il.end())
same as X(il.begin(), il.end())
X(il,c)
same as X(il.begin(), il.end(), c)
same as X(il.begin(), il.end(), c)
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.
in general, where N has the value il.size() + a.size(); linear if [il.begin(), il.end()) is sorted with value_­comp()
b.key_­comp()
X​::​key_­compare
Returns: the comparison object out of which b was constructed.
constant
b.value_­comp()
X​::​value_­compare
Returns: an object of value_­compare constructed out of the comparison object
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.
logarithmic
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.
If a range containing elements equivalent to t exists in a_­eq, t is inserted at the end of that range.
logarithmic
a.emplace_­hint(​p, args)
iterator
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 element is inserted as close as possible to the position just prior to p.
logarithmic in general, but amortized constant if the element is inserted right before p
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 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.
logarithmic
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 the iterator pointing to the newly inserted element.
If a range containing elements equivalent to t exists in a_­eq, t is inserted at the end of that range.
logarithmic
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:  Inserts t if and only if there is no element with key equivalent to the key of t in containers with unique keys; always inserts t in containers with equivalent keys.
Always returns the iterator pointing to the element with key equivalent to the key of t.
t is inserted as close as possible to the position just prior to p.
logarithmic in general, but amortized constant if t is inserted right before p.
a.​insert(​i, j)
void
Preconditions: value_­type is Cpp17EmplaceConstructible into X from *i.
Neither i nor j are iterators into a.

Effects: Inserts each element from the range [i, j) if and only if there is no element with key equivalent to the key of that element in containers with unique keys; always inserts that element in containers with equivalent keys.
, where N has the value distance(i, j)
a.​insert(​il)
void
Effects: Equivalent to 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().
logarithmic
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.
If a range containing elements with keys equivalent to nh.key() exists in a_­eq, the element is inserted at the end of that range.

Postconditions: nh is empty.
logarithmic
a.​insert(​p, 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 element is inserted as close as possible to the position just prior to p.

Postconditions: nh is empty if insertion succeeds, unchanged if insertion fails.
logarithmic in general, but amortized constant if the element is inserted right before p.
a.​extract(​k)
node_­type
Effects: Removes the first element in the container with key equivalent to k.

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

Returns: A node_­type owning that element.
amortized constant
a.merge(a2)
void
Preconditions: a.get_­allocator() == a2.get_­allocator().

Effects: Attempts to extract each element in a2 and insert it into a using the comparison object 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 will continue to refer to their elements, but they now behave as iterators into a, not into a2.

Throws: Nothing unless the comparison object throws.
, where N has the value a2.size().
a.erase(k)
size_­type
Effects: Erases all elements in the container with key equivalent to k.

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

Returns: An iterator pointing to the element immediately following q prior to the element being erased.
If no such element exists, returns a.end().
amortized constant
a.erase(r)
iterator
Effects: Erases the element pointed to by r.

Returns: An iterator pointing to the element immediately following r prior to the element being erased.
If no such element exists, returns a.end().
amortized constant
a.erase(
q1, q2)
iterator
Effects: Erases all the elements in the range [q1, q2).

Returns: An iterator pointing to the element pointed to by q2 prior to any elements being erased.
If no such element exists, a.end() is returned.
, where N has the value distance(q1, q2).
a.clear()
void
Effects: Equivalent to a.erase(a.begin(), a.end()).

Postconditions: a.empty() is true.
linear in a.size().
b.find(k)
iterator; const_­iterator for constant b.
Returns: An iterator pointing to an element with the key equivalent to k, or b.end() if such an element is not found.
logarithmic
a_­tran.
find(ke)
iterator; const_­iterator for constant a_­tran.
Returns: An iterator pointing to an element with key r such that !c(r, ke) && !c(ke, r), or a_­tran.end() if such an element is not found.
logarithmic
b.count(k)
size_­type
Returns: The number of elements with key equivalent to k.
a_­tran.
count(ke)
size_­type
Returns: The number of elements with key r such that !c(r, ke) && !c(ke, r)
b.
contains(k)
bool
Effects: Equivalent to: return b.find(k) != b.end();
logarithmic
a_­tran.
contains(ke)
bool
Effects: Equivalent to: return a_­tran.find(ke) != a_­tran.end();
logarithmic
b.lower_­bound(k)
iterator; const_­iterator for constant b.
Returns: An iterator pointing to the first element with key not less than k, or b.end() if such an element is not found.
logarithmic
a_­tran.
lower_­bound(kl)
iterator; const_­iterator for constant a_­tran.
Returns: An iterator pointing to the first element with key r such that !c(r, kl), or a_­tran.end() if such an element is not found.
logarithmic
b.upper_­bound(k)
iterator; const_­iterator for constant b.
Returns: An iterator pointing to the first element with key greater than k, or b.end() if such an element is not found.
logarithmic
a_­tran.
upper_­bound(ku)
iterator; const_­iterator for constant a_­tran.
Returns: An iterator pointing to the first element with key r such that c(ku, r), or a_­tran.end() if such an element is not found.
logarithmic
b.equal_­range(k)
pair<​iterator, iterator>; pair<​const_­iterator, const_­iterator> for constant b.
Effects: Equivalent to: return make_­pair(b.lower_­bound(k), b.upper_­bound(k));
logarithmic
a_­tran.
equal_­range(ke)
pair<​iterator, iterator>; pair<​const_­iterator, const_­iterator> for constant a_­tran.
Effects: Equivalent to: return make_­pair(
a_­tran.lower_­bound(ke), a_­tran.upper_­bound(ke));
logarithmic
The insert and emplace members shall not affect the validity of iterators and references to the container, and the erase members shall invalidate only iterators and references to the erased elements.
The extract members invalidate only iterators to the removed element; 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 fundamental property of iterators of associative containers is that they iterate through the containers in the non-descending order of keys where non-descending is defined by the comparison that was used to construct them.
For any two dereferenceable iterators i and j such that distance from i to j is positive, the following condition holds: value_comp(*j, *i) == false
For associative containers with unique keys the stronger condition holds: value_comp(*i, *j) != false
When an associative container is constructed by passing a comparison object the container shall not store a pointer or reference to the passed object, even if that object is passed by reference.
When an associative container is copied, through either a copy constructor or an assignment operator, the target container shall then use the comparison object from the container being copied, as if that comparison object had been passed to the target container in its constructor.
The member function templates find, count, contains, lower_­bound, upper_­bound, and equal_­range shall not participate in overload resolution unless the qualified-id Compare​::​is_­transparent is valid and denotes a type ([temp.deduct]).
A deduction guide for an 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 Compare template parameter and a type that qualifies as an allocator is deduced for that parameter.

22.2.6.2 Exception safety guarantees [associative.reqmts.except]

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

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.