code
stringlengths
2.5k
150k
kind
stringclasses
1 value
cpp std::max std::max ======== | Defined in header `[<algorithm>](../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | | (1) | | | ``` template< class T > const T& max( const T& a, const T& b ); ``` | (until C++14) | | ``` template< class T > constexpr const T& max( const T& a, const T& b ); ``` | (since C++14) | | | (2) | | | ``` template< class T, class Compare > const T& max( const T& a, const T& b, Compare comp ); ``` | (until C++14) | | ``` template< class T, class Compare > constexpr const T& max( const T& a, const T& b, Compare comp ); ``` | (since C++14) | | | (3) | | | ``` template< class T > T max( std::initializer_list<T> ilist ); ``` | (since C++11) (until C++14) | | ``` template< class T > constexpr T max( std::initializer_list<T> ilist ); ``` | (since C++14) | | | (4) | | | ``` template< class T, class Compare > T max( std::initializer_list<T> ilist, Compare comp ); ``` | (since C++11) (until C++14) | | ``` template< class T, class Compare > constexpr T max( std::initializer_list<T> ilist, Compare comp ); ``` | (since C++14) | Returns the greater of the given values. 1-2) Returns the greater of `a` and `b`. 3-4) Returns the greatest of the values in initializer list `ilist`. The (1,3) versions use `operator<` to compare the values, the (2,4) versions use the given comparison function `comp`. ### Parameters | | | | | --- | --- | --- | | a, b | - | the values to compare | | ilist | - | initializer list with the values to compare | | comp | - | comparison function object (i.e. an object that satisfies the requirements of [Compare](../named_req/compare "cpp/named req/Compare")) which returns ​`true` if `a` is *less* than `b`. The signature of the comparison function should be equivalent to the following: `bool cmp(const Type1 &a, const Type2 &b);` While the signature does not need to have `const &`, the function must not modify the objects passed to it and must be able to accept all values of type (possibly const) `Type1` and `Type2` regardless of [value category](../language/value_category "cpp/language/value category") (thus, `Type1 &` is not allowed, nor is `Type1` unless for `Type1` a move is equivalent to a copy (since C++11)). The types `Type1` and `Type2` must be such that an object of type `T` can be implicitly converted to both of them. ​ | | Type requirements | | -`T` must meet the requirements of [LessThanComparable](../named_req/lessthancomparable "cpp/named req/LessThanComparable") in order to use overloads (1,3). | | -`T` must meet the requirements of [CopyConstructible](../named_req/copyconstructible "cpp/named req/CopyConstructible") in order to use overloads (3,4). | ### Return value 1-2) The greater of `a` and `b`. If they are equivalent, returns `a`. 3-4) The greatest value in `ilist`. If several values are equivalent to the greatest, returns the leftmost one. ### Complexity 1-2) Exactly one comparison 3-4) Exactly `ilist.size() - 1` comparisons ### Possible implementation | First version | | --- | | ``` template<class T> const T& max(const T& a, const T& b) { return (a < b) ? b : a; } ``` | | Second version | | ``` template<class T, class Compare> const T& max(const T& a, const T& b, Compare comp) { return (comp(a, b)) ? b : a; } ``` | | Third version | | ``` template< class T > T max( std::initializer_list<T> ilist) { return *std::max_element(ilist.begin(), ilist.end()); } ``` | | Fourth version | | ``` template< class T, class Compare > T max( std::initializer_list<T> ilist, Compare comp ) { return *std::max_element(ilist.begin(), ilist.end(), comp); } ``` | ### Notes Capturing the result of `std::max` by reference produces a dangling reference if one of the parameters is a temporary and that parameter is returned: ``` int n = 1; const int& r = std::max(n-1, n+1); // r is dangling ``` ### Example ``` #include <algorithm> #include <iostream> #include <string_view> int main() { std::cout << "larger of 1 and 9999 is " << std::max(1, 9999) << '\n' << "larger of 'a', and 'b' is '" << std::max('a', 'b') << "'\n" << "largest of 1, 10, 50, and 200 is " << std::max({1, 10, 50, 200}) << '\n' << "longest of \"foo\", \"bar\", and \"hello\" is \"" << std::max({ "foo", "bar", "hello" }, [](const std::string_view s1, const std::string_view s2) { return s1.size() < s2.size(); }) << "\"\n"; } ``` Output: ``` larger of 1 and 9999 is 9999 larger of 'a', and 'b' is 'b' largest of 1, 10, 50, and 200 is 200 longest of "foo", "bar", and "hello" is "hello" ``` ### See also | | | | --- | --- | | [min](min "cpp/algorithm/min") | returns the smaller of the given values (function template) | | [minmax](minmax "cpp/algorithm/minmax") (C++11) | returns the smaller and larger of two elements (function template) | | [max\_element](max_element "cpp/algorithm/max element") | returns the largest element in a range (function template) | | [clamp](clamp "cpp/algorithm/clamp") (C++17) | clamps a value between a pair of boundary values (function template) | | [ranges::max](ranges/max "cpp/algorithm/ranges/max") (C++20) | returns the greater of the given values (niebloid) | cpp std::is_heap std::is\_heap ============= | Defined in header `[<algorithm>](../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | | (1) | | | ``` template< class RandomIt > bool is_heap( RandomIt first, RandomIt last ); ``` | (since C++11) (until C++20) | | ``` template< class RandomIt > constexpr bool is_heap( RandomIt first, RandomIt last ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class RandomIt > bool is_heap( ExecutionPolicy&& policy, RandomIt first, RandomIt last ); ``` | (2) | (since C++17) | | | (3) | | | ``` template< class RandomIt, class Compare > bool is_heap( RandomIt first, RandomIt last, Compare comp ); ``` | (since C++11) (until C++20) | | ``` template< class RandomIt, class Compare > constexpr bool is_heap( RandomIt first, RandomIt last, Compare comp ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class RandomIt, class Compare > bool is_heap( ExecutionPolicy&& policy, RandomIt first, RandomIt last, Compare comp ); ``` | (4) | (since C++17) | Checks whether the elements in range `[first, last)` are a [*max heap*](https://en.wikipedia.org/wiki/Binary_heap "enwiki:Binary heap"). 1) Elements are compared using `operator<`. 3) Elements are compared using the given binary comparison function `comp`. 2,4) Same as (1,3), but executed according to `policy`. These overloads do not participate in overload resolution unless `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ExecutionPolicy>>` (until C++20) `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<ExecutionPolicy>>` (since C++20) is true. ### Parameters | | | | | --- | --- | --- | | first, last | - | the range of elements to examine | | policy | - | the execution policy to use. See [execution policy](execution_policy_tag_t "cpp/algorithm/execution policy tag t") for details. | | comp | - | comparison function object (i.e. an object that satisfies the requirements of [Compare](../named_req/compare "cpp/named req/Compare")) which returns ​`true` if the first argument is *less* than the second. The signature of the comparison function should be equivalent to the following: `bool cmp(const Type1 &a, const Type2 &b);` While the signature does not need to have `const &`, the function must not modify the objects passed to it and must be able to accept all values of type (possibly const) `Type1` and `Type2` regardless of [value category](../language/value_category "cpp/language/value category") (thus, `Type1 &` is not allowed, nor is `Type1` unless for `Type1` a move is equivalent to a copy (since C++11)). The types `Type1` and `Type2` must be such that an object of type `RandomIt` can be dereferenced and then implicitly converted to both of them. ​ | | Type requirements | | -`RandomIt` must meet the requirements of [LegacyRandomAccessIterator](../named_req/randomaccessiterator "cpp/named req/RandomAccessIterator"). | ### Return value `true` if the range is *max heap*, `false` otherwise. ### Complexity Linear in the distance between `first` and `last`. ### Exceptions The overloads with a template parameter named `ExecutionPolicy` report errors as follows: * If execution of a function invoked as part of the algorithm throws an exception and `ExecutionPolicy` is one of the [standard policies](execution_policy_tag_t "cpp/algorithm/execution policy tag t"), `[std::terminate](../error/terminate "cpp/error/terminate")` is called. For any other `ExecutionPolicy`, the behavior is implementation-defined. * If the algorithm fails to allocate memory, `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` is thrown. ### Notes A *max heap* is a range of elements `[f,l)` that has the following properties: * With `N = l-f`, for all `0 < i < N`, `f[(i-1)/2]` does not compare less than `f[i]`. * A new element can be added using `[std::push\_heap](push_heap "cpp/algorithm/push heap")`, in \(\scriptsize \mathcal{O}(\log N)\)𝓞(log N) time. * The first element can be removed using `[std::pop\_heap](pop_heap "cpp/algorithm/pop heap")`, in \(\scriptsize \mathcal{O}(\log N)\)𝓞(log N) time. ### Example ``` #include <algorithm> #include <bit> #include <iostream> #include <vector> int main() { std::vector<int> v { 3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9 }; std::cout << "initially, v:\n"; for (auto i : v) std::cout << i << ' '; std::cout << '\n'; if (!std::is_heap(v.begin(), v.end())) { std::cout << "making heap...\n"; std::make_heap(v.begin(), v.end()); } std::cout << "after make_heap, v:\n"; for (auto t{1U}; auto i : v) std::cout << i << (std::has_single_bit(++t) ? " │ " : " "); std::cout << '\n'; } ``` Output: ``` initially, v: 3 1 4 1 5 9 2 6 5 3 5 8 9 7 9 making heap... after make_heap, v: 9 │ 6 9 │ 5 5 9 7 │ 1 1 3 5 8 3 4 2 │ ``` ### See also | | | | --- | --- | | [is\_heap\_until](is_heap_until "cpp/algorithm/is heap until") (C++11) | finds the largest subrange that is a max heap (function template) | | [make\_heap](make_heap "cpp/algorithm/make heap") | creates a max heap out of a range of elements (function template) | | [push\_heap](push_heap "cpp/algorithm/push heap") | adds an element to a max heap (function template) | | [pop\_heap](pop_heap "cpp/algorithm/pop heap") | removes the largest element from a max heap (function template) | | [sort\_heap](sort_heap "cpp/algorithm/sort heap") | turns a max heap into a range of elements sorted in ascending order (function template) | | [ranges::is\_heap](ranges/is_heap "cpp/algorithm/ranges/is heap") (C++20) | checks if the given range is a max heap (niebloid) | cpp std::minmax_element std::minmax\_element ==================== | Defined in header `[<algorithm>](../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | | (1) | | | ``` template< class ForwardIt > std::pair<ForwardIt,ForwardIt> minmax_element( ForwardIt first, ForwardIt last ); ``` | (since C++11) (until C++17) | | ``` template< class ForwardIt > constexpr std::pair<ForwardIt,ForwardIt> minmax_element( ForwardIt first, ForwardIt last ); ``` | (since C++17) | | ``` template< class ExecutionPolicy, class ForwardIt > std::pair<ForwardIt,ForwardIt> minmax_element( ExecutionPolicy&& policy, ForwardIt first, ForwardIt last ); ``` | (2) | (since C++17) | | | (3) | | | ``` template< class ForwardIt, class Compare > std::pair<ForwardIt,ForwardIt> minmax_element( ForwardIt first, ForwardIt last, Compare comp ); ``` | (since C++11) (until C++17) | | ``` template< class ForwardIt, class Compare > constexpr std::pair<ForwardIt,ForwardIt> minmax_element( ForwardIt first, ForwardIt last, Compare comp ); ``` | (since C++17) | | ``` template< class ExecutionPolicy, class ForwardIt, class Compare > std::pair<ForwardIt,ForwardIt> minmax_element( ExecutionPolicy&& policy, ForwardIt first, ForwardIt last, Compare comp ); ``` | (4) | (since C++17) | Finds the smallest and greatest element in the range `[first, last)`. 1) Elements are compared using `operator<`. 3) Elements are compared using the given binary comparison function `comp`. 2,4) Same as (1,3), but executed according to `policy`. These overloads do not participate in overload resolution unless `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ExecutionPolicy>>` (until C++20) `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<ExecutionPolicy>>` (since C++20) is true. ### Parameters | | | | | --- | --- | --- | | first, last | - | forward iterators defining the range to examine | | policy | - | the execution policy to use. See [execution policy](execution_policy_tag_t "cpp/algorithm/execution policy tag t") for details. | | cmp | - | comparison function object (i.e. an object that satisfies the requirements of [Compare](../named_req/compare "cpp/named req/Compare")) which returns ​`true` if if `*a` is *less* than `*b`. The signature of the comparison function should be equivalent to the following: `bool cmp(const Type1 &a, const Type2 &b);` While the signature does not need to have `const &`, the function must not modify the objects passed to it and must be able to accept all values of type (possibly const) `Type1` and `Type2` regardless of [value category](../language/value_category "cpp/language/value category") (thus, `Type1 &` is not allowed, nor is `Type1` unless for `Type1` a move is equivalent to a copy (since C++11)). The types `Type1` and `Type2` must be such that an object of type `ForwardIt` can be dereferenced and then implicitly converted to both of them. ​ | | Type requirements | | -`ForwardIt` must meet the requirements of [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"). | ### Return value a pair consisting of an iterator to the smallest element as the first element and an iterator to the greatest element as the second. Returns `[std::make\_pair](http://en.cppreference.com/w/cpp/utility/pair/make_pair)(first, first)` if the range is empty. If several elements are equivalent to the smallest element, the iterator to the first such element is returned. If several elements are equivalent to the largest element, the iterator to the last such element is returned. ### Complexity At most max(floor((3/2)\*(N−1)), 0) applications of the predicate, where `N = [std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(first, last)`. ### Exceptions The overloads with a template parameter named `ExecutionPolicy` report errors as follows: * If execution of a function invoked as part of the algorithm throws an exception and `ExecutionPolicy` is one of the [standard policies](execution_policy_tag_t "cpp/algorithm/execution policy tag t"), `[std::terminate](../error/terminate "cpp/error/terminate")` is called. For any other `ExecutionPolicy`, the behavior is implementation-defined. * If the algorithm fails to allocate memory, `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` is thrown. ### Notes This algorithm is different from `[std::make\_pair](http://en.cppreference.com/w/cpp/utility/pair/make_pair)([std::min\_element](http://en.cppreference.com/w/cpp/algorithm/min_element)(), [std::max\_element](http://en.cppreference.com/w/cpp/algorithm/max_element)())`, not only in efficiency, but also in that this algorithm finds the *last* biggest element while `[std::max\_element](max_element "cpp/algorithm/max element")` finds the *first* biggest element. ### Possible implementation | First version | | --- | | ``` template<class ForwardIt> std::pair<ForwardIt, ForwardIt> minmax_element(ForwardIt first, ForwardIt last) { using value_type = typename std::iterator_traits<ForwardIt>::value_type; return std::minmax_element(first, last, std::less<value_type>()); } ``` | | Second version | | ``` template<class ForwardIt, class Compare> std::pair<ForwardIt, ForwardIt> minmax_element(ForwardIt first, ForwardIt last, Compare comp) { auto min = first, max = first; if (first == last || ++first == last) return {min, max}; if (comp(*first, *min)) { min = first; } else { max = first; } while (++first != last) { auto i = first; if (++first == last) { if (comp(*i, *min)) min = i; else if (!(comp(*i, *max))) max = i; break; } else { if (comp(*first, *i)) { if (comp(*first, *min)) min = first; if (!(comp(*i, *max))) max = i; } else { if (comp(*i, *min)) min = i; if (!(comp(*first, *max))) max = first; } } } return {min, max}; } ``` | ### Example ``` #include <algorithm> #include <iostream> int main() { const auto v = { 3, 9, 1, 4, 2, 5, 9 }; const auto [min, max] = std::minmax_element(begin(v), end(v)); std::cout << "min = " << *min << ", max = " << *max << '\n'; } ``` Output: ``` min = 1, max = 9 ``` ### See also | | | | --- | --- | | [min\_element](min_element "cpp/algorithm/min element") | returns the smallest element in a range (function template) | | [max\_element](max_element "cpp/algorithm/max element") | returns the largest element in a range (function template) | | [ranges::minmax\_element](ranges/minmax_element "cpp/algorithm/ranges/minmax element") (C++20) | returns the smallest and the largest elements in a range (niebloid) | cpp std::shift_left, std::shift_right std::shift\_left, std::shift\_right =================================== | Defined in header `[<algorithm>](../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | ``` template< class ForwardIt > constexpr ForwardIt shift_left( ForwardIt first, ForwardIt last, typename std::iterator_traits<ForwardIt>::difference_type n ); ``` | (1) | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt > ForwardIt shift_left( ExecutionPolicy&& policy, ForwardIt first, ForwardIt last, typename std::iterator_traits<ForwardIt>::difference_type n ); ``` | (2) | (since C++20) | | ``` template< class ForwardIt > constexpr ForwardIt shift_right( ForwardIt first, ForwardIt last, typename std::iterator_traits<ForwardIt>::difference_type n ); ``` | (3) | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt > ForwardIt shift_right( ExecutionPolicy&& policy, ForwardIt first, ForwardIt last, typename std::iterator_traits<ForwardIt>::difference_type n ); ``` | (4) | (since C++20) | Shifts the elements in the range `[first, last)` by `n` positions. 1) Shifts the elements towards the beginning of the range. If `n == 0 || n >= last - first`, there are no effects. If `n < 0`, the behavior is undefined. Otherwise, for every integer `i` in `[0, last - first - n)`, moves the element originally at position `first + n + i` to position `first + i`. The moves are performed in increasing order of `i` starting from `​0​`. 3) Shifts the elements towards the end of the range. If `n == 0 || n >= last - first`, there are no effects. If `n < 0`, the behavior is undefined. Otherwise, for every integer `i` in `[0, last - first - n)`, moves the element originally at position `first + i` to position `first + n + i`. If `ForwardIt` meets the [LegacyBidirectionalIterator](../named_req/bidirectionaliterator "cpp/named req/BidirectionalIterator") requirements, then the moves are performed in decreasing order of `i` starting from `last - first - n - 1`. 2,4) Same as (1) and (3), respectively, but executed according to `policy` and the moves may be performed in any order. This overload participates in overload resolution only if `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<ExecutionPolicy>>` is true Elements that are in the original range but not the new range are left in a valid but unspecified state. ### Parameters | | | | | --- | --- | --- | | first | - | the beginning of the original range | | last | - | the end of the original range | | n | - | the number of positions to shift | | policy | - | the execution policy to use. See [execution policy](execution_policy_tag_t "cpp/algorithm/execution policy tag t") for details. | | Type requirements | | -`ForwardIt` must meet the requirements of [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"). | | -`ForwardIt` must meet either the requirements of [LegacyBidirectionalIterator](../named_req/bidirectionaliterator "cpp/named req/BidirectionalIterator") or the requirements of [ValueSwappable](../named_req/valueswappable "cpp/named req/ValueSwappable") for overloads (3-4). | | -The type of dereferenced `ForwardIt` must meet the requirements of [MoveAssignable](../named_req/moveassignable "cpp/named req/MoveAssignable"). | ### Return value 1-2) The end of the resulting range. If `n` is less than `last - first`, returns `first + (last - first - n)`. Otherwise, returns `first`. 3-4) The beginning of the resulting range. If `n` is less than `last - first`, returns `first + n`. Otherwise, returns `last`. ### Complexity 1-2) At most `[std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(first, last) - n` assignments. 3-4) At most `[std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(first, last) - n` assignment or swaps. ### Exceptions The overloads with a template parameter named `ExecutionPolicy` report errors as follows: * If execution of a function invoked as part of the algorithm throws an exception and `ExecutionPolicy` is one of the [standard policies](execution_policy_tag_t "cpp/algorithm/execution policy tag t"), `[std::terminate](../error/terminate "cpp/error/terminate")` is called. For any other `ExecutionPolicy`, the behavior is implementation-defined. * If the algorithm fails to allocate memory, `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` is thrown. ### Notes | [Feature-test](../utility/feature_test "cpp/utility/feature test") macro | Value | Std | | --- | --- | --- | | [`__cpp_lib_shift`](../feature_test#Library_features "cpp/feature test") | `201806L` | (C++20) | ### Example ``` #include <algorithm> #include <iostream> #include <string> #include <type_traits> #include <vector> struct S { int value{0}; bool specified_state{true}; S(int v = 0) : value{v} {} S(S const& rhs) = default; S(S&& rhs) { *this = std::move(rhs); } S& operator=(S const& rhs) = default; S& operator=(S&& rhs) { if (this != &rhs) { value = rhs.value; specified_state = rhs.specified_state; rhs.specified_state = false; } return *this; } }; template <typename T> std::ostream& operator<< (std::ostream& os, std::vector<T> const& v) { for (const auto& s : v) { if constexpr (std::is_same_v<T, S>) s.specified_state ? os << s.value << ' ' : os << ". "; else if constexpr (std::is_same_v<T, std::string>) os << (s.empty() ? "." : s) << ' '; else os << s << ' '; } return os; } int main() { std::cout << std::left; std::vector<S> a{1, 2, 3, 4, 5, 6, 7}; std::vector<int> b{1, 2, 3, 4, 5, 6, 7}; std::vector<std::string> c{"α", "β", "γ", "δ", "ε", "ζ", "η"}; std::cout << "vector<S> \tvector<int> \tvector<string>\n"; std::cout << a << " " << b << " " << c << '\n'; std::shift_left(begin(a), end(a), 3); std::shift_left(begin(b), end(b), 3); std::shift_left(begin(c), end(c), 3); std::cout << a << " " << b << " " << c << '\n'; std::shift_right(begin(a), end(a), 2); std::shift_right(begin(b), end(b), 2); std::shift_right(begin(c), end(c), 2); std::cout << a << " " << b << " " << c << '\n'; std::shift_left(begin(a), end(a), 8); // has no effect: n >= last - first std::shift_left(begin(b), end(b), 8); // ditto std::shift_left(begin(c), end(c), 8); // ditto std::cout << a << " " << b << " " << c << '\n'; // std::shift_left(begin(a), end(a),-3); // UB, e.g. segfault.) } ``` Possible output: ``` vector<S> vector<int> vector<string> 1 2 3 4 5 6 7 1 2 3 4 5 6 7 α β γ δ ε ζ η 4 5 6 7 . . . 4 5 6 7 5 6 7 δ ε ζ η . . . . . 4 5 6 7 . 4 5 4 5 6 7 5 . . δ ε ζ η . . . 4 5 6 7 . 4 5 4 5 6 7 5 . . δ ε ζ η . ``` ### See also | | | | --- | --- | | [move](move "cpp/algorithm/move") (C++11) | moves a range of elements to a new location (function template) | | [move\_backward](move_backward "cpp/algorithm/move backward") (C++11) | moves a range of elements to a new location in backwards order (function template) | | [rotate](rotate "cpp/algorithm/rotate") | rotates the order of elements in a range (function template) | | [ranges::shift\_leftranges::shift\_right](ranges/shift "cpp/algorithm/ranges/shift") (C++23) | shifts elements in a range (niebloid) |
programming_docs
cpp std::min std::min ======== | Defined in header `[<algorithm>](../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | | (1) | | | ``` template< class T > const T& min( const T& a, const T& b ); ``` | (until C++14) | | ``` template< class T > constexpr const T& min( const T& a, const T& b ); ``` | (since C++14) | | | (2) | | | ``` template< class T, class Compare > const T& min( const T& a, const T& b, Compare comp ); ``` | (until C++14) | | ``` template< class T, class Compare > constexpr const T& min( const T& a, const T& b, Compare comp ); ``` | (since C++14) | | | (3) | | | ``` template< class T > T min( std::initializer_list<T> ilist ); ``` | (since C++11) (until C++14) | | ``` template< class T > constexpr T min( std::initializer_list<T> ilist ); ``` | (since C++14) | | | (4) | | | ``` template< class T, class Compare > T min( std::initializer_list<T> ilist, Compare comp ); ``` | (since C++11) (until C++14) | | ``` template< class T, class Compare > constexpr T min( std::initializer_list<T> ilist, Compare comp ); ``` | (since C++14) | Returns the smaller of the given values. 1-2) Returns the smaller of `a` and `b`. 3-4) Returns the smallest of the values in initializer list `ilist`. The (1,3) versions use `operator<` to compare the values, the (2,4) versions use the given comparison function `comp`. ### Parameters | | | | | --- | --- | --- | | a, b | - | the values to compare | | ilist | - | initializer list with the values to compare | | cmp | - | comparison function object (i.e. an object that satisfies the requirements of [Compare](../named_req/compare "cpp/named req/Compare")) which returns ​`true` if `a` is *less* than `b`. The signature of the comparison function should be equivalent to the following: `bool cmp(const Type1 &a, const Type2 &b);` While the signature does not need to have `const &`, the function must not modify the objects passed to it and must be able to accept all values of type (possibly const) `Type1` and `Type2` regardless of [value category](../language/value_category "cpp/language/value category") (thus, `Type1 &` is not allowed, nor is `Type1` unless for `Type1` a move is equivalent to a copy (since C++11)). The types `Type1` and `Type2` must be such that an object of type `T` can be implicitly converted to both of them. ​ | | Type requirements | | -`T` must meet the requirements of [LessThanComparable](../named_req/lessthancomparable "cpp/named req/LessThanComparable") in order to use overloads (1,3). | | -`T` must meet the requirements of [CopyConstructible](../named_req/copyconstructible "cpp/named req/CopyConstructible") in order to use overloads (3,4). | ### Return value 1-2) The smaller of `a` and `b`. If the values are equivalent, returns `a`. 3-4) The smallest value in `ilist`. If several values are equivalent to the smallest, returns the leftmost such value. ### Complexity 1-2) Exactly one comparison 3-4) Exactly `ilist.size() - 1` comparisons ### Possible implementation | First version | | --- | | ``` template<class T> const T& min(const T& a, const T& b) { return (b < a) ? b : a; } ``` | | Second version | | ``` template<class T, class Compare> const T& min(const T& a, const T& b, Compare comp) { return (comp(b, a)) ? b : a; } ``` | | Third version | | ``` template<class T> T min( std::initializer_list<T> ilist) { return *std::min_element(ilist.begin(), ilist.end()); } ``` | | Fourth version | | ``` template<class T, class Compare> T min(std::initializer_list<T> ilist, Compare comp) { return *std::min_element(ilist.begin(), ilist.end(), comp); } ``` | ### Notes Capturing the result of `std::min` by reference produces a dangling reference if one of the parameters is a temporary and that parameter is returned: ``` int n = 1; const int& r = std::min(n-1, n+1); // r is dangling ``` ### Example ``` #include <algorithm> #include <iostream> #include <string_view> int main() { std::cout << "smaller of 1 and 9999 is " << std::min(1, 9999) << '\n' << "smaller of 'a', and 'b' is '" << std::min('a', 'b') << "'\n" << "shortest of \"foo\", \"bar\", and \"hello\" is \"" << std::min({ "foo", "bar", "hello" }, [](const std::string_view s1, const std::string_view s2) { return s1.size() < s2.size(); }) << "\"\n"; } ``` Output: ``` smaller of 1 and 9999 is 1 smaller of 'a', and 'b' is 'a' shortest of "foo", "bar", and "hello" is "foo" ``` ### See also | | | | --- | --- | | [max](max "cpp/algorithm/max") | returns the greater of the given values (function template) | | [minmax](minmax "cpp/algorithm/minmax") (C++11) | returns the smaller and larger of two elements (function template) | | [min\_element](min_element "cpp/algorithm/min element") | returns the smallest element in a range (function template) | | [clamp](clamp "cpp/algorithm/clamp") (C++17) | clamps a value between a pair of boundary values (function template) | | [ranges::min](ranges/min "cpp/algorithm/ranges/min") (C++20) | returns the smaller of the given values (niebloid) | cpp std::inner_product std::inner\_product =================== | Defined in header `[<numeric>](../header/numeric "cpp/header/numeric")` | | | | --- | --- | --- | | | (1) | | | ``` template< class InputIt1, class InputIt2, class T > T inner_product( InputIt1 first1, InputIt1 last1, InputIt2 first2, T init ); ``` | (until C++20) | | ``` template< class InputIt1, class InputIt2, class T > constexpr T inner_product( InputIt1 first1, InputIt1 last1, InputIt2 first2, T init ); ``` | (since C++20) | | | (2) | | | ``` template< class InputIt1, class InputIt2, class T, class BinaryOperation1, class BinaryOperation2 > T inner_product( InputIt1 first1, InputIt1 last1, InputIt2 first2, T init, BinaryOperation1 op1, BinaryOperation2 op2 ); ``` | (until C++20) | | ``` template< class InputIt1, class InputIt2, class T, class BinaryOperation1, class BinaryOperation2 > constexpr T inner_product( InputIt1 first1, InputIt1 last1, InputIt2 first2, T init, BinaryOperation1 op1, BinaryOperation2 op2 ); ``` | (since C++20) | Computes inner product (i.e. sum of products) or performs ordered map/reduce operation on the range `[first1, last1)` and the range beginning at `first2`. 1) Initializes the accumulator `acc` with the initial value `init` and then | | | | --- | --- | | modifies it with the expression `acc = acc + *first1 * *first2`, then modifies again with the expression `acc = acc + *(first1+1) * *(first2+1)`, etc. | (until C++20) | | modifies it with the expression `acc = std::move(acc) + *first1 * *first2`, then modifies again with the expression `acc = std::move(acc) + *(first1+1) * *(first2+1)`, etc. | (since C++20) | until reaching `last1`. For built-in meaning of + and \*, this computes inner product of the two ranges. 2) Initializes the accumulator `acc` with the initial value `init` and then | | | | --- | --- | | modifies it with the expression `acc = op1(acc, op2(*first1, *first2))`, then modifies again with the expression `acc = op1(acc, op2(*(first1+1), *(first2+1)))`, etc. | (until C++20) | | modifies it with the expression `acc = op1(std::move(acc), op2(*first1, *first2))`, then modifies again with the expression `acc = op1(std::move(acc), op2(*(first1+1), *(first2+1)))`, etc. | (since C++20) | until reaching `last1`. | | | | --- | --- | | `op1` or `op2` must not have side effects. | (until C++11) | | `op1` or `op2` must not invalidate any iterators, including the end iterators, or modify any elements of the range involved. | (since C++11) | ### Parameters | | | | | --- | --- | --- | | first1, last1 | - | the first range of elements | | first2 | - | the beginning of the second range of elements | | init | - | initial value of the sum of the products | | op1 | - | binary operation function object that will be applied. This "sum" function takes a value returned by op2 and the current value of the accumulator and produces a new value to be stored in the accumulator. The signature of the function should be equivalent to the following: `Ret fun(const Type1 &a, const Type2 &b);` The signature does not need to have `const &`. The types `Type1` and `Type2` must be such that objects of types `T` and `Type3` can be implicitly converted to `Type1` and `Type2` respectively. The type `Ret` must be such that an object of type `T` can be assigned a value of type `Ret`. ​ | | op2 | - | binary operation function object that will be applied. This "product" function takes one value from each range and produces a new value. The signature of the function should be equivalent to the following: `Ret fun(const Type1 &a, const Type2 &b);` The signature does not need to have `const &`. The types `Type1` and `Type2` must be such that objects of types `InputIt1` and `InputIt2` can be dereferenced and then implicitly converted to `Type1` and `Type2` respectively. The type `Ret` must be such that an object of type `Type3` can be assigned a value of type `Ret`. ​ | | Type requirements | | -`InputIt1, InputIt2` must meet the requirements of [LegacyInputIterator](../named_req/inputiterator "cpp/named req/InputIterator"). | | -`ForwardIt1, ForwardIt2` must meet the requirements of [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"). | | -`T` must meet the requirements of [CopyAssignable](../named_req/copyassignable "cpp/named req/CopyAssignable") and [CopyConstructible](../named_req/copyconstructible "cpp/named req/CopyConstructible"). | ### Return value The final value of `acc` as described above. ### Possible implementation | First version | | --- | | ``` template<class InputIt1, class InputIt2, class T> constexpr // since C++20 T inner_product(InputIt1 first1, InputIt1 last1, InputIt2 first2, T init) { while (first1 != last1) { init = std::move(init) + *first1 * *first2; // std::move since C++20 ++first1; ++first2; } return init; } ``` | | Second version | | ``` template<class InputIt1, class InputIt2, class T, class BinaryOperation1, class BinaryOperation2> constexpr // since C++20 T inner_product(InputIt1 first1, InputIt1 last1, InputIt2 first2, T init, BinaryOperation1 op1 BinaryOperation2 op2) { while (first1 != last1) { init = op1(std::move(init), op2(*first1, *first2)); // std::move since C++20 ++first1; ++first2; } return init; } ``` | ### Notes The parallelizable version of this algorithm, `[std::transform\_reduce](transform_reduce "cpp/algorithm/transform reduce")`, requires `op1` and `op2` to be commutative and associative, but `std::inner_product` makes no such requirement, and always performs the operations in the order given. ### Example ``` #include <numeric> #include <iostream> #include <vector> #include <functional> int main() { std::vector<int> a{0, 1, 2, 3, 4}; std::vector<int> b{5, 4, 2, 3, 1}; int r1 = std::inner_product(a.begin(), a.end(), b.begin(), 0); std::cout << "Inner product of a and b: " << r1 << '\n'; int r2 = std::inner_product(a.begin(), a.end(), b.begin(), 0, std::plus<>(), std::equal_to<>()); std::cout << "Number of pairwise matches between a and b: " << r2 << '\n'; } ``` Output: ``` Inner product of a and b: 21 Number of pairwise matches between a and b: 2 ``` ### See also | | | | --- | --- | | [transform\_reduce](transform_reduce "cpp/algorithm/transform reduce") (C++17) | applies an invocable, then reduces out of order (function template) | | [accumulate](accumulate "cpp/algorithm/accumulate") | sums up a range of elements (function template) | | [partial\_sum](partial_sum "cpp/algorithm/partial sum") | computes the partial sum of a range of elements (function template) | cpp std::includes std::includes ============= | Defined in header `[<algorithm>](../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | | (1) | | | ``` template< class InputIt1, class InputIt2 > bool includes( InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2 ); ``` | (until C++20) | | ``` template< class InputIt1, class InputIt2 > constexpr bool includes( InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2 ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt1, class ForwardIt2 > bool includes( ExecutionPolicy&& policy, ForwardIt1 first1, ForwardIt1 last1, ForwardIt2 first2, ForwardIt2 last2 ); ``` | (2) | (since C++17) | | | (3) | | | ``` template< class InputIt1, class InputIt2, class Compare > bool includes( InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2, Compare comp ); ``` | (until C++20) | | ``` template< class InputIt1, class InputIt2, class Compare > constexpr bool includes( InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2, Compare comp ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt1, class ForwardIt2, class Compare > bool includes( ExecutionPolicy&& policy, ForwardIt1 first1, ForwardIt1 last1, ForwardIt2 first2, ForwardIt2 last2, Compare comp ); ``` | (4) | (since C++17) | Returns `true` if the sorted range `[first2, last2)` is a [subsequence](https://en.wikipedia.org/wiki/subsequence "enwiki:subsequence") of the sorted range `[first1, last1)`. (A subsequence need not be contiguous.). 1) Both ranges must be sorted with `operator<`. 3) Both ranges must be sorted with the given comparison function `comp`. 2,4) Same as (1,3), but executed according to `policy`. These overloads do not participate in overload resolution unless `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ExecutionPolicy>>` (until C++20) `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<ExecutionPolicy>>` (since C++20) is true. ### Parameters | | | | | --- | --- | --- | | first1, last1 | - | the sorted range of elements to examine | | first2, last2 | - | the sorted range of elements to search for | | policy | - | the execution policy to use. See [execution policy](execution_policy_tag_t "cpp/algorithm/execution policy tag t") for details. | | comp | - | comparison function object (i.e. an object that satisfies the requirements of [Compare](../named_req/compare "cpp/named req/Compare")) which returns ​`true` if the first argument is *less* than (i.e. is ordered *before*) the second. The signature of the comparison function should be equivalent to the following: `bool cmp(const Type1 &a, const Type2 &b);` While the signature does not need to have `const &`, the function must not modify the objects passed to it and must be able to accept all values of type (possibly const) `Type1` and `Type2` regardless of [value category](../language/value_category "cpp/language/value category") (thus, `Type1 &` is not allowed, nor is `Type1` unless for `Type1` a move is equivalent to a copy (since C++11)). The types `Type1` and `Type2` must be such that an object of type `InputIt` can be dereferenced and then implicitly converted to both of them. ​ | | Type requirements | | -`InputIt1, InputIt2` must meet the requirements of [LegacyInputIterator](../named_req/inputiterator "cpp/named req/InputIterator"). | | -`ForwardIt1, ForwardIt2` must meet the requirements of [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"). | ### Return value `true` if `[first2, last2)` is a subsequence of `[first1, last1)`; otherwise `false`. ### Complexity At most \(\scriptsize 2 \cdot (N\_1+N\_2-1)\)2·(N1+N2-1) comparisons, where \(\scriptsize N\_1\)N1 is `[std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(first1, last1)` and \(\scriptsize N\_2\)N2 is `[std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(first2, last2)`. ### Exceptions The overloads with a template parameter named `ExecutionPolicy` report errors as follows: * If execution of a function invoked as part of the algorithm throws an exception and `ExecutionPolicy` is one of the [standard policies](execution_policy_tag_t "cpp/algorithm/execution policy tag t"), `[std::terminate](../error/terminate "cpp/error/terminate")` is called. For any other `ExecutionPolicy`, the behavior is implementation-defined. * If the algorithm fails to allocate memory, `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` is thrown. ### Possible implementation | First version | | --- | | ``` template<class InputIt1, class InputIt2> bool includes(InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2) { for (; first2 != last2; ++first1) { if (first1 == last1 || *first2 < *first1) return false; if ( !(*first1 < *first2) ) ++first2; } return true; } ``` | | Second version | | ``` template<class InputIt1, class InputIt2, class Compare> bool includes(InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2, Compare comp) { for (; first2 != last2; ++first1) { if (first1 == last1 || comp(*first2, *first1)) return false; if (!comp(*first1, *first2)) ++first2; } return true; } ``` | ### Example ``` #include <iostream> #include <algorithm> #include <cctype> template<class Os, class Co> Os& operator<<(Os& os, const Co& v) { for (auto i : v) os << i << ' '; return os << '\t'; } int main() { const auto v1 = {'a', 'b', 'c', 'f', 'h', 'x'}, v2 = {'a', 'b', 'c'}, v3 = {'a', 'c'}, v4 = {'a', 'a', 'b'}, v5 = {'g'}, v6 = {'a', 'c', 'g'}, v7 = {'A', 'B', 'C'}; auto no_case = [](char a, char b) { return std::tolower(a) < std::tolower(b); }; std::cout << v1 << "\nincludes:\n" << std::boolalpha << v2 << ": " << std::includes(v1.begin(), v1.end(), v2.begin(), v2.end()) << '\n' << v3 << ": " << std::includes(v1.begin(), v1.end(), v3.begin(), v3.end()) << '\n' << v4 << ": " << std::includes(v1.begin(), v1.end(), v4.begin(), v4.end()) << '\n' << v5 << ": " << std::includes(v1.begin(), v1.end(), v5.begin(), v5.end()) << '\n' << v6 << ": " << std::includes(v1.begin(), v1.end(), v6.begin(), v6.end()) << '\n' << v7 << ": " << std::includes(v1.begin(), v1.end(), v7.begin(), v7.end(), no_case) << " (case-insensitive)\n"; } ``` Output: ``` a b c f h x includes: a b c : true a c : true a a b : false g : false a c g : false A B C : true (case-insensitive) ``` ### See also | | | | --- | --- | | [set\_difference](set_difference "cpp/algorithm/set difference") | computes the difference between two sets (function template) | | [search](search "cpp/algorithm/search") | searches for a range of elements (function template) | | [ranges::includes](ranges/includes "cpp/algorithm/ranges/includes") (C++20) | returns true if one sequence is a subsequence of another (niebloid) | cpp std::generate_n std::generate\_n ================ | Defined in header `[<algorithm>](../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | | (1) | | | ``` template< class OutputIt, class Size, class Generator > void generate_n( OutputIt first, Size count, Generator g ); ``` | (until C++11) | | ``` template< class OutputIt, class Size, class Generator > OutputIt generate_n( OutputIt first, Size count, Generator g ); ``` | (since C++11) (until C++20) | | ``` template< class OutputIt, class Size, class Generator > constexpr OutputIt generate_n( OutputIt first, Size count, Generator g ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt , class Size, class Generator > ForwardIt generate_n( ExecutionPolicy&& policy, ForwardIt first, Size count, Generator g ); ``` | (2) | (since C++17) | 1) Assigns values, generated by given function object `g`, to the first `count` elements in the range beginning at `first`, if `count>0`. Does nothing otherwise. 2) Same as (1), but executed according to `policy`. This overload does not participate in overload resolution unless `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ExecutionPolicy>>` (until C++20) `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<ExecutionPolicy>>` (since C++20) is true. ### Parameters | | | | | --- | --- | --- | | first | - | the beginning of the range of elements to generate | | count | - | number of the elements to generate | | policy | - | the execution policy to use. See [execution policy](execution_policy_tag_t "cpp/algorithm/execution policy tag t") for details. | | g | - | generator function object that will be called. The signature of the function should be equivalent to the following: | | | | | --- | --- | --- | | ``` Ret fun(); ``` | | | The type `Ret` must be such that an object of type `OutputIt` can be dereferenced and assigned a value of type `Ret`. ​ | | Type requirements | | -`OutputIt` must meet the requirements of [LegacyOutputIterator](../named_req/outputiterator "cpp/named req/OutputIterator"). | | -`ForwardIt` must meet the requirements of [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"). | ### Return value | | | | --- | --- | | (none). | (until C++11) | | Iterator one past the last element assigned if `count>0`, `first` otherwise. | (since C++11) | ### Complexity Exactly `count` invocations of `g()` and assignments, for `count>0`. ### Exceptions The overload with a template parameter named `ExecutionPolicy` reports errors as follows: * If execution of a function invoked as part of the algorithm throws an exception and `ExecutionPolicy` is one of the [standard policies](execution_policy_tag_t "cpp/algorithm/execution policy tag t"), `[std::terminate](../error/terminate "cpp/error/terminate")` is called. For any other `ExecutionPolicy`, the behavior is implementation-defined. * If the algorithm fails to allocate memory, `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` is thrown. ### Possible implementation | | | --- | | ``` template< class OutputIt, class Size, class Generator > constexpr // since C++20 OutputIt // void until C++11 generate_n( OutputIt first, Size count, Generator g ) { for( Size i = 0; i < count; ++i ) { *first++ = g(); } return first; } ``` | ### Example ``` #include <random> #include <iostream> #include <iterator> #include <algorithm> #include <functional> int main() { std::mt19937 rng; // default constructed, seeded with fixed seed std::generate_n(std::ostream_iterator<std::mt19937::result_type>(std::cout, " "), 5, std::ref(rng)); std::cout << '\n'; } ``` Output: ``` 3499211612 581869302 3890346734 3586334585 545404204 ``` ### See also | | | | --- | --- | | [fill\_n](fill_n "cpp/algorithm/fill n") | copy-assigns the given value to N elements in a range (function template) | | [generate](generate "cpp/algorithm/generate") | assigns the results of successive function calls to every element in a range (function template) | | [ranges::generate\_n](ranges/generate_n "cpp/algorithm/ranges/generate n") (C++20) | saves the result of N applications of a function (niebloid) |
programming_docs
cpp std::binary_search std::binary\_search =================== | Defined in header `[<algorithm>](../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | | (1) | | | ``` template< class ForwardIt, class T > bool binary_search( ForwardIt first, ForwardIt last, const T& value ); ``` | (until C++20) | | ``` template< class ForwardIt, class T > constexpr bool binary_search( ForwardIt first, ForwardIt last, const T& value ); ``` | (since C++20) | | | (2) | | | ``` template< class ForwardIt, class T, class Compare > bool binary_search( ForwardIt first, ForwardIt last, const T& value, Compare comp ); ``` | (until C++20) | | ``` template< class ForwardIt, class T, class Compare > constexpr bool binary_search( ForwardIt first, ForwardIt last, const T& value, Compare comp ); ``` | (since C++20) | Checks if an element equivalent to `value` appears within the range `[first, last)`. For `std::binary_search` to succeed, the range `[first, last)` must be at least partially ordered with respect to `value`, i.e. it must satisfy all of the following requirements: * partitioned with respect to `element < value` or `comp(element, value)` (that is, all elements for which the expression is `true` precede all elements for which the expression is `false`) * partitioned with respect to `!(value < element)` or `!comp(value, element)` * for all elements, if `element < value` or `comp(element, value)` is `true` then `!(value < element)` or `!comp(value, element)` is also `true` A fully-sorted range meets these criteria. The first version uses `operator<` to compare the elements, the second version uses the given comparison function `comp`. ### Parameters | | | | | --- | --- | --- | | first, last | - | the range of elements to examine | | value | - | value to compare the elements to | | comp | - | binary predicate which returns ​`true` if the first argument is *less* than (i.e. is ordered before) the second. The signature of the predicate function should be equivalent to the following: `bool pred(const Type1 &a, const Type2 &b);` While the signature does not need to have `const &`, the function must not modify the objects passed to it and must be able to accept all values of type (possibly const) `Type1` and `Type2` regardless of [value category](../language/value_category "cpp/language/value category") (thus, `Type1 &` is not allowed, nor is `Type1` unless for `Type1` a move is equivalent to a copy (since C++11)). The types `Type1` and `Type2` must be such that an object of type `T` can be implicitly converted to both `Type1` and `Type2`, and an object of type `ForwardIt` can be dereferenced and then implicitly converted to both `Type1` and `Type2`. ​ | | Type requirements | | -`ForwardIt` must meet the requirements of [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"). | | -`Compare` must meet the requirements of [BinaryPredicate](../named_req/binarypredicate "cpp/named req/BinaryPredicate"). it is not required to satisfy [Compare](../named_req/compare "cpp/named req/Compare") | ### Return value `true` if an element equal to `value` is found, `false` otherwise. ### Complexity The number of comparisons performed is logarithmic in the distance between `first` and `last` (At most log 2(last - first) + O(1) comparisons). However, for non-[LegacyRandomAccessIterators](../named_req/randomaccessiterator "cpp/named req/RandomAccessIterator"), number of iterator increments is linear. ### Possible implementation See also the implementations in [libstdc++](https://github.com/gcc-mirror/gcc/blob/d9375e490072d1aae73a93949aa158fcd2a27018/libstdc%2B%2B-v3/include/bits/stl_algo.h#L2236) and [libc++](https://github.com/llvm-mirror/libcxx/blob/a12cb9d211019d99b5875b6d8034617cbc24c2cc/include/algorithm#L4320). | First version | | --- | | ``` template<class ForwardIt, class T> bool binary_search(ForwardIt first, ForwardIt last, const T& value) { first = std::lower_bound(first, last, value); return (!(first == last) && !(value < *first)); } ``` | | Second version | | ``` template<class ForwardIt, class T, class Compare> bool binary_search(ForwardIt first, ForwardIt last, const T& value, Compare comp) { first = std::lower_bound(first, last, value, comp); return (!(first == last) && !(comp(value, *first))); } ``` | ### Example ``` #include <iostream> #include <algorithm> #include <vector> int main() { std::vector<int> haystack {1, 3, 4, 5, 9}; std::vector<int> needles {1, 2, 3}; for (auto needle : needles) { std::cout << "Searching for " << needle << '\n'; if (std::binary_search(haystack.begin(), haystack.end(), needle)) { std::cout << "Found " << needle << '\n'; } else { std::cout << "no dice!\n"; } } } ``` Output: ``` Searching for 1 Found 1 Searching for 2 no dice! Searching for 3 Found 3 ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 270](https://cplusplus.github.io/LWG/issue270) | C++98 | Compare was required to be a strict weak ordering | only a partitioning is needed; heterogeneous comparisons permitted | ### See also | | | | --- | --- | | [equal\_range](equal_range "cpp/algorithm/equal range") | returns range of elements matching a specific key (function template) | | [lower\_bound](lower_bound "cpp/algorithm/lower bound") | returns an iterator to the first element *not less* than the given value (function template) | | [upper\_bound](upper_bound "cpp/algorithm/upper bound") | returns an iterator to the first element *greater* than a certain value (function template) | | [ranges::binary\_search](ranges/binary_search "cpp/algorithm/ranges/binary search") (C++20) | determines if an element exists in a partially-ordered range (niebloid) | cpp std::partition std::partition ============== | Defined in header `[<algorithm>](../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | | (1) | | | ``` template< class BidirIt, class UnaryPredicate > BidirIt partition( BidirIt first, BidirIt last, UnaryPredicate p ); ``` | (until C++11) | | ``` template< class ForwardIt, class UnaryPredicate > ForwardIt partition( ForwardIt first, ForwardIt last, UnaryPredicate p ); ``` | (since C++11) (until C++20) | | ``` template< class ForwardIt, class UnaryPredicate > constexpr ForwardIt partition( ForwardIt first, ForwardIt last, UnaryPredicate p ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt, class UnaryPredicate > ForwardIt partition( ExecutionPolicy&& policy, ForwardIt first, ForwardIt last, UnaryPredicate p ); ``` | (2) | (since C++17) | 1) Reorders the elements in the range `[first, last)` in such a way that all elements for which the predicate `p` returns `true` precede the elements for which predicate `p` returns `false`. Relative order of the elements is not preserved. 2) Same as (1), but executed according to `policy`. This overload does not participate in overload resolution unless `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ExecutionPolicy>>` (until C++20) `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<ExecutionPolicy>>` (since C++20) is true. ### Parameters | | | | | --- | --- | --- | | first, last | - | the range of elements to reorder | | policy | - | the execution policy to use. See [execution policy](execution_policy_tag_t "cpp/algorithm/execution policy tag t") for details. | | p | - | unary predicate which returns ​`true` if the element should be ordered before other elements. The expression `p(v)` must be convertible to `bool` for every argument `v` of type (possibly const) `VT`, where `VT` is the value type of `ForwardIt`, regardless of [value category](../language/value_category "cpp/language/value category"), and must not modify `v`. Thus, a parameter type of `VT&`is not allowed, nor is `VT` unless for `VT` a move is equivalent to a copy (since C++11). ​ | | Type requirements | | -`BidirIt` must meet the requirements of [LegacyBidirectionalIterator](../named_req/bidirectionaliterator "cpp/named req/BidirectionalIterator"). | | -`ForwardIt` must meet the requirements of [ValueSwappable](../named_req/valueswappable "cpp/named req/ValueSwappable") and [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"). However, the operation is more efficient if `ForwardIt` also satisfies the requirements of [LegacyBidirectionalIterator](../named_req/bidirectionaliterator "cpp/named req/BidirectionalIterator") | | -`UnaryPredicate` must meet the requirements of [Predicate](../named_req/predicate "cpp/named req/Predicate"). | ### Return value Iterator to the first element of the second group. ### Complexity Given N = `[std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(first,last)`, 1) Exactly N applications of the predicate. At most N/2 swaps if `ForwardIt` meets the requirements of [LegacyBidirectionalIterator](../named_req/bidirectionaliterator "cpp/named req/BidirectionalIterator"), and at most N swaps otherwise. 2) `O(N log N)` swaps `and O(N)` applications of the predicate. ### Exceptions The overload with a template parameter named `ExecutionPolicy` reports errors as follows: * If execution of a function invoked as part of the algorithm throws an exception and `ExecutionPolicy` is one of the [standard policies](execution_policy_tag_t "cpp/algorithm/execution policy tag t"), `[std::terminate](../error/terminate "cpp/error/terminate")` is called. For any other `ExecutionPolicy`, the behavior is implementation-defined. * If the algorithm fails to allocate memory, `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` is thrown. ### Possible implementation Implements overload (1) preserving C++11 compatibility. | | | --- | | ``` template<class ForwardIt, class UnaryPredicate> ForwardIt partition(ForwardIt first, ForwardIt last, UnaryPredicate p) { first = std::find_if_not(first, last, p); if (first == last) return first; for (auto i = std::next(first); i != last; ++i) { if (p(*i)) { std::iter_swap(i, first); ++first; } } return first; } ``` | ### Example ``` #include <algorithm> #include <iostream> #include <iterator> #include <vector> #include <forward_list> template <class ForwardIt> void quicksort(ForwardIt first, ForwardIt last) { if(first == last) return; auto pivot = *std::next(first, std::distance(first,last)/2); auto middle1 = std::partition(first, last, [pivot](const auto& em) { return em < pivot; }); auto middle2 = std::partition(middle1, last, [pivot](const auto& em) { return !(pivot < em); }); quicksort(first, middle1); quicksort(middle2, last); } int main() { std::vector<int> v = {0,1,2,3,4,5,6,7,8,9}; std::cout << "Original vector:\n "; for(int elem : v) std::cout << elem << ' '; auto it = std::partition(v.begin(), v.end(), [](int i){return i % 2 == 0;}); std::cout << "\nPartitioned vector:\n "; std::copy(std::begin(v), it, std::ostream_iterator<int>(std::cout, " ")); std::cout << " * " " "; std::copy(it, std::end(v), std::ostream_iterator<int>(std::cout, " ")); std::forward_list<int> fl = {1, 30, -4, 3, 5, -4, 1, 6, -8, 2, -5, 64, 1, 92}; std::cout << "\nUnsorted list:\n "; for(int n : fl) std::cout << n << ' '; std::cout << '\n'; quicksort(std::begin(fl), std::end(fl)); std::cout << "Sorted using quicksort:\n "; for(int fi : fl) std::cout << fi << ' '; std::cout << '\n'; } ``` Possible output: ``` Original vector: 0 1 2 3 4 5 6 7 8 9 Partitioned vector: 0 8 2 6 4 * 5 3 7 1 9 Unsorted list: 1 30 -4 3 5 -4 1 6 -8 2 -5 64 1 92 Sorted using quicksort: -8 -5 -4 -4 1 1 1 2 3 5 6 30 64 92 ``` ### See also | | | | --- | --- | | [is\_partitioned](is_partitioned "cpp/algorithm/is partitioned") (C++11) | determines if the range is partitioned by the given predicate (function template) | | [stable\_partition](stable_partition "cpp/algorithm/stable partition") | divides elements into two groups while preserving their relative order (function template) | | [ranges::partition](ranges/partition "cpp/algorithm/ranges/partition") (C++20) | divides a range of elements into two groups (niebloid) | cpp std::is_partitioned std::is\_partitioned ==================== | Defined in header `[<algorithm>](../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | | (1) | | | ``` template< class InputIt, class UnaryPredicate > bool is_partitioned( InputIt first, InputIt last, UnaryPredicate p ); ``` | (since C++11) (until C++20) | | ``` template< class InputIt, class UnaryPredicate > constexpr bool is_partitioned( InputIt first, InputIt last, UnaryPredicate p ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt, class UnaryPredicate > bool is_partitioned( ExecutionPolicy&& policy, ForwardIt first, ForwardIt last, UnaryPredicate p ); ``` | (2) | (since C++17) | 1) Returns `true` if all elements in the range `[first, last)` that satisfy the predicate `p` appear before all elements that don't. Also returns `true` if `[first, last)` is empty. 2) Same as (1), but executed according to `policy`. This overload does not participate in overload resolution unless `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ExecutionPolicy>>` (until C++20) `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<ExecutionPolicy>>` (since C++20) is true. ### Parameters | | | | | --- | --- | --- | | first, last | - | the range of elements to check | | policy | - | the execution policy to use. See [execution policy](execution_policy_tag_t "cpp/algorithm/execution policy tag t") for details. | | p | - | unary predicate which returns ​`true` for the elements expected to be found in the beginning of the range. The expression `p(v)` must be convertible to `bool` for every argument `v` of type (possibly const) `VT`, where `VT` is the value type of `InputIt`, regardless of [value category](../language/value_category "cpp/language/value category"), and must not modify `v`. Thus, a parameter type of `VT&`is not allowed, nor is `VT` unless for `VT` a move is equivalent to a copy (since C++11). ​ | | Type requirements | | -`InputIt` must meet the requirements of [LegacyInputIterator](../named_req/inputiterator "cpp/named req/InputIterator"). | | -`ForwardIt` must meet the requirements of [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"). and its value type must be convertible to UnaryPredicate's argument type | | -`UnaryPredicate` must meet the requirements of [Predicate](../named_req/predicate "cpp/named req/Predicate"). | ### Return value `true` if the range `[first, last)` is empty or is partitioned by `p`. `false` otherwise. ### Complexity At most `std::distance(first, last)` applications of `p`. ### Exceptions The overload with a template parameter named `ExecutionPolicy` reports errors as follows: * If execution of a function invoked as part of the algorithm throws an exception and `ExecutionPolicy` is one of the [standard policies](execution_policy_tag_t "cpp/algorithm/execution policy tag t"), `[std::terminate](../error/terminate "cpp/error/terminate")` is called. For any other `ExecutionPolicy`, the behavior is implementation-defined. * If the algorithm fails to allocate memory, `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` is thrown. ### Possible implementation | | | --- | | ``` template< class InputIt, class UnaryPredicate > bool is_partitioned(InputIt first, InputIt last, UnaryPredicate p) { for (; first != last; ++first) if (!p(*first)) break; for (; first != last; ++first) if (p(*first)) return false; return true; } ``` | ### Example ``` #include <algorithm> #include <array> #include <iostream> int main() { std::array<int, 9> v = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; auto is_even = [](int i){ return i % 2 == 0; }; std::cout.setf(std::ios_base::boolalpha); std::cout << std::is_partitioned(v.begin(), v.end(), is_even) << ' '; std::partition(v.begin(), v.end(), is_even); std::cout << std::is_partitioned(v.begin(), v.end(), is_even) << ' '; std::reverse(v.begin(), v.end()); std::cout << std::is_partitioned(v.cbegin(), v.cend(), is_even) << ' '; std::cout << std::is_partitioned(v.crbegin(), v.crend(), is_even) << '\n'; } ``` Output: ``` false true false true ``` ### See also | | | | --- | --- | | [partition](partition "cpp/algorithm/partition") | divides a range of elements into two groups (function template) | | [partition\_point](partition_point "cpp/algorithm/partition point") (C++11) | locates the partition point of a partitioned range (function template) | | [ranges::is\_partitioned](ranges/is_partitioned "cpp/algorithm/ranges/is partitioned") (C++20) | determines if the range is partitioned by the given predicate (niebloid) | cpp std::make_heap std::make\_heap =============== | Defined in header `[<algorithm>](../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | | (1) | | | ``` template< class RandomIt > void make_heap( RandomIt first, RandomIt last ); ``` | (until C++20) | | ``` template< class RandomIt > constexpr void make_heap( RandomIt first, RandomIt last ); ``` | (since C++20) | | | (2) | | | ``` template< class RandomIt, class Compare > void make_heap( RandomIt first, RandomIt last, Compare comp ); ``` | (until C++20) | | ``` template< class RandomIt, class Compare > constexpr void make_heap( RandomIt first, RandomIt last, Compare comp ); ``` | (since C++20) | Constructs a [*max heap*](https://en.wikipedia.org/wiki/Binary_heap "enwiki:Binary heap") in the range `[first, last)`. The first version of the function uses `operator<` to compare the elements, the second uses the given comparison function `comp`. ### Parameters | | | | | --- | --- | --- | | first, last | - | the range of elements to make the heap from | | comp | - | comparison function object (i.e. an object that satisfies the requirements of [Compare](../named_req/compare "cpp/named req/Compare")) which returns ​`true` if the first argument is *less* than the second. The signature of the comparison function should be equivalent to the following: `bool cmp(const Type1 &a, const Type2 &b);` While the signature does not need to have `const &`, the function must not modify the objects passed to it and must be able to accept all values of type (possibly const) `Type1` and `Type2` regardless of [value category](../language/value_category "cpp/language/value category") (thus, `Type1 &` is not allowed, nor is `Type1` unless for `Type1` a move is equivalent to a copy (since C++11)). The types `Type1` and `Type2` must be such that an object of type `RandomIt` can be dereferenced and then implicitly converted to both of them. ​ | | Type requirements | | -`RandomIt` must meet the requirements of [LegacyRandomAccessIterator](../named_req/randomaccessiterator "cpp/named req/RandomAccessIterator"). | | -The type of dereferenced `RandomIt` must meet the requirements of [MoveAssignable](../named_req/moveassignable "cpp/named req/MoveAssignable") and [MoveConstructible](../named_req/moveconstructible "cpp/named req/MoveConstructible"). | ### Return value (none). ### Complexity At most `3\*[std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(first, last)` comparisons. ### Notes A *max heap* is a range of elements `[f,l)` that has the following properties: * With `N = l-f`, for all `0 < i < N`, `f[(i-1)/2]` does not compare less than `f[i]`. * A new element can be added using `[std::push\_heap](push_heap "cpp/algorithm/push heap")`, in \(\scriptsize \mathcal{O}(\log N)\)𝓞(log N) time. * The first element can be removed using `[std::pop\_heap](pop_heap "cpp/algorithm/pop heap")`, in \(\scriptsize \mathcal{O}(\log N)\)𝓞(log N) time. ### Example ``` #include <algorithm> #include <functional> #include <iostream> #include <string_view> #include <vector> void print(std::string_view text, std::vector<int> const& v = {}) { std::cout << text << ": "; for (const auto& e : v) std::cout << e << ' '; std::cout << '\n'; } int main() { print("Max heap"); std::vector<int> v { 3, 2, 4, 1, 5, 9 }; print("initially, v", v); std::make_heap(v.begin(), v.end()); print("after make_heap, v", v); std::pop_heap(v.begin(), v.end()); print("after pop_heap, v", v); auto top = v.back(); v.pop_back(); print("former top element", {top}); print("after removing the former top element, v", v); print("\nMin heap"); std::vector<int> v1 { 3, 2, 4, 1, 5, 9 }; print("initially, v1", v1); std::make_heap(v1.begin(), v1.end(), std::greater<>{}); print("after make_heap, v1", v1); std::pop_heap(v1.begin(), v1.end(), std::greater<>{}); print("after pop_heap, v1", v1); auto top1 = v1.back(); v1.pop_back(); print("former top element", {top1}); print("after removing the former top element, v1", v1); } ``` Output: ``` Max heap: initially, v: 3 2 4 1 5 9 after make_heap, v: 9 5 4 1 2 3 after pop_heap, v: 5 3 4 1 2 9 former top element: 9 after removing the former top element, v: 5 3 4 1 2 Min heap: initially, v1: 3 2 4 1 5 9 after make_heap, v1: 1 2 4 3 5 9 after pop_heap, v1: 2 3 4 9 5 1 former top element: 1 after removing the former top element, v1: 2 3 4 9 5 ``` ### See also | | | | --- | --- | | [is\_heap](is_heap "cpp/algorithm/is heap") (C++11) | checks if the given range is a max heap (function template) | | [is\_heap\_until](is_heap_until "cpp/algorithm/is heap until") (C++11) | finds the largest subrange that is a max heap (function template) | | [push\_heap](push_heap "cpp/algorithm/push heap") | adds an element to a max heap (function template) | | [pop\_heap](pop_heap "cpp/algorithm/pop heap") | removes the largest element from a max heap (function template) | | [sort\_heap](sort_heap "cpp/algorithm/sort heap") | turns a max heap into a range of elements sorted in ascending order (function template) | | [priority\_queue](../container/priority_queue "cpp/container/priority queue") | adapts a container to provide priority queue (class template) | | [ranges::make\_heap](ranges/make_heap "cpp/algorithm/ranges/make heap") (C++20) | creates a max heap out of a range of elements (niebloid) |
programming_docs
cpp std::search std::search =========== | Defined in header `[<algorithm>](../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | | (1) | | | ``` template< class ForwardIt1, class ForwardIt2 > ForwardIt1 search( ForwardIt1 first, ForwardIt1 last, ForwardIt2 s_first, ForwardIt2 s_last ); ``` | (until C++20) | | ``` template< class ForwardIt1, class ForwardIt2 > constexpr ForwardIt1 search( ForwardIt1 first, ForwardIt1 last, ForwardIt2 s_first, ForwardIt2 s_last ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt1, class ForwardIt2 > ForwardIt1 search( ExecutionPolicy&& policy, ForwardIt1 first, ForwardIt1 last, ForwardIt2 s_first, ForwardIt2 s_last ); ``` | (2) | (since C++17) | | | (3) | | | ``` template< class ForwardIt1, class ForwardIt2, class BinaryPredicate > ForwardIt1 search( ForwardIt1 first, ForwardIt1 last, ForwardIt2 s_first, ForwardIt2 s_last, BinaryPredicate p ); ``` | (until C++20) | | ``` template< class ForwardIt1, class ForwardIt2, class BinaryPredicate > constexpr ForwardIt1 search( ForwardIt1 first, ForwardIt1 last, ForwardIt2 s_first, ForwardIt2 s_last, BinaryPredicate p ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt1, class ForwardIt2, class BinaryPredicate > ForwardIt1 search( ExecutionPolicy&& policy, ForwardIt1 first, ForwardIt1 last, ForwardIt2 s_first, ForwardIt2 s_last, BinaryPredicate p ); ``` | (4) | (since C++17) | | | (5) | | | ``` template< class ForwardIt, class Searcher > ForwardIt search( ForwardIt first, ForwardIt last, const Searcher& searcher ); ``` | (since C++17) (until C++20) | | ``` template< class ForwardIt, class Searcher > constexpr ForwardIt search( ForwardIt first, ForwardIt last, const Searcher& searcher ); ``` | (since C++20) | 1-4) Searches for the first occurrence of the sequence of elements `[s_first, s_last)` in the range `[first, last)`. 1) Elements are compared using `operator==`. 3) Elements are compared using the given binary predicate `p`. 2,4) Same as (1,3), but executed according to `policy`. These overloads do not participate in overload resolution unless `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ExecutionPolicy>>` (until C++20) `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<ExecutionPolicy>>` (since C++20) is true. 5) Searches the sequence [first, last) for the pattern specified in the constructor of `searcher`. Effectively executes `return searcher(first, last).first;`. `Searcher` need not be [CopyConstructible](../named_req/copyconstructible "cpp/named req/CopyConstructible"). | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | | The standard library provides the following searchers: | | | | --- | --- | | [default\_searcher](../utility/functional/default_searcher "cpp/utility/functional/default searcher") (C++17) | standard C++ library search algorithm implementation (class template) | | [boyer\_moore\_searcher](../utility/functional/boyer_moore_searcher "cpp/utility/functional/boyer moore searcher") (C++17) | Boyer-Moore search algorithm implementation (class template) | | [boyer\_moore\_horspool\_searcher](../utility/functional/boyer_moore_horspool_searcher "cpp/utility/functional/boyer moore horspool searcher") (C++17) | Boyer-Moore-Horspool search algorithm implementation (class template) | | (since C++17) | ### Parameters | | | | | --- | --- | --- | | first, last | - | the range of elements to examine | | s\_first, s\_last | - | the range of elements to search for | | policy | - | the execution policy to use. See [execution policy](execution_policy_tag_t "cpp/algorithm/execution policy tag t") for details. | | searcher | - | the searcher encapsulating the search algorithm and the pattern to look for | | p | - | binary predicate which returns ​`true` if the elements should be treated as equal. The signature of the predicate function should be equivalent to the following: `bool pred(const Type1 &a, const Type2 &b);` While the signature does not need to have `const &`, the function must not modify the objects passed to it and must be able to accept all values of type (possibly const) `Type1` and `Type2` regardless of [value category](../language/value_category "cpp/language/value category") (thus, `Type1 &` is not allowed, nor is `Type1` unless for `Type1` a move is equivalent to a copy (since C++11)). The types `Type1` and `Type2` must be such that objects of types `ForwardIt1` and `ForwardIt2` can be dereferenced and then implicitly converted to `Type1` and `Type2` respectively. ​ | | Type requirements | | -`ForwardIt1, ForwardIt2` must meet the requirements of [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"). | | -`Searcher` must meet the requirements of [Searcher](https://en.cppreference.com/mwiki/index.php?title=cpp/named_req/Searcher&action=edit&redlink=1 "cpp/named req/Searcher (page does not exist)"). | ### Return value 1-4) Iterator to the beginning of first occurrence of the sequence `[s_first, s_last)` in the range `[first, last)`. If no such occurrence is found, `last` is returned. If `[s_first, s_last)` is empty, `first` is returned. (since C++11) 5) Returns the result of `searcher.operator()`, that is, an iterator to the location at which the substring is found or a copy of `last` if it was not found. ### Complexity 1-4) At most `S*N` comparisons where `S = [std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(s_first, s_last)` and `N = [std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(first, last)`. 5) Depends on the searcher ### Exceptions The overloads with a template parameter named `ExecutionPolicy` report errors as follows: * If execution of a function invoked as part of the algorithm throws an exception and `ExecutionPolicy` is one of the [standard policies](execution_policy_tag_t "cpp/algorithm/execution policy tag t"), `[std::terminate](../error/terminate "cpp/error/terminate")` is called. For any other `ExecutionPolicy`, the behavior is implementation-defined. * If the algorithm fails to allocate memory, `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` is thrown. ### Possible implementation | First version | | --- | | ``` template<class ForwardIt1, class ForwardIt2> constexpr ForwardIt1 search(ForwardIt1 first, ForwardIt1 last, ForwardIt2 s_first, ForwardIt2 s_last) { while (1) { ForwardIt1 it = first; for (ForwardIt2 s_it = s_first; ; ++it, ++s_it) { if (s_it == s_last) return first; if (it == last) return last; if (!(*it == *s_it)) break; } ++first; } } ``` | | Second version | | ``` template<class ForwardIt1, class ForwardIt2, class BinaryPredicate> constexpr ForwardIt1 search(ForwardIt1 first, ForwardIt1 last, ForwardIt2 s_first, ForwardIt2 s_last, BinaryPredicate p) { while (1) { ForwardIt1 it = first; for (ForwardIt2 s_it = s_first; ; ++it, ++s_it) { if (s_it == s_last) return first; if (it == last) return last; if (!p(*it, *s_it)) break; } ++first; } } ``` | ### Example ``` #include <string_view> #include <functional> #include <algorithm> #include <iostream> #include <iomanip> #include <vector> #include <string> template <typename Container> bool contains(const Container& cont, const std::string& s) { return std::search(cont.begin(), cont.end(), s.begin(), s.end()) != cont.end(); } int main() { std::string str = "why waste time learning, when ignorance is instantaneous?"; // str.find() can be used as well std::cout << std::boolalpha << contains(str, "learning") << '\n' // true << contains(str, "lemming") << '\n'; // false std::vector<char> vec(str.begin(), str.end()); std::cout << contains(vec, "learning") << '\n' // true << contains(vec, "leaning") << '\n'; // false // The C++17 overload demo: constexpr std::string_view haystack = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed " "do eiusmod tempor incididunt ut labore et dolore magna aliqua"; const std::string needle {"pisci"}; if (auto it = std::search(haystack.begin(), haystack.end(), std::boyer_moore_searcher(needle.begin(), needle.end())); it != haystack.end()) { std::cout << "The string " << quoted(needle, '\'') << " found at offset " << it - haystack.begin() << '\n'; } else { std::cout << "The string " << std::quoted(needle) << " not found\n"; } } ``` Output: ``` true false true false The string 'pisci' found at offset 43 ``` ### See also | | | | --- | --- | | [find\_end](find_end "cpp/algorithm/find end") | finds the last sequence of elements in a certain range (function template) | | [includes](includes "cpp/algorithm/includes") | returns true if one sequence is a subsequence of another (function template) | | [equal](equal "cpp/algorithm/equal") | determines if two sets of elements are the same (function template) | | [findfind\_iffind\_if\_not](find "cpp/algorithm/find") (C++11) | finds the first element satisfying specific criteria (function template) | | [lexicographical\_compare](lexicographical_compare "cpp/algorithm/lexicographical compare") | returns true if one range is lexicographically less than another (function template) | | [mismatch](mismatch "cpp/algorithm/mismatch") | finds the first position where two ranges differ (function template) | | [search\_n](search_n "cpp/algorithm/search n") | searches a range for a number of consecutive copies of an element (function template) | | [default\_searcher](../utility/functional/default_searcher "cpp/utility/functional/default searcher") (C++17) | standard C++ library search algorithm implementation (class template) | | [boyer\_moore\_searcher](../utility/functional/boyer_moore_searcher "cpp/utility/functional/boyer moore searcher") (C++17) | Boyer-Moore search algorithm implementation (class template) | | [boyer\_moore\_horspool\_searcher](../utility/functional/boyer_moore_horspool_searcher "cpp/utility/functional/boyer moore horspool searcher") (C++17) | Boyer-Moore-Horspool search algorithm implementation (class template) | | [ranges::search](ranges/search "cpp/algorithm/ranges/search") (C++20) | searches for a range of elements (niebloid) | cpp std::sort_heap std::sort\_heap =============== | Defined in header `[<algorithm>](../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | | (1) | | | ``` template< class RandomIt > void sort_heap( RandomIt first, RandomIt last ); ``` | (until C++20) | | ``` template< class RandomIt > constexpr void sort_heap( RandomIt first, RandomIt last ); ``` | (since C++20) | | | (2) | | | ``` template< class RandomIt, class Compare > void sort_heap( RandomIt first, RandomIt last, Compare comp ); ``` | (until C++20) | | ``` template< class RandomIt, class Compare > constexpr void sort_heap( RandomIt first, RandomIt last, Compare comp ); ``` | (since C++20) | Converts the [*max heap*](https://en.wikipedia.org/wiki/Binary_heap "enwiki:Binary heap") `[first, last)` into a sorted range in ascending order. The resulting range no longer has the heap property. The first version of the function uses `operator<` to compare the elements, the second uses the given comparison function `comp`. ### Parameters | | | | | --- | --- | --- | | first, last | - | the range of elements to sort | | comp | - | comparison function object (i.e. an object that satisfies the requirements of [Compare](../named_req/compare "cpp/named req/Compare")) which returns ​`true` if the first argument is *less* than the second. The signature of the comparison function should be equivalent to the following: `bool cmp(const Type1 &a, const Type2 &b);` While the signature does not need to have `const &`, the function must not modify the objects passed to it and must be able to accept all values of type (possibly const) `Type1` and `Type2` regardless of [value category](../language/value_category "cpp/language/value category") (thus, `Type1 &` is not allowed, nor is `Type1` unless for `Type1` a move is equivalent to a copy (since C++11)). The types `Type1` and `Type2` must be such that an object of type `RandomIt` can be dereferenced and then implicitly converted to both of them. ​ | | Type requirements | | -`RandomIt` must meet the requirements of [ValueSwappable](../named_req/valueswappable "cpp/named req/ValueSwappable") and [LegacyRandomAccessIterator](../named_req/randomaccessiterator "cpp/named req/RandomAccessIterator"). | | -The type of dereferenced `RandomIt` must meet the requirements of [MoveAssignable](../named_req/moveassignable "cpp/named req/MoveAssignable") and [MoveConstructible](../named_req/moveconstructible "cpp/named req/MoveConstructible"). | ### Return value (none). ### Complexity At most *2×N×log(N)* comparisons where `N=[std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(first, last)`. ### Notes A *max heap* is a range of elements `[f,l)` that has the following properties: * With `N = l-f`, for all `0 < i < N`, `f[(i-1)/2]` does not compare less than `f[i]`. * A new element can be added using `[std::push\_heap](push_heap "cpp/algorithm/push heap")`, in \(\scriptsize \mathcal{O}(\log N)\)𝓞(log N) time. * The first element can be removed using `[std::pop\_heap](pop_heap "cpp/algorithm/pop heap")`, in \(\scriptsize \mathcal{O}(\log N)\)𝓞(log N) time. ### Possible implementation | First version | | --- | | ``` template< class RandomIt > void sort_heap( RandomIt first, RandomIt last ) { while (first != last) std::pop_heap(first, last--); } ``` | | Second version | | ``` template< class RandomIt, class Compare > void sort_heap( RandomIt first, RandomIt last, Compare comp ) { while (first != last) std::pop_heap(first, last--, comp); } ``` | ### Example ``` #include <algorithm> #include <vector> #include <iostream> int main() { std::vector<int> v = {3, 1, 4, 1, 5, 9}; std::make_heap(v.begin(), v.end()); std::cout << "heap:\t"; for (const auto &i : v) { std::cout << i << ' '; } std::sort_heap(v.begin(), v.end()); std::cout << "\nsorted:\t"; for (const auto &i : v) { std::cout << i << ' '; } std::cout << '\n'; } ``` Output: ``` heap: 9 4 5 1 1 3 sorted: 1 1 3 4 5 9 ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 2444](https://cplusplus.github.io/LWG/issue2444) | C++98 | complexity requirement was wrong by a factor of 2 | corrected | ### See also | | | | --- | --- | | [is\_heap](is_heap "cpp/algorithm/is heap") (C++11) | checks if the given range is a max heap (function template) | | [is\_heap\_until](is_heap_until "cpp/algorithm/is heap until") (C++11) | finds the largest subrange that is a max heap (function template) | | [make\_heap](make_heap "cpp/algorithm/make heap") | creates a max heap out of a range of elements (function template) | | [pop\_heap](pop_heap "cpp/algorithm/pop heap") | removes the largest element from a max heap (function template) | | [push\_heap](push_heap "cpp/algorithm/push heap") | adds an element to a max heap (function template) | | [ranges::sort\_heap](ranges/sort_heap "cpp/algorithm/ranges/sort heap") (C++20) | turns a max heap into a range of elements sorted in ascending order (niebloid) | cpp std::is_permutation std::is\_permutation ==================== | Defined in header `[<algorithm>](../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | | (1) | | | ``` template< class ForwardIt1, class ForwardIt2 > bool is_permutation( ForwardIt1 first1, ForwardIt1 last1, ForwardIt2 first2 ); ``` | (since C++11) (until C++20) | | ``` template< class ForwardIt1, class ForwardIt2 > constexpr bool is_permutation( ForwardIt1 first1, ForwardIt1 last1, ForwardIt2 first2 ); ``` | (since C++20) | | | (2) | | | ``` template< class ForwardIt1, class ForwardIt2, class BinaryPredicate > bool is_permutation( ForwardIt1 first1, ForwardIt1 last1, ForwardIt2 first2, BinaryPredicate p ); ``` | (since C++11) (until C++20) | | ``` template< class ForwardIt1, class ForwardIt2, class BinaryPredicate > constexpr bool is_permutation( ForwardIt1 first1, ForwardIt1 last1, ForwardIt2 first2, BinaryPredicate p ); ``` | (since C++20) | | | (3) | | | ``` template< class ForwardIt1, class ForwardIt2 > bool is_permutation( ForwardIt1 first1, ForwardIt1 last1, ForwardIt2 first2, ForwardIt2 last2 ); ``` | (since C++14) (until C++20) | | ``` template< class ForwardIt1, class ForwardIt2 > constexpr bool is_permutation( ForwardIt1 first1, ForwardIt1 last1, ForwardIt2 first2, ForwardIt2 last2 ); ``` | (since C++20) | | | (4) | | | ``` template< class ForwardIt1, class ForwardIt2, class BinaryPredicate > bool is_permutation( ForwardIt1 first1, ForwardIt1 last1, ForwardIt2 first2, ForwardIt2 last2, BinaryPredicate p ); ``` | (since C++14) (until C++20) | | ``` template< class ForwardIt1, class ForwardIt2, class BinaryPredicate > constexpr bool is_permutation( ForwardIt1 first1, ForwardIt1 last1, ForwardIt2 first2, ForwardIt2 last2, BinaryPredicate p ); ``` | (since C++20) | Returns `true` if there exists a permutation of the elements in the range `[first1, last1)` that makes that range equal to the range `[first2,last2)`, where `last2` denotes `first2 + (last1 - first1)` if it was not given. 1,3) Elements are compared using `operator==`. The behavior is undefined if it is not an [equivalence relation](https://en.wikipedia.org/wiki/equivalence_relation "enwiki:equivalence relation"). 2,4) Elements are compared using the given binary predicate `p`. The behavior is undefined if it is not an equivalence relation. ### Parameters | | | | | --- | --- | --- | | first1, last1 | - | the range of elements to compare | | first2, last2 | - | the second range to compare | | p | - | binary predicate which returns `true` if the elements should be treated as equal. The signature of the predicate function should be equivalent to the following: `bool pred(const Type &a, const Type &b);` `Type` should be the value type of both `ForwardIt1` and `ForwardIt2`. The signature does not need to have `const &`, but the function must not modify the objects passed to it. | | Type requirements | | -`ForwardIt1, ForwardIt2` must meet the requirements of [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"). | | -`ForwardIt1, ForwardIt2` must have the same value type. | ### Return value `true` if the range `[first1, last1)` is a permutation of the range `[first2, last2)`. ### Complexity At most \(\scriptsize \mathcal{O}(N^2)\)O(N2) applications of the predicate, or exactly \(\scriptsize N\)N if the sequences are already equal, where \(\scriptsize N\)N is `[std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(first1, last1)`. However if `ForwardIt1` and `ForwardIt2` meet the requirements of [LegacyRandomAccessIterator](../named_req/randomaccessiterator "cpp/named req/RandomAccessIterator") and `[std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(first1, last1) != [std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(first2, last2)` no applications of the predicate are made. ### Note The **`std::is_permutation`** can be used in *testing*, namely to check the correctness of rearranging algorithms (e.g. sorting, shuffling, partitioning). If `x` is an original range and `y` is a *permuted* range then `std::is_permutation(x, y) == true` means that `y` consist of *"the same"* elements, maybe staying at other positions. ### Possible implementation | | | --- | | ``` template<class ForwardIt1, class ForwardIt2> bool is_permutation(ForwardIt1 first, ForwardIt1 last, ForwardIt2 d_first) { // skip common prefix std::tie(first, d_first) = std::mismatch(first, last, d_first); // iterate over the rest, counting how many times each element // from [first, last) appears in [d_first, d_last) if (first != last) { ForwardIt2 d_last = std::next(d_first, std::distance(first, last)); for (ForwardIt1 i = first; i != last; ++i) { if (i != std::find(first, i, *i)) continue; // this *i has been checked auto m = std::count(d_first, d_last, *i); if (m==0 || std::count(i, last, *i) != m) { return false; } } } return true; } ``` | ### Example ``` #include <iostream> #include <algorithm> template<typename Os, typename V> Os& operator<< (Os& os, V const& v) { os << "{ "; for (auto const& e : v) os << e << ' '; return os << "}"; } int main() { static constexpr auto v1 = {1,2,3,4,5}; static constexpr auto v2 = {3,5,4,1,2}; static constexpr auto v3 = {3,5,4,1,1}; std::cout << v2 << " is a permutation of " << v1 << ": " << std::boolalpha << std::is_permutation(v1.begin(), v1.end(), v2.begin()) << '\n' << v3 << " is a permutation of " << v1 << ": " << std::boolalpha << std::is_permutation(v1.begin(), v1.end(), v3.begin()) << '\n'; } ``` Output: ``` { 3 5 4 1 2 } is a permutation of { 1 2 3 4 5 }: true { 3 5 4 1 1 } is a permutation of { 1 2 3 4 5 }: false ``` ### See also | | | | --- | --- | | [next\_permutation](next_permutation "cpp/algorithm/next permutation") | generates the next greater lexicographic permutation of a range of elements (function template) | | [prev\_permutation](prev_permutation "cpp/algorithm/prev permutation") | generates the next smaller lexicographic permutation of a range of elements (function template) | | [equivalence\_relation](../concepts/equivalence_relation "cpp/concepts/equivalence relation") (C++20) | specifies that a [`relation`](../concepts/relation "cpp/concepts/relation") imposes an equivalence relation (concept) | | [ranges::is\_permutation](ranges/is_permutation "cpp/algorithm/ranges/is permutation") (C++20) | determines if a sequence is a permutation of another sequence (niebloid) |
programming_docs
cpp std::is_execution_policy std::is\_execution\_policy ========================== | Defined in header `[<execution>](../header/execution "cpp/header/execution")` | | | | --- | --- | --- | | ``` template< class T > struct is_execution_policy; ``` | | (since C++17) | Checks whether `T` is a standard or implementation-defined execution policy type. Provides the member constant `value` which is equal to `true`, if `T` is [a standard execution policy type](execution_policy_tag_t "cpp/algorithm/execution policy tag t"), or an implementation-defined execution policy type. Otherwise, `value` is equal to `false`. The behavior of a program that adds specializations for `is_execution_policy` or `is_execution_policy_v` is undefined. ### Template parameters | | | | | --- | --- | --- | | T | - | a type to check | ### Helper template | Defined in header `[<execution>](../header/execution "cpp/header/execution")` | | | | --- | --- | --- | | ``` template< class T > inline constexpr bool is_execution_policy_v = std::is_execution_policy<T>::value; ``` | | (since C++17) | Inherited from [std::integral\_constant](../types/integral_constant "cpp/types/integral constant") ---------------------------------------------------------------------------------------------------- ### Member constants | | | | --- | --- | | value [static] | `true` if `T` is a standard or implementation-defined execution policy type, `false` otherwise (public static member constant) | ### Member functions | | | | --- | --- | | operator bool | converts the object to `bool`, returns `value` (public member function) | | operator() (C++14) | returns `value` (public member function) | ### Member types | Type | Definition | | --- | --- | | `value_type` | `bool` | | `type` | `[std::integral\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<bool, value>` | ### See also | | | | --- | --- | | [sequenced\_policyparallel\_policyparallel\_unsequenced\_policyunsequenced\_policy](execution_policy_tag_t "cpp/algorithm/execution policy tag t") (C++17)(C++17)(C++17)(C++20) | execution policy types (class) | | [seqparpar\_unsequnseq](execution_policy_tag "cpp/algorithm/execution policy tag") (C++17)(C++17)(C++17)(C++20) | global execution policy objects (constant) | cpp std::copy, std::copy_if std::copy, std::copy\_if ======================== | Defined in header `[<algorithm>](../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | | (1) | | | ``` template< class InputIt, class OutputIt > OutputIt copy( InputIt first, InputIt last, OutputIt d_first ); ``` | (until C++20) | | ``` template< class InputIt, class OutputIt > constexpr OutputIt copy( InputIt first, InputIt last, OutputIt d_first ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt1, class ForwardIt2 > ForwardIt2 copy( ExecutionPolicy&& policy, ForwardIt1 first, ForwardIt1 last, ForwardIt2 d_first ); ``` | (2) | (since C++17) | | | (3) | | | ``` template< class InputIt, class OutputIt, class UnaryPredicate > OutputIt copy_if( InputIt first, InputIt last, OutputIt d_first, UnaryPredicate pred ); ``` | (since C++11) (until C++20) | | ``` template< class InputIt, class OutputIt, class UnaryPredicate > constexpr OutputIt copy_if( InputIt first, InputIt last, OutputIt d_first, UnaryPredicate pred ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt1, class ForwardIt2, class UnaryPredicate > ForwardIt2 copy_if( ExecutionPolicy&& policy, ForwardIt1 first, ForwardIt1 last, ForwardIt2 d_first, UnaryPredicate pred ); ``` | (4) | (since C++17) | Copies the elements in the range, defined by `[first, last)`, to another range beginning at `d_first`. 1) Copies all elements in the range `[first, last)` starting from first and proceeding to last - 1. The behavior is undefined if `d_first` is within the range `[first, last)`. In this case, `[std::copy\_backward](copy_backward "cpp/algorithm/copy backward")` may be used instead. 3) Only copies the elements for which the predicate `pred` returns `true`. The relative order of the elements that are copied is preserved. The behavior is undefined if the source and the destination ranges overlap. 2,4) Same as (1,3), but executed according to `policy`. These overloads do not participate in overload resolution unless `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ExecutionPolicy>>` (until C++20) `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<ExecutionPolicy>>` (since C++20) is true. ### Parameters | | | | | --- | --- | --- | | first, last | - | the range of elements to copy | | d\_first | - | the beginning of the destination range. | | policy | - | the execution policy to use. See [execution policy](execution_policy_tag_t "cpp/algorithm/execution policy tag t") for details. | | pred | - | unary predicate which returns ​`true` for the required elements. The expression `pred(v)` must be convertible to `bool` for every argument `v` of type (possibly const) `VT`, where `VT` is the value type of `InputIt`, regardless of [value category](../language/value_category "cpp/language/value category"), and must not modify `v`. Thus, a parameter type of `VT&`is not allowed, nor is `VT` unless for `VT` a move is equivalent to a copy (since C++11). ​ | | Type requirements | | -`InputIt` must meet the requirements of [LegacyInputIterator](../named_req/inputiterator "cpp/named req/InputIterator"). | | -`OutputIt` must meet the requirements of [LegacyOutputIterator](../named_req/outputiterator "cpp/named req/OutputIterator"). | | -`ForwardIt1, ForwardIt2` must meet the requirements of [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"). | | -`UnaryPredicate` must meet the requirements of [Predicate](../named_req/predicate "cpp/named req/Predicate"). | ### Return value Output iterator to the element in the destination range, one past the last element copied. ### Complexity 1-2) Exactly `(last - first)` assignments 3-4) Exactly `(last - first)` applications of the predicate, between `​0​` and `(last - first)` assignments (assignment for every element for which predicate is equal to true, dependent on predicate and input data) For the overloads with an ExecutionPolicy, there may be a performance cost if `ForwardIt1`'s value type is not [MoveConstructible](../named_req/moveconstructible "cpp/named req/MoveConstructible"). ### Exceptions The overloads with a template parameter named `ExecutionPolicy` report errors as follows: * If execution of a function invoked as part of the algorithm throws an exception and `ExecutionPolicy` is one of the [standard policies](execution_policy_tag_t "cpp/algorithm/execution policy tag t"), `[std::terminate](../error/terminate "cpp/error/terminate")` is called. For any other `ExecutionPolicy`, the behavior is implementation-defined. * If the algorithm fails to allocate memory, `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` is thrown. ### Notes In practice, implementations of `std::copy` avoid multiple assignments and use bulk copy functions such as `[std::memmove](../string/byte/memmove "cpp/string/byte/memmove")` if the value type is [TriviallyCopyable](../named_req/triviallycopyable "cpp/named req/TriviallyCopyable") and the iterator types satisfy [LegacyContiguousIterator](../named_req/contiguousiterator "cpp/named req/ContiguousIterator"). When copying overlapping ranges, `std::copy` is appropriate when copying to the left (beginning of the destination range is outside the source range) while `std::copy_backward` is appropriate when copying to the right (end of the destination range is outside the source range). ### Possible implementation | First version | | --- | | ``` template<class InputIt, class OutputIt> OutputIt copy(InputIt first, InputIt last, OutputIt d_first) { for (; first != last; (void)++first, (void)++d_first) { *d_first = *first; } return d_first; } ``` | | Second version | | ``` template<class InputIt, class OutputIt, class UnaryPredicate> OutputIt copy_if(InputIt first, InputIt last, OutputIt d_first, UnaryPredicate pred) { for (; first != last; ++first) { if (pred(*first)) { *d_first = *first; ++d_first; } } return d_first; } ``` | ### Example The following code uses `copy` to both copy the contents of one `vector` to another and to display the resulting `vector`: ``` #include <algorithm> #include <iostream> #include <vector> #include <iterator> #include <numeric> int main() { std::vector<int> from_vector(10); std::iota(from_vector.begin(), from_vector.end(), 0); std::vector<int> to_vector; std::copy(from_vector.begin(), from_vector.end(), std::back_inserter(to_vector)); // or, alternatively, // std::vector<int> to_vector(from_vector.size()); // std::copy(from_vector.begin(), from_vector.end(), to_vector.begin()); // either way is equivalent to // std::vector<int> to_vector = from_vector; std::cout << "to_vector contains: "; std::copy(to_vector.begin(), to_vector.end(), std::ostream_iterator<int>(std::cout, " ")); std::cout << '\n'; std::cout << "odd numbers in to_vector are: "; std::copy_if(to_vector.begin(), to_vector.end(), std::ostream_iterator<int>(std::cout, " "), [](int x) { return x % 2 != 0; }); std::cout << '\n'; std::cout << "to_vector contains these multiples of 3:\n"; to_vector.clear(); std::copy_if(from_vector.begin(), from_vector.end(), std::back_inserter(to_vector), [](int x) { return x % 3 == 0; }); for (int x : to_vector) std::cout << x << ' '; std::cout << '\n'; } ``` Possible output: ``` to_vector contains: 0 1 2 3 4 5 6 7 8 9 odd numbers in to_vector are: 1 3 5 7 9 to_vector contains these multiples of 3: 0 3 6 9 ``` ### See also | | | | --- | --- | | [copy\_backward](copy_backward "cpp/algorithm/copy backward") | copies a range of elements in backwards order (function template) | | [reverse\_copy](reverse_copy "cpp/algorithm/reverse copy") | creates a copy of a range that is reversed (function template) | | [copy\_n](copy_n "cpp/algorithm/copy n") (C++11) | copies a number of elements to a new location (function template) | | [fill](fill "cpp/algorithm/fill") | copy-assigns the given value to every element in a range (function template) | | [remove\_copyremove\_copy\_if](remove_copy "cpp/algorithm/remove copy") | copies a range of elements omitting those that satisfy specific criteria (function template) | | [ranges::copyranges::copy\_if](ranges/copy "cpp/algorithm/ranges/copy") (C++20)(C++20) | copies a range of elements to a new location (niebloid) | cpp std::iter_swap std::iter\_swap =============== | Defined in header `[<algorithm>](../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | ``` template< class ForwardIt1, class ForwardIt2 > void iter_swap( ForwardIt1 a, ForwardIt2 b ); ``` | | (until C++20) | | ``` template< class ForwardIt1, class ForwardIt2 > constexpr void iter_swap( ForwardIt1 a, ForwardIt2 b ); ``` | | (since C++20) | Swaps the values of the elements the given iterators are pointing to. ### Parameters | | | | | --- | --- | --- | | a, b | - | iterators to the elements to swap | | Type requirements | | -`ForwardIt1, ForwardIt2` must meet the requirements of [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"). | | -`*a, *b` must meet the requirements of [Swappable](../named_req/swappable "cpp/named req/Swappable"). | ### Return value (none). ### Complexity constant. ### Notes This function template models the semantics of the swap operation given by [Swappable](../named_req/swappable "cpp/named req/Swappable"). That is, overloads of `swap` found by [ADL](../language/adl "cpp/language/adl") and the fall back of `[std::swap](swap "cpp/algorithm/swap")` are considered. ### Possible implementation | | | --- | | ``` template<class ForwardIt1, class ForwardIt2> constexpr void iter_swap(ForwardIt1 a, ForwardIt2 b) // constexpr since C++20 { using std::swap; swap(*a, *b); } ``` | ### Example The following is an implementation of selection sort in C++. ``` #include <random> #include <vector> #include <iostream> #include <algorithm> #include <functional> template<class ForwardIt> void selection_sort(ForwardIt begin, ForwardIt end) { for (ForwardIt i = begin; i != end; ++i) std::iter_swap(i, std::min_element(i, end)); } int main() { std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution<> dist(-9, +9); std::vector<int> v; std::generate_n(back_inserter(v), 20, bind(dist, gen)); std::cout << "Before sort: " << std::showpos; for(auto e : v) std::cout << e << ' '; selection_sort(v.begin(), v.end()); std::cout << "\nAfter sort : "; for(auto e : v) std::cout << e << ' '; std::cout << '\n'; } ``` Possible output: ``` Before sort: -9 -3 +2 -8 +0 -1 +8 -4 -5 +1 -4 -5 +4 -9 -8 -6 -6 +8 -4 -6 After sort : -9 -9 -8 -8 -6 -6 -6 -5 -5 -4 -4 -4 -3 -1 +0 +1 +2 +4 +8 +8 ``` ### See also | | | | --- | --- | | [swap](swap "cpp/algorithm/swap") | swaps the values of two objects (function template) | | [swap\_ranges](swap_ranges "cpp/algorithm/swap ranges") | swaps two ranges of elements (function template) | | [iter\_swap](../iterator/reverse_iterator/iter_swap "cpp/iterator/reverse iterator/iter swap") (C++20) | swaps the objects pointed to by two adjusted underlying iterators (function template) | | [iter\_swap](../iterator/move_iterator/iter_swap "cpp/iterator/move iterator/iter swap") (C++20) | swaps the objects pointed to by two underlying iterators (function template) | | [iter\_swap](../iterator/ranges/iter_swap "cpp/iterator/ranges/iter swap") (C++20) | swaps the values referenced by two dereferenceable objects (customization point object) | cpp std::max_element std::max\_element ================= | Defined in header `[<algorithm>](../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | | (1) | | | ``` template< class ForwardIt > ForwardIt max_element( ForwardIt first, ForwardIt last ); ``` | (until C++17) | | ``` template< class ForwardIt > constexpr ForwardIt max_element( ForwardIt first, ForwardIt last ); ``` | (since C++17) | | ``` template< class ExecutionPolicy, class ForwardIt > ForwardIt max_element( ExecutionPolicy&& policy, ForwardIt first, ForwardIt last ); ``` | (2) | (since C++17) | | | (3) | | | ``` template< class ForwardIt, class Compare > ForwardIt max_element( ForwardIt first, ForwardIt last, Compare comp ); ``` | (until C++17) | | ``` template< class ForwardIt, class Compare > constexpr ForwardIt max_element( ForwardIt first, ForwardIt last, Compare comp ); ``` | (since C++17) | | ``` template< class ExecutionPolicy, class ForwardIt, class Compare > ForwardIt max_element( ExecutionPolicy&& policy, ForwardIt first, ForwardIt last, Compare comp ); ``` | (4) | (since C++17) | Finds the greatest element in the range `[first, last)`. 1) Elements are compared using `operator<`. 3) Elements are compared using the given binary comparison function `comp`. 2,4) Same as (1,3), but executed according to `policy`. These overloads do not participate in overload resolution unless `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ExecutionPolicy>>` (until C++20) `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<ExecutionPolicy>>` (since C++20) is true. ### Parameters | | | | | --- | --- | --- | | first, last | - | forward iterators defining the range to examine | | policy | - | the execution policy to use. See [execution policy](execution_policy_tag_t "cpp/algorithm/execution policy tag t") for details. | | comp | - | comparison function object (i.e. an object that satisfies the requirements of [Compare](../named_req/compare "cpp/named req/Compare")) which returns ​`true` if the first argument is *less* than the second. The signature of the comparison function should be equivalent to the following: `bool cmp(const Type1 &a, const Type2 &b);` While the signature does not need to have `const &`, the function must not modify the objects passed to it and must be able to accept all values of type (possibly const) `Type1` and `Type2` regardless of [value category](../language/value_category "cpp/language/value category") (thus, `Type1 &` is not allowed, nor is `Type1` unless for `Type1` a move is equivalent to a copy (since C++11)). The types `Type1` and `Type2` must be such that an object of type `ForwardIt` can be dereferenced and then implicitly converted to both of them. ​ | | Type requirements | | -`ForwardIt` must meet the requirements of [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"). | ### Return value Iterator to the greatest element in the range `[first, last)`. If several elements in the range are equivalent to the greatest element, returns the iterator to the first such element. Returns `last` if the range is empty. ### Complexity Exactly max(N-1,0) comparisons, where `N = [std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(first, last)`. ### Exceptions The overloads with a template parameter named `ExecutionPolicy` report errors as follows: * If execution of a function invoked as part of the algorithm throws an exception and `ExecutionPolicy` is one of the [standard policies](execution_policy_tag_t "cpp/algorithm/execution policy tag t"), `[std::terminate](../error/terminate "cpp/error/terminate")` is called. For any other `ExecutionPolicy`, the behavior is implementation-defined. * If the algorithm fails to allocate memory, `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` is thrown. ### Possible implementation | First version | | --- | | ``` template<class ForwardIt> ForwardIt max_element(ForwardIt first, ForwardIt last) { if (first == last) return last; ForwardIt largest = first; ++first; for (; first != last; ++first) { if (*largest < *first) { largest = first; } } return largest; } ``` | | Second version | | ``` template<class ForwardIt, class Compare> ForwardIt max_element(ForwardIt first, ForwardIt last, Compare comp) { if (first == last) return last; ForwardIt largest = first; ++first; for (; first != last; ++first) { if (comp(*largest, *first)) { largest = first; } } return largest; } ``` | ### Example ``` #include <algorithm> #include <iostream> #include <vector> #include <cmath> static bool abs_compare(int a, int b) { return (std::abs(a) < std::abs(b)); } int main() { std::vector<int> v{ 3, 1, -14, 1, 5, 9 }; std::vector<int>::iterator result; result = std::max_element(v.begin(), v.end()); std::cout << "max element at: " << std::distance(v.begin(), result) << '\n'; result = std::max_element(v.begin(), v.end(), abs_compare); std::cout << "max element (absolute) at: " << std::distance(v.begin(), result) << '\n'; } ``` Output: ``` max element at: 5 max element (absolute) at: 2 ``` ### See also | | | | --- | --- | | [min\_element](min_element "cpp/algorithm/min element") | returns the smallest element in a range (function template) | | [minmax\_element](minmax_element "cpp/algorithm/minmax element") (C++11) | returns the smallest and the largest elements in a range (function template) | | [max](max "cpp/algorithm/max") | returns the greater of the given values (function template) | | [ranges::max\_element](ranges/max_element "cpp/algorithm/ranges/max element") (C++20) | returns the largest element in a range (niebloid) |
programming_docs
cpp std::find_first_of std::find\_first\_of ==================== | Defined in header `[<algorithm>](../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | | (1) | | | ``` template< class ForwardIt1, class ForwardIt2 > ForwardIt1 find_first_of( ForwardIt1 first, ForwardIt1 last, ForwardIt2 s_first, ForwardIt2 s_last ); ``` | (until C++11) | | ``` template< class InputIt, class ForwardIt > InputIt find_first_of( InputIt first, InputIt last, ForwardIt s_first, ForwardIt s_last ); ``` | (since C++11) (until C++20) | | ``` template< class InputIt, class ForwardIt > constexpr InputIt find_first_of( InputIt first, InputIt last, ForwardIt s_first, ForwardIt s_last ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt1, class ForwardIt2 > ForwardIt1 find_first_of( ExecutionPolicy&& policy, ForwardIt1 first, ForwardIt1 last, ForwardIt2 s_first, ForwardIt2 s_last ); ``` | (2) | (since C++17) | | | (3) | | | ``` template< class ForwardIt1, class ForwardIt2, class BinaryPredicate > ForwardIt1 find_first_of( ForwardIt1 first, ForwardIt1 last, ForwardIt2 s_first, ForwardIt2 s_last, BinaryPredicate p ); ``` | (until C++11) | | ``` template< class InputIt, class ForwardIt, class BinaryPredicate > InputIt find_first_of( InputIt first, InputIt last, ForwardIt s_first, ForwardIt s_last, BinaryPredicate p ); ``` | (since C++11) (until C++20) | | ``` template< class InputIt, class ForwardIt, class BinaryPredicate > constexpr InputIt find_first_of( InputIt first, InputIt last, ForwardIt s_first, ForwardIt s_last, BinaryPredicate p ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt1, class ForwardIt2, class BinaryPredicate > ForwardIt1 find_first_of( ExecutionPolicy&& policy, ForwardIt1 first, ForwardIt last, ForwardIt2 s_first, ForwardIt2 s_last, BinaryPredicate p ); ``` | (4) | (since C++17) | Searches the range `[first, last)` for any of the elements in the range `[s_first, s_last)`. 1) Elements are compared using `operator==`. 3) Elements are compared using the given binary predicate `p`. 2,4) Same as (1,3), but executed according to `policy`. These overloads do not participate in overload resolution unless `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ExecutionPolicy>>` (until C++20) `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<ExecutionPolicy>>` (since C++20) is true. ### Parameters | | | | | --- | --- | --- | | first, last | - | the range of elements to examine | | s\_first, s\_last | - | the range of elements to search for | | policy | - | the execution policy to use. See [execution policy](execution_policy_tag_t "cpp/algorithm/execution policy tag t") for details. | | p | - | binary predicate which returns ​`true` if the elements should be treated as equal. The signature of the predicate function should be equivalent to the following: `bool pred(const Type1 &a, const Type2 &b);` While the signature does not need to have `const &`, the function must not modify the objects passed to it and must be able to accept all values of type (possibly const) `Type1` and `Type2` regardless of [value category](../language/value_category "cpp/language/value category") (thus, `Type1 &` is not allowed, nor is `Type1` unless for `Type1` a move is equivalent to a copy (since C++11)). The types `Type1` and `Type2` must be such that objects of types `ForwardIt1` and `ForwardIt2` can be dereferenced and then implicitly converted to `Type1` and `Type2` respectively. ​ | | Type requirements | | -`InputIt` must meet the requirements of [LegacyInputIterator](../named_req/inputiterator "cpp/named req/InputIterator"). | | -`ForwardIt1` must meet the requirements of [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"). | | -`ForwardIt2` must meet the requirements of [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"). | ### Return value Iterator to the first element in the range `[first, last)` that is equal to an element from the range `[s_first, s_last)`. If no such element is found, `last` is returned. ### Complexity Does at most `(S*N)` comparisons where `S = [std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(s_first, s_last)` and `N = [std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(first, last)`. ### Exceptions The overloads with a template parameter named `ExecutionPolicy` report errors as follows: * If execution of a function invoked as part of the algorithm throws an exception and `ExecutionPolicy` is one of the [standard policies](execution_policy_tag_t "cpp/algorithm/execution policy tag t"), `[std::terminate](../error/terminate "cpp/error/terminate")` is called. For any other `ExecutionPolicy`, the behavior is implementation-defined. * If the algorithm fails to allocate memory, `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` is thrown. ### Possible implementation | First version | | --- | | ``` template<class InputIt, class ForwardIt> InputIt find_first_of(InputIt first, InputIt last, ForwardIt s_first, ForwardIt s_last) { for (; first != last; ++first) { for (ForwardIt it = s_first; it != s_last; ++it) { if (*first == *it) { return first; } } } return last; } ``` | | Second version | | ``` template<class InputIt, class ForwardIt, class BinaryPredicate> InputIt find_first_of(InputIt first, InputIt last, ForwardIt s_first, ForwardIt s_last, BinaryPredicate p) { for (; first != last; ++first) { for (ForwardIt it = s_first; it != s_last; ++it) { if (p(*first, *it)) { return first; } } } return last; } ``` | ### Example The following code searches for any of specified integers in a vector of integers: ``` #include <algorithm> #include <iostream> #include <vector> auto print_sequence = [](auto const id, auto const& seq, int pos = -1) { std::cout << id << "{ "; for (int i{}; auto const& e : seq) { const bool mark {i == pos}; std::cout << (i++ ? ", " : ""); std::cout << (mark ? ">> " : "") << e << (mark ? " <<" : ""); } std::cout << " }\n"; }; int main() { const std::vector<int> v{0, 2, 3, 25, 5}; const auto t1 = {19, 10, 3, 4}; const auto t2 = {1, 6, 7, 9}; auto find_any_of = [](const auto& v, const auto& t) { const auto result = std::find_first_of(v.begin(), v.end(), t.begin(), t.end()); if (result == v.end()) { std::cout << "No elements of v are equal to any element of "; print_sequence("t = ", t); print_sequence("v = ", v); } else { const auto pos = std::distance(v.begin(), result); std::cout << "Found a match (" << *result << ") at position " << pos; print_sequence(", where t = ", t); print_sequence("v = ", v, pos); } }; find_any_of(v, t1); find_any_of(v, t2); } ``` Output: ``` Found a match (3) at position 2, where t = { 19, 10, 3, 4 } v = { 0, 2, >> 3 <<, 25, 5 } No elements of v are equal to any element of t = { 1, 6, 7, 9 } v = { 0, 2, 3, 25, 5 } ``` ### See also | | | | --- | --- | | [findfind\_iffind\_if\_not](find "cpp/algorithm/find") (C++11) | finds the first element satisfying specific criteria (function template) | | [ranges::find\_first\_of](ranges/find_first_of "cpp/algorithm/ranges/find first of") (C++20) | searches for any one of a set of elements (niebloid) | cpp std::min_element std::min\_element ================= | Defined in header `[<algorithm>](../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | | (1) | | | ``` template< class ForwardIt > ForwardIt min_element( ForwardIt first, ForwardIt last ); ``` | (until C++17) | | ``` template< class ForwardIt > constexpr ForwardIt min_element( ForwardIt first, ForwardIt last ); ``` | (since C++17) | | ``` template< class ExecutionPolicy, class ForwardIt > ForwardIt min_element( ExecutionPolicy&& policy, ForwardIt first, ForwardIt last ); ``` | (2) | (since C++17) | | | (3) | | | ``` template< class ForwardIt, class Compare > ForwardIt min_element( ForwardIt first, ForwardIt last, Compare comp ); ``` | (until C++17) | | ``` template< class ForwardIt, class Compare > constexpr ForwardIt min_element( ForwardIt first, ForwardIt last, Compare comp ); ``` | (since C++17) | | ``` template< class ExecutionPolicy, class ForwardIt, class Compare > ForwardIt min_element( ExecutionPolicy&& policy, ForwardIt first, ForwardIt last, Compare comp ); ``` | (4) | (since C++17) | Finds the smallest element in the range `[first, last)`. 1) Elements are compared using `operator<`. 3) Elements are compared using the given binary comparison function `comp`. 2,4) Same as (1,3), but executed according to `policy`. These overloads do not participate in overload resolution unless `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ExecutionPolicy>>` (until C++20) `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<ExecutionPolicy>>` (since C++20) is true. ### Parameters | | | | | --- | --- | --- | | first, last | - | forward iterators defining the range to examine | | policy | - | the execution policy to use. See [execution policy](execution_policy_tag_t "cpp/algorithm/execution policy tag t") for details. | | comp | - | comparison function object (i.e. an object that satisfies the requirements of [Compare](../named_req/compare "cpp/named req/Compare")) which returns ​`true` if `a` is *less* than `b`. The signature of the comparison function should be equivalent to the following: `bool cmp(const Type1 &a, const Type2 &b);` While the signature does not need to have `const &`, the function must not modify the objects passed to it and must be able to accept all values of type (possibly const) `Type1` and `Type2` regardless of [value category](../language/value_category "cpp/language/value category") (thus, `Type1 &` is not allowed, nor is `Type1` unless for `Type1` a move is equivalent to a copy (since C++11)). The types `Type1` and `Type2` must be such that an object of type `ForwardIt` can be dereferenced and then implicitly converted to both of them. ​ | | Type requirements | | -`ForwardIt` must meet the requirements of [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"). | ### Return value Iterator to the smallest element in the range `[first, last)`. If several elements in the range are equivalent to the smallest element, returns the iterator to the first such element. Returns `last` if the range is empty. ### Complexity Exactly max(N-1,0) comparisons, where `N = [std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(first, last)`. ### Exceptions The overloads with a template parameter named `ExecutionPolicy` report errors as follows: * If execution of a function invoked as part of the algorithm throws an exception and `ExecutionPolicy` is one of the [standard policies](execution_policy_tag_t "cpp/algorithm/execution policy tag t"), `[std::terminate](../error/terminate "cpp/error/terminate")` is called. For any other `ExecutionPolicy`, the behavior is implementation-defined. * If the algorithm fails to allocate memory, `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` is thrown. ### Possible implementation | First version | | --- | | ``` template<class ForwardIt> ForwardIt min_element(ForwardIt first, ForwardIt last) { if (first == last) return last; ForwardIt smallest = first; ++first; for (; first != last; ++first) { if (*first < *smallest) { smallest = first; } } return smallest; } ``` | | Second version | | ``` template<class ForwardIt, class Compare> ForwardIt min_element(ForwardIt first, ForwardIt last, Compare comp) { if (first == last) return last; ForwardIt smallest = first; ++first; for (; first != last; ++first) { if (comp(*first, *smallest)) { smallest = first; } } return smallest; } ``` | ### Example ``` #include <algorithm> #include <iostream> #include <vector> int main() { std::vector<int> v{3, 1, 4, 1, 5, 9}; std::vector<int>::iterator result = std::min_element(v.begin(), v.end()); std::cout << "min element at: " << std::distance(v.begin(), result); } ``` Output: ``` min element at: 1 ``` ### See also | | | | --- | --- | | [max\_element](max_element "cpp/algorithm/max element") | returns the largest element in a range (function template) | | [minmax\_element](minmax_element "cpp/algorithm/minmax element") (C++11) | returns the smallest and the largest elements in a range (function template) | | [min](min "cpp/algorithm/min") | returns the smaller of the given values (function template) | | [ranges::min\_element](ranges/min_element "cpp/algorithm/ranges/min element") (C++20) | returns the smallest element in a range (niebloid) | cpp std::is_sorted_until std::is\_sorted\_until ====================== | Defined in header `[<algorithm>](../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | | (1) | | | ``` template< class ForwardIt > ForwardIt is_sorted_until( ForwardIt first, ForwardIt last ); ``` | (since C++11) (until C++20) | | ``` template< class ForwardIt > constexpr ForwardIt is_sorted_until( ForwardIt first, ForwardIt last ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt > ForwardIt is_sorted_until( ExecutionPolicy&& policy, ForwardIt first, ForwardIt last ); ``` | (2) | (since C++17) | | | (3) | | | ``` template< class ForwardIt, class Compare > ForwardIt is_sorted_until( ForwardIt first, ForwardIt last, Compare comp ); ``` | (since C++11) (until C++20) | | ``` template< class ForwardIt, class Compare > constexpr ForwardIt is_sorted_until( ForwardIt first, ForwardIt last, Compare comp ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt, class Compare > ForwardIt is_sorted_until( ExecutionPolicy&& policy, ForwardIt first, ForwardIt last, Compare comp ); ``` | (4) | (since C++17) | Examines the range `[first, last)` and finds the largest range beginning at `first` in which the elements are sorted in non-descending order. A sequence is sorted with respect to a comparator `comp` if for any iterator `it` pointing to the sequence and any non-negative integer `n` such that `it + n` is a valid iterator pointing to an element of the sequence, `comp(*(it + n), *it)` evaluates to `false`. 1) Elements are compared using `operator<`. 3) Elements are compared using the given binary comparison function `comp`. 2,4) Same as (1,3), but executed according to `policy`. These overloads do not participate in overload resolution unless `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ExecutionPolicy>>` (until C++20) `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<ExecutionPolicy>>` (since C++20) is true. ### Parameters | | | | | --- | --- | --- | | first, last | - | the range of elements to examine | | policy | - | the execution policy to use. See [execution policy](execution_policy_tag_t "cpp/algorithm/execution policy tag t") for details. | | comp | - | comparison function object (i.e. an object that satisfies the requirements of [Compare](../named_req/compare "cpp/named req/Compare")) which returns ​`true` if the first argument is *less* than (i.e. is ordered *before*) the second. The signature of the comparison function should be equivalent to the following: `bool cmp(const Type1 &a, const Type2 &b);` While the signature does not need to have `const &`, the function must not modify the objects passed to it and must be able to accept all values of type (possibly const) `Type1` and `Type2` regardless of [value category](../language/value_category "cpp/language/value category") (thus, `Type1 &` is not allowed, nor is `Type1` unless for `Type1` a move is equivalent to a copy (since C++11)). The types `Type1` and `Type2` must be such that an object of type `ForwardIt` can be dereferenced and then implicitly converted to both of them. ​ | | Type requirements | | -`ForwardIt` must meet the requirements of [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"). | ### Return value The upper bound of the largest range beginning at `first` in which the elements are sorted in ascending order. That is, the last iterator `it` for which range `[first, it)` is sorted. ### Complexity Linear in the distance between `first` and `last`. ### Exceptions The overloads with a template parameter named `ExecutionPolicy` report errors as follows: * If execution of a function invoked as part of the algorithm throws an exception and `ExecutionPolicy` is one of the [standard policies](execution_policy_tag_t "cpp/algorithm/execution policy tag t"), `[std::terminate](../error/terminate "cpp/error/terminate")` is called. For any other `ExecutionPolicy`, the behavior is implementation-defined. * If the algorithm fails to allocate memory, `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` is thrown. ### Possible implementation See also the implementations in [libstdc++](https://github.com/gcc-mirror/gcc/blob/d9375e490072d1aae73a93949aa158fcd2a27018/libstdc%2B%2B-v3/include/bits/stl_algo.h#L3211) and [libc++](https://github.com/llvm-mirror/libcxx/blob/a12cb9d211019d99b5875b6d8034617cbc24c2cc/include/algorithm#L3614). | First version | | --- | | ``` template<class ForwardIt> constexpr //< since C++20 ForwardIt is_sorted_until(ForwardIt first, ForwardIt last) { return std::is_sorted_until(first, last, std::less<>()); } ``` | | Second version | | ``` template <class ForwardIt, class Compare> constexpr //< since C++20 ForwardIt is_sorted_until(ForwardIt first, ForwardIt last, Compare comp) { if (first != last) { ForwardIt next = first; while (++next != last) { if (comp(*next, *first)) return next; first = next; } } return last; } ``` | ### Notes `std::is_sorted_until` returns `last` for empty ranges and ranges of length one. ### Example ``` #include <iostream> #include <algorithm> #include <iterator> #include <random> #include <string> #include <cassert> int main() { std::random_device rd; std::mt19937 g(rd()); const int N = 6; int nums[N] = {3, 1, 4, 1, 5, 9}; const int min_sorted_size = 4; for (int sorted_size = 0; sorted_size < min_sorted_size; ) { std::shuffle(nums, nums + N, g); int *const sorted_end = std::is_sorted_until(nums, nums + N); sorted_size = std::distance(nums, sorted_end); assert(sorted_size >= 1); for (auto i : nums) std::cout << i << ' '; std::cout << " : " << sorted_size << " initial sorted elements\n" << std::string(sorted_size * 2 - 1, '^') << '\n'; } } ``` Possible output: ``` 4 1 9 5 1 3 : 1 initial sorted elements ^ 4 5 9 3 1 1 : 3 initial sorted elements ^^^^^ 9 3 1 4 5 1 : 1 initial sorted elements ^ 1 3 5 4 1 9 : 3 initial sorted elements ^^^^^ 5 9 1 1 3 4 : 2 initial sorted elements ^^^ 4 9 1 5 1 3 : 2 initial sorted elements ^^^ 1 1 4 9 5 3 : 4 initial sorted elements ^^^^^^^ ``` ### See also | | | | --- | --- | | [is\_sorted](is_sorted "cpp/algorithm/is sorted") (C++11) | checks whether a range is sorted into ascending order (function template) | | [ranges::is\_sorted\_until](ranges/is_sorted_until "cpp/algorithm/ranges/is sorted until") (C++20) | finds the largest sorted subrange (niebloid) |
programming_docs
cpp std::upper_bound std::upper\_bound ================= | Defined in header `[<algorithm>](../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | | (1) | | | ``` template< class ForwardIt, class T > ForwardIt upper_bound( ForwardIt first, ForwardIt last, const T& value ); ``` | (until C++20) | | ``` template< class ForwardIt, class T > constexpr ForwardIt upper_bound( ForwardIt first, ForwardIt last, const T& value ); ``` | (since C++20) | | | (2) | | | ``` template< class ForwardIt, class T, class Compare > ForwardIt upper_bound( ForwardIt first, ForwardIt last, const T& value, Compare comp ); ``` | (until C++20) | | ``` template< class ForwardIt, class T, class Compare > constexpr ForwardIt upper_bound( ForwardIt first, ForwardIt last, const T& value, Compare comp ); ``` | (since C++20) | Returns an iterator pointing to the first element in the range `[first, last)` such that `value < element` (or `comp(value, element)`) is true (i.e. strictly greater), or `last` if no such element is found. The range `[first, last)` must be partitioned with respect to the expression `!(value < element)` or `!comp(value, element)`, i.e., all elements for which the expression is `true` must precede all elements for which the expression is `false`. A fully-sorted range meets this criterion. The first version uses `operator<` to compare the elements, the second version uses the given comparison function `comp`. ### Parameters | | | | | --- | --- | --- | | first, last | - | iterators defining the partially-ordered range to examine | | value | - | value to compare the elements to | | comp | - | binary predicate which returns ​`true` if the first argument is *less* than (i.e. is ordered before) the second. The signature of the predicate function should be equivalent to the following: `bool pred(const Type1 &a, const Type2 &b);` While the signature does not need to have `const &`, the function must not modify the objects passed to it and must be able to accept all values of type (possibly const) `Type1` and `Type2` regardless of [value category](../language/value_category "cpp/language/value category") (thus, `Type1 &` is not allowed, nor is `Type1` unless for `Type1` a move is equivalent to a copy (since C++11)). The type `Type1` must be such that an object of type `T` can be implicitly converted to `Type1`. The type `Type2` must be such that an object of type `ForwardIt` can be dereferenced and then implicitly converted to `Type2`. ​ | | Type requirements | | -`ForwardIt` must meet the requirements of [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"). | | -`Compare` must meet the requirements of [BinaryPredicate](../named_req/binarypredicate "cpp/named req/BinaryPredicate"). it is not required to satisfy [Compare](../named_req/compare "cpp/named req/Compare") | ### Return value Iterator pointing to the first element in the range `[first, last)` such that `value < element` (or `comp(value, element)`) is true, or `last` if no such element is found. ### Complexity The number of comparisons performed is logarithmic in the distance between `first` and `last` (At most log 2(last - first) + O(1) comparisons). However, for non-[LegacyRandomAccessIterators](../named_req/randomaccessiterator "cpp/named req/RandomAccessIterator"), the number of iterator increments is linear. Notably, `[std::set](../container/set "cpp/container/set")` and `[std::multiset](../container/multiset "cpp/container/multiset")` iterators are not random access, and so their member functions `[std::set::upper\_bound](../container/set/upper_bound "cpp/container/set/upper bound")` (resp. `[std::multiset::upper\_bound](../container/multiset/upper_bound "cpp/container/multiset/upper bound")`) should be preferred. ### Possible implementation See also the implementations in [libstdc++](https://github.com/gcc-mirror/gcc/blob/d9375e490072d1aae73a93949aa158fcd2a27018/libstdc%2B%2B-v3/include/bits/stl_algo.h#L2028) and [libc++](https://github.com/llvm-mirror/libcxx/blob/a12cb9d211019d99b5875b6d8034617cbc24c2cc/include/algorithm#L4219). | First version | | --- | | ``` template<class ForwardIt, class T> ForwardIt upper_bound(ForwardIt first, ForwardIt last, const T& value) { ForwardIt it; typename std::iterator_traits<ForwardIt>::difference_type count, step; count = std::distance(first, last); while (count > 0) { it = first; step = count / 2; std::advance(it, step); if (!(value < *it)) { first = ++it; count -= step + 1; } else count = step; } return first; } ``` | | Second version | | ``` template<class ForwardIt, class T, class Compare> ForwardIt upper_bound(ForwardIt first, ForwardIt last, const T& value, Compare comp) { ForwardIt it; typename std::iterator_traits<ForwardIt>::difference_type count, step; count = std::distance(first, last); while (count > 0) { it = first; step = count / 2; std::advance(it, step); if (!comp(value, *it)) { first = ++it; count -= step + 1; } else count = step; } return first; } ``` | ### Example ``` #include <algorithm> #include <iostream> #include <vector> struct PriceInfo { double price; }; int main() { const std::vector<int> data = { 1, 2, 4, 5, 5, 6 }; for (int i = 0; i < 7; ++i) { // Search first element that is greater than i auto upper = std::upper_bound(data.begin(), data.end(), i); std::cout << i << " < "; upper != data.end() ? std::cout << *upper << " at index " << std::distance(data.begin(), upper) : std::cout << "not found"; std::cout << '\n'; } std::vector<PriceInfo> prices = { {100.0}, {101.5}, {102.5}, {102.5}, {107.3} }; for(double to_find: {102.5, 110.2}) { auto prc_info = std::upper_bound(prices.begin(), prices.end(), to_find, [](double value, const PriceInfo& info){ return value < info.price; }); prc_info != prices.end() ? std::cout << prc_info->price << " at index " << prc_info - prices.begin() : std::cout << to_find << " not found"; std::cout << '\n'; } } ``` Output: ``` 0 < 1 at index 0 1 < 2 at index 1 2 < 4 at index 2 3 < 4 at index 2 4 < 5 at index 3 5 < 6 at index 5 6 < not found 107.3 at index 4 110.2 not found ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 270](https://cplusplus.github.io/LWG/issue270) | C++98 | Compare was required to be a strict weak ordering | only a partitioning is needed; heterogeneous comparisons permitted | ### See also | | | | --- | --- | | [equal\_range](equal_range "cpp/algorithm/equal range") | returns range of elements matching a specific key (function template) | | [lower\_bound](lower_bound "cpp/algorithm/lower bound") | returns an iterator to the first element *not less* than the given value (function template) | | [partition](partition "cpp/algorithm/partition") | divides a range of elements into two groups (function template) | | [partition\_point](partition_point "cpp/algorithm/partition point") (C++11) | locates the partition point of a partitioned range (function template) | | [ranges::upper\_bound](ranges/upper_bound "cpp/algorithm/ranges/upper bound") (C++20) | returns an iterator to the first element *greater* than a certain value (niebloid) | | [upper\_bound](../container/set/upper_bound "cpp/container/set/upper bound") | returns an iterator to the first element *greater* than the given key (public member function of `std::set<Key,Compare,Allocator>`) | | [upper\_bound](../container/multiset/upper_bound "cpp/container/multiset/upper bound") | returns an iterator to the first element *greater* than the given key (public member function of `std::multiset<Key,Compare,Allocator>`) | cpp std::stable_sort std::stable\_sort ================= | Defined in header `[<algorithm>](../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | ``` template< class RandomIt > void stable_sort( RandomIt first, RandomIt last ); ``` | (1) | | | ``` template< class ExecutionPolicy, class RandomIt > void stable_sort( ExecutionPolicy&& policy, RandomIt first, RandomIt last ); ``` | (2) | (since C++17) | | ``` template< class RandomIt, class Compare > void stable_sort( RandomIt first, RandomIt last, Compare comp ); ``` | (3) | | | ``` template< class ExecutionPolicy, class RandomIt, class Compare > void stable_sort( ExecutionPolicy&& policy, RandomIt first, RandomIt last, Compare comp ); ``` | (4) | (since C++17) | Sorts the elements in the range `[first, last)` in non-descending order. The order of equivalent elements is guaranteed to be preserved. A sequence is sorted with respect to a comparator `comp` if for any iterator `it` pointing to the sequence and any non-negative integer `n` such that `it + n` is a valid iterator pointing to an element of the sequence, `comp(*(it + n), *it)` (or `*(it + n) < *it`) evaluates to `false`. 1) Elements are compared using `operator<`. 3) Elements are compared using the given comparison function `comp`. 2,4) Same as (1,3), but executed according to `policy`. These overloads do not participate in overload resolution unless `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ExecutionPolicy>>` (until C++20) `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<ExecutionPolicy>>` (since C++20) is true. ### Parameters | | | | | --- | --- | --- | | first, last | - | the range of elements to sort | | policy | - | the execution policy to use. See [execution policy](execution_policy_tag_t "cpp/algorithm/execution policy tag t") for details. | | comp | - | comparison function object (i.e. an object that satisfies the requirements of [Compare](../named_req/compare "cpp/named req/Compare")) which returns ​`true` if the first argument is *less* than (i.e. is ordered *before*) the second. The signature of the comparison function should be equivalent to the following: `bool cmp(const Type1 &a, const Type2 &b);` While the signature does not need to have `const &`, the function must not modify the objects passed to it and must be able to accept all values of type (possibly const) `Type1` and `Type2` regardless of [value category](../language/value_category "cpp/language/value category") (thus, `Type1 &` is not allowed, nor is `Type1` unless for `Type1` a move is equivalent to a copy (since C++11)). The types `Type1` and `Type2` must be such that an object of type `RandomIt` can be dereferenced and then implicitly converted to both of them. ​ | | Type requirements | | -`RandomIt` must meet the requirements of [ValueSwappable](../named_req/valueswappable "cpp/named req/ValueSwappable") and [LegacyRandomAccessIterator](../named_req/randomaccessiterator "cpp/named req/RandomAccessIterator"). | | -The type of dereferenced `RandomIt` must meet the requirements of [MoveAssignable](../named_req/moveassignable "cpp/named req/MoveAssignable") and [MoveConstructible](../named_req/moveconstructible "cpp/named req/MoveConstructible"). | ### Return value (none). ### Complexity O(N·log(N)2), where `N = [std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(first, last)` applications of `cmp`. If additional memory is available, then the complexity is O(N·log(N)). ### Exceptions The overloads with a template parameter named `ExecutionPolicy` report errors as follows: * If execution of a function invoked as part of the algorithm throws an exception and `ExecutionPolicy` is one of the [standard policies](execution_policy_tag_t "cpp/algorithm/execution policy tag t"), `[std::terminate](../error/terminate "cpp/error/terminate")` is called. For any other `ExecutionPolicy`, the behavior is implementation-defined. * If the algorithm fails to allocate memory, `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` is thrown. ### Notes This function attempts to allocate a temporary buffer equal in size to the sequence to be sorted. If the allocation fails, the less efficient algorithm is chosen. ### Possible implementation See also the implementations in [libstdc++](https://github.com/gcc-mirror/gcc/blob/d9375e490072d1aae73a93949aa158fcd2a27018/libstdc%2B%2B-v3/include/bits/stl_algo.h#L4977) and [libc++](https://github.com/llvm-mirror/libcxx/blob/a12cb9d211019d99b5875b6d8034617cbc24c2cc/include/algorithm#L4696). ### Example ``` #include <algorithm> #include <iostream> #include <string> #include <vector> struct Employee { int age; std::string name; // Does not participate in comparisons }; bool operator<(const Employee & lhs, const Employee & rhs) { return lhs.age < rhs.age; } int main() { std::vector<Employee> v = { {108, "Zaphod"}, {32, "Arthur"}, {108, "Ford"}, }; std::stable_sort(v.begin(), v.end()); for (const Employee & e : v) std::cout << e.age << ", " << e.name << '\n'; } ``` Output: ``` 32, Arthur 108, Zaphod 108, Ford ``` ### See also | | | | --- | --- | | [sort](sort "cpp/algorithm/sort") | sorts a range into ascending order (function template) | | [partial\_sort](partial_sort "cpp/algorithm/partial sort") | sorts the first N elements of a range (function template) | | [stable\_partition](stable_partition "cpp/algorithm/stable partition") | divides elements into two groups while preserving their relative order (function template) | | [ranges::stable\_sort](ranges/stable_sort "cpp/algorithm/ranges/stable sort") (C++20) | sorts a range of elements while preserving order between equal elements (niebloid) | cpp std::equal std::equal ========== | Defined in header `[<algorithm>](../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | | (1) | | | ``` template< class InputIt1, class InputIt2 > bool equal( InputIt1 first1, InputIt1 last1, InputIt2 first2 ); ``` | (until C++20) | | ``` template< class InputIt1, class InputIt2 > constexpr bool equal( InputIt1 first1, InputIt1 last1, InputIt2 first2 ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt1, class ForwardIt2 > bool equal( ExecutionPolicy&& policy, ForwardIt1 first1, ForwardIt1 last1, ForwardIt2 first2 ); ``` | (2) | (since C++17) | | | (3) | | | ``` template< class InputIt1, class InputIt2, class BinaryPredicate > bool equal( InputIt1 first1, InputIt1 last1, InputIt2 first2, BinaryPredicate p ); ``` | (until C++20) | | ``` template< class InputIt1, class InputIt2, class BinaryPredicate > constexpr bool equal( InputIt1 first1, InputIt1 last1, InputIt2 first2, BinaryPredicate p ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt1, class ForwardIt2, class BinaryPredicate > bool equal( ExecutionPolicy&& policy, ForwardIt1 first1, ForwardIt1 last1, ForwardIt2 first2, BinaryPredicate p ); ``` | (4) | (since C++17) | | | (5) | | | ``` template< class InputIt1, class InputIt2 > bool equal( InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2 ); ``` | (since C++14) (until C++20) | | ``` template< class InputIt1, class InputIt2 > constexpr bool equal( InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2 ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt1, class ForwardIt2 > bool equal( ExecutionPolicy&& policy, ForwardIt1 first1, ForwardIt1 last1, ForwardIt2 first2, ForwardIt2 last2 ); ``` | (6) | (since C++17) | | | (7) | | | ``` template< class InputIt1, class InputIt2, class BinaryPredicate > bool equal( InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2, BinaryPredicate p ); ``` | (since C++14) (until C++20) | | ``` template< class InputIt1, class InputIt2, class BinaryPredicate > constexpr bool equal( InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2, BinaryPredicate p ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt1, class ForwardIt2, class BinaryPredicate > bool equal( ExecutionPolicy&& policy, ForwardIt1 first1, ForwardIt1 last1, ForwardIt2 first2, ForwardIt2 last2, BinaryPredicate p ); ``` | (8) | (since C++17) | 1,3) Returns `true` if the range `[first1, last1)` is equal to the range `[first2, first2 + (last1 - first1))`, and `false` otherwise. 5,7) Returns `true` if the range `[first1, last1)` is equal to the range `[first2, last2)`, and `false` otherwise. 2,4,6,8) Same as (1,3,5,7), but executed according to `policy`. These overloads do not participate in overload resolution unless `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ExecutionPolicy>>` (until C++20) `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<ExecutionPolicy>>` (since C++20) is true. Two ranges are considered equal if they have the same number of elements and, for every iterator `i` in the range `[first1,last1)`, `*i` equals `*(first2 + (i - first1))`. The overloads (1,2,5,6) use `operator==` to determine if two elements are equal, whereas overloads (3,4,7,8) use the given binary predicate `p`. ### Parameters | | | | | --- | --- | --- | | first1, last1 | - | the first range of the elements to compare | | first2, last2 | - | the second range of the elements to compare | | policy | - | the execution policy to use. See [execution policy](execution_policy_tag_t "cpp/algorithm/execution policy tag t") for details. | | p | - | binary predicate which returns ​`true` if the elements should be treated as equal. The signature of the predicate function should be equivalent to the following: `bool pred(const Type1 &a, const Type2 &b);` While the signature does not need to have `const &`, the function must not modify the objects passed to it and must be able to accept all values of type (possibly const) `Type1` and `Type2` regardless of [value category](../language/value_category "cpp/language/value category") (thus, `Type1 &` is not allowed, nor is `Type1` unless for `Type1` a move is equivalent to a copy (since C++11)). The types `Type1` and `Type2` must be such that objects of types `InputIt1` and `InputIt2` can be dereferenced and then implicitly converted to `Type1` and `Type2` respectively. ​ | | Type requirements | | -`InputIt1, InputIt2` must meet the requirements of [LegacyInputIterator](../named_req/inputiterator "cpp/named req/InputIterator"). | | -`ForwardIt1, ForwardIt2` must meet the requirements of [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"). | ### Return value 5-8) If the length of the range `[first1, last1)` does not equal the length of the range `[first2, last2)`, returns `false` If the elements in the two ranges are equal, returns `true`. Otherwise returns `false`. ### Notes `std::equal` should not be used to compare the ranges formed by the iterators from `[std::unordered\_set](../container/unordered_set "cpp/container/unordered set")`, `[std::unordered\_multiset](../container/unordered_multiset "cpp/container/unordered multiset")`, `[std::unordered\_map](../container/unordered_map "cpp/container/unordered map")`, or `[std::unordered\_multimap](../container/unordered_multimap "cpp/container/unordered multimap")` because the order in which the elements are stored in those containers may be different even if the two containers store the same elements. When comparing entire containers for equality, `operator==` for the corresponding container are usually preferred. ### Complexity 1,3) At most `last1` - `first1` applications of the predicate 5,7) At most min(`last1` - `first1`, `last2` - `first2`) applications of the predicate. However, if `InputIt1` and `InputIt2` meet the requirements of [LegacyRandomAccessIterator](../named_req/randomaccessiterator "cpp/named req/RandomAccessIterator") and `last1 - first1 != last2 - first2` then no applications of the predicate are made (size mismatch is detected without looking at any elements). 2,4,6,8) same, but the complexity is specified as O(x), rather than "at most x" ### Exceptions The overloads with a template parameter named `ExecutionPolicy` report errors as follows: * If execution of a function invoked as part of the algorithm throws an exception and `ExecutionPolicy` is one of the [standard policies](execution_policy_tag_t "cpp/algorithm/execution policy tag t"), `[std::terminate](../error/terminate "cpp/error/terminate")` is called. For any other `ExecutionPolicy`, the behavior is implementation-defined. * If the algorithm fails to allocate memory, `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` is thrown. ### Possible implementation | First version | | --- | | ``` template<class InputIt1, class InputIt2> constexpr //< since C++20 bool equal(InputIt1 first1, InputIt1 last1, InputIt2 first2) { for (; first1 != last1; ++first1, ++first2) { if (!(*first1 == *first2)) { return false; } } return true; } ``` | | Second version | | ``` template<class InputIt1, class InputIt2, class BinaryPredicate> constexpr //< since C++20 bool equal(InputIt1 first1, InputIt1 last1, InputIt2 first2, BinaryPredicate p) { for (; first1 != last1; ++first1, ++first2) { if (!p(*first1, *first2)) { return false; } } return true; } ``` | ### Example The following code uses `std::equal` to test if a string is a palindrome. ``` #include <algorithm> #include <iostream> #include <string_view> constexpr bool is_palindrome(const std::string_view& s) { return std::equal(s.begin(), s.begin() + s.size()/2, s.rbegin()); } void test(const std::string_view& s) { std::cout << "\"" << s << "\" " << (is_palindrome(s) ? "is" : "is not") << " a palindrome\n"; } int main() { test("radar"); test("hello"); } ``` Output: ``` "radar" is a palindrome "hello" is not a palindrome ``` ### See also | | | | --- | --- | | [findfind\_iffind\_if\_not](find "cpp/algorithm/find") (C++11) | finds the first element satisfying specific criteria (function template) | | [lexicographical\_compare](lexicographical_compare "cpp/algorithm/lexicographical compare") | returns true if one range is lexicographically less than another (function template) | | [mismatch](mismatch "cpp/algorithm/mismatch") | finds the first position where two ranges differ (function template) | | [search](search "cpp/algorithm/search") | searches for a range of elements (function template) | | [ranges::equal](ranges/equal "cpp/algorithm/ranges/equal") (C++20) | determines if two sets of elements are the same (niebloid) | | [equal\_to](../utility/functional/equal_to "cpp/utility/functional/equal to") | function object implementing `x == y` (class template) | | [equal\_range](equal_range "cpp/algorithm/equal range") | returns range of elements matching a specific key (function template) |
programming_docs
cpp std::all_of, std::any_of, std::none_of std::all\_of, std::any\_of, std::none\_of ========================================= | Defined in header `[<algorithm>](../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | | (1) | | | ``` template< class InputIt, class UnaryPredicate > bool all_of( InputIt first, InputIt last, UnaryPredicate p ); ``` | (since C++11) (until C++20) | | ``` template< class InputIt, class UnaryPredicate > constexpr bool all_of( InputIt first, InputIt last, UnaryPredicate p ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt, class UnaryPredicate > bool all_of( ExecutionPolicy&& policy, ForwardIt first, ForwardIt last, UnaryPredicate p ); ``` | (2) | (since C++17) | | | (3) | | | ``` template< class InputIt, class UnaryPredicate > bool any_of( InputIt first, InputIt last, UnaryPredicate p ); ``` | (since C++11) (until C++20) | | ``` template< class InputIt, class UnaryPredicate > constexpr bool any_of( InputIt first, InputIt last, UnaryPredicate p ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt, class UnaryPredicate > bool any_of( ExecutionPolicy&& policy, ForwardIt first, ForwardIt last, UnaryPredicate p ); ``` | (4) | (since C++17) | | | (5) | | | ``` template< class InputIt, class UnaryPredicate > bool none_of( InputIt first, InputIt last, UnaryPredicate p ); ``` | (since C++11) (until C++20) | | ``` template< class InputIt, class UnaryPredicate > constexpr bool none_of( InputIt first, InputIt last, UnaryPredicate p ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt, class UnaryPredicate > bool none_of( ExecutionPolicy&& policy, ForwardIt first, ForwardIt last, UnaryPredicate p ); ``` | (6) | (since C++17) | 1) Checks if unary predicate `p` returns `true` for all elements in the range `[first, last)`. 3) Checks if unary predicate `p` returns `true` for at least one element in the range `[first, last)`. 5) Checks if unary predicate `p` returns `true` for no elements in the range `[first, last)`. 2,4,6) Same as (1,3,5), but executed according to `policy`. These overloads do not participate in overload resolution unless `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ExecutionPolicy>>` (until C++20) `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<ExecutionPolicy>>` (since C++20) is true. ### Parameters | | | | | --- | --- | --- | | first, last | - | the range of elements to examine | | policy | - | the execution policy to use. See [execution policy](execution_policy_tag_t "cpp/algorithm/execution policy tag t") for details. | | p | - | unary predicate . The expression `p(v)` must be convertible to `bool` for every argument `v` of type (possibly const) `VT`, where `VT` is the value type of `InputIt`, regardless of [value category](../language/value_category "cpp/language/value category"), and must not modify `v`. Thus, a parameter type of `VT&`is not allowed, nor is `VT` unless for `VT` a move is equivalent to a copy (since C++11). ​ | | Type requirements | | -`InputIt` must meet the requirements of [LegacyInputIterator](../named_req/inputiterator "cpp/named req/InputIterator"). | | -`ForwardIt` must meet the requirements of [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"). | | -`UnaryPredicate` must meet the requirements of [Predicate](../named_req/predicate "cpp/named req/Predicate"). | ### Return value See also [Notes](#Notes) below. 1-2) `true` if unary predicate returns `true` for all elements in the range, `false` otherwise. Returns `true` if the range is empty. 3-4) `true` if unary predicate returns `true` for at least one element in the range, `false` otherwise. Returns `false` if the range is empty. 5-6) `true` if unary predicate returns `true` for no elements in the range, `false` otherwise. Returns `true` if the range is empty. ### Complexity 1,3,5) At most `last` - `first` applications of the predicate 2,4,6) `O(last-first)` applications of the predicate ### Exceptions The overloads with a template parameter named `ExecutionPolicy` report errors as follows: * If execution of a function invoked as part of the algorithm throws an exception and `ExecutionPolicy` is one of the [standard policies](execution_policy_tag_t "cpp/algorithm/execution policy tag t"), `[std::terminate](../error/terminate "cpp/error/terminate")` is called. For any other `ExecutionPolicy`, the behavior is implementation-defined. * If the algorithm fails to allocate memory, `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` is thrown. ### Possible implementation See also the implementations of `all_of` in [libstdc++](https://github.com/gcc-mirror/gcc/blob/d9375e490072d1aae73a93949aa158fcd2a27018/libstdc%2B%2B-v3/include/bits/stl_algo.h#L508) and [libc++](https://github.com/llvm-mirror/libcxx/blob/a12cb9d211019d99b5875b6d8034617cbc24c2cc/include/algorithm#L838). See also the implementations of `any_of` in [libstdc++](https://github.com/gcc-mirror/gcc/blob/d9375e490072d1aae73a93949aa158fcd2a27018/libstdc%2B%2B-v3/include/bits/stl_algo.h#L541) and [libc++](https://github.com/llvm-mirror/libcxx/blob/a12cb9d211019d99b5875b6d8034617cbc24c2cc/include/algorithm#L852). See also the implementations of `none_of` in [libstdc++](https://github.com/gcc-mirror/gcc/blob/d9375e490072d1aae73a93949aa158fcd2a27018/libstdc%2B%2B-v3/include/bits/stl_algo.h#L523) and [libc++](https://github.com/llvm-mirror/libcxx/blob/a12cb9d211019d99b5875b6d8034617cbc24c2cc/include/algorithm#L866). | First version | | --- | | ``` template< class InputIt, class UnaryPredicate > constexpr bool all_of(InputIt first, InputIt last, UnaryPredicate p) { return std::find_if_not(first, last, p) == last; } ``` | | Second version | | ``` template< class InputIt, class UnaryPredicate > constexpr bool any_of(InputIt first, InputIt last, UnaryPredicate p) { return std::find_if(first, last, p) != last; } ``` | | Third version | | ``` template< class InputIt, class UnaryPredicate > constexpr bool none_of(InputIt first, InputIt last, UnaryPredicate p) { return std::find_if(first, last, p) == last; } ``` | ### Notes The [return value](#Return_value) represented in the form of the [Truth table](https://en.wikipedia.org/wiki/Truth_table "enwiki:Truth table") is: | | | | --- | --- | | | input range contains | | | all `true`,none `false` | some `true`,some `false` | none `true`,all `false` | none `true`,none `false`(empty range) | | 1–2) `all_of` | `true` | `false` | `false` | `true` | | 3–4) `any_of` | `true` | `true` | `false` | `false` | | 5–6) `none_of` | `false` | `false` | `true` | `true` | ### Example ``` #include <vector> #include <numeric> #include <algorithm> #include <iterator> #include <iostream> #include <functional> int main() { std::vector<int> v(10, 2); std::partial_sum(v.cbegin(), v.cend(), v.begin()); std::cout << "Among the numbers: "; std::copy(v.cbegin(), v.cend(), std::ostream_iterator<int>(std::cout, " ")); std::cout << '\n'; if (std::all_of(v.cbegin(), v.cend(), [](int i){ return i % 2 == 0; })) { std::cout << "All numbers are even\n"; } if (std::none_of(v.cbegin(), v.cend(), std::bind(std::modulus<>(), std::placeholders::_1, 2))) { std::cout << "None of them are odd\n"; } struct DivisibleBy { const int d; DivisibleBy(int n) : d(n) {} bool operator()(int n) const { return n % d == 0; } }; if (std::any_of(v.cbegin(), v.cend(), DivisibleBy(7))) { std::cout << "At least one number is divisible by 7\n"; } } ``` Output: ``` Among the numbers: 2 4 6 8 10 12 14 16 18 20 All numbers are even None of them are odd At least one number is divisible by 7 ``` ### See also | | | | --- | --- | | [ranges::all\_ofranges::any\_ofranges::none\_of](ranges/all_any_none_of "cpp/algorithm/ranges/all any none of") (C++20)(C++20)(C++20) | checks if a predicate is `true` for all, any or none of the elements in a range (niebloid) | cpp std::clamp std::clamp ========== | Defined in header `[<algorithm>](../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | ``` template<class T> constexpr const T& clamp( const T& v, const T& lo, const T& hi ); ``` | (1) | (since C++17) | | ``` template<class T, class Compare> constexpr const T& clamp( const T& v, const T& lo, const T& hi, Compare comp ); ``` | (2) | (since C++17) | 1) If `v` compares less than `lo`, returns `lo`; otherwise if `hi` compares less than `v`, returns `hi`; otherwise returns `v`. Uses `operator<` to compare the values. 2) Same as (1), but uses `comp` to compare the values. The behavior is undefined if the value of `lo` is greater than `hi`. ### Parameters | | | | | --- | --- | --- | | v | - | the value to clamp | | lo,hi | - | the boundaries to clamp `v` to | | comp | - | comparison function object (i.e. an object that satisfies the requirements of [Compare](../named_req/compare "cpp/named req/Compare")) which returns ​`true` if the first argument is *less* than the second. The signature of the comparison function should be equivalent to the following: `bool cmp(const Type1 &a, const Type2 &b);` While the signature does not need to have `const &`, the function must not modify the objects passed to it and must be able to accept all values of type (possibly const) `Type1` and `Type2` regardless of [value category](../language/value_category "cpp/language/value category") (thus, `Type1 &` is not allowed, nor is `Type1` unless for `Type1` a move is equivalent to a copy (since C++11)). The types `Type1` and `Type2` must be such that an object of type `T` can be implicitly converted to both of them. ​ | | Type requirements | | -`T` must meet the requirements of [LessThanComparable](../named_req/lessthancomparable "cpp/named req/LessThanComparable") in order to use overloads (1). However, if `NaN` is avoided, `T` can be a floating-point type. | ### Return value Reference to `lo` if `v` is less than `lo`, reference to `hi` if `hi` is less than `v`, otherwise reference to `v`. ### Complexity At most two comparisons. ### Possible implementation | First version | | --- | | ``` template<class T> constexpr const T& clamp( const T& v, const T& lo, const T& hi ) { return clamp(v, lo, hi, less{}); } ``` | | Second version | | ``` template<class T, class Compare> constexpr const T& clamp( const T& v, const T& lo, const T& hi, Compare comp ) { return comp(v, lo) ? lo : comp(hi, v) ? hi : v; } ``` | ### Notes Capturing the result of `std::clamp` by reference produces a dangling reference if one of the parameters is a temporary and that parameter is returned: ``` int n = -1; const int& r = std::clamp(n, 0, 255); // r is dangling ``` If `v` compares equivalent to either bound, returns a reference to `v`, not the bound. | [Feature-test](../utility/feature_test "cpp/utility/feature test") macro | | --- | | [`__cpp_lib_clamp`](../feature_test#Library_features "cpp/feature test") | ### Example ``` #include <cstdint> #include <algorithm> #include <iostream> #include <iomanip> int main() { std::cout << " raw clamped to int8_t clamped to uint8_t\n"; for(int const v: {-129, -128, -1, 0, 42, 127, 128, 255, 256}) { std::cout << std::setw(04) << v << std::setw(20) << std::clamp(v, INT8_MIN, INT8_MAX) << std::setw(21) << std::clamp(v, 0, UINT8_MAX) << '\n'; } } ``` Output: ``` raw clamped to int8_t clamped to uint8_t -129 -128 0 -128 -128 0 -1 -1 0 0 0 0 42 42 42 127 127 127 128 127 128 255 127 255 256 127 255 ``` ### See also | | | | --- | --- | | [min](min "cpp/algorithm/min") | returns the smaller of the given values (function template) | | [max](max "cpp/algorithm/max") | returns the greater of the given values (function template) | | [in\_range](../utility/in_range "cpp/utility/in range") (C++20) | checks if an integer value is in the range of a given integer type (function template) | | [ranges::clamp](ranges/clamp "cpp/algorithm/ranges/clamp") (C++20) | clamps a value between a pair of boundary values (niebloid) | cpp std::for_each_n std::for\_each\_n ================= | Defined in header `[<algorithm>](../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | | (1) | | | ``` template< class InputIt, class Size, class UnaryFunction > InputIt for_each_n( InputIt first, Size n, UnaryFunction f ); ``` | (since C++17) (until C++20) | | ``` template< class InputIt, class Size, class UnaryFunction > constexpr InputIt for_each_n( InputIt first, Size n, UnaryFunction f ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt, class Size, class UnaryFunction2 > ForwardIt for_each_n( ExecutionPolicy&& policy, ForwardIt first, Size n, UnaryFunction2 f ); ``` | (2) | (since C++17) | 1) Applies the given function object `f` to the result of dereferencing every iterator in the range `[first, first + n)`, in order. 2) Applies the given function object `f` to the result of dereferencing every iterator in the range `[first, first + n)` (not necessarily in order). The algorithm is executed according to `policy`. This overload does not participate in overload resolution unless `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ExecutionPolicy>>` (until C++20) `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<ExecutionPolicy>>` (since C++20) is true. For both overloads, if the iterator type is mutable, `f` may modify the elements of the range through the dereferenced iterator. If `f` returns a result, the result is ignored. If `n` is less than zero, the behavior is undefined. Unlike the rest of the parallel algorithms, `for_each_n` is not allowed to make copies of the elements in the sequence even if they are trivially copyable. ### Parameters | | | | | --- | --- | --- | | first | - | the beginning of the range to apply the function to | | n | - | the number of elements to apply the function to | | policy | - | the execution policy to use. See [execution policy](execution_policy_tag_t "cpp/algorithm/execution policy tag t") for details. | | f | - | function object, to be applied to the result of dereferencing every iterator in the range `[first, first + n)` The signature of the function should be equivalent to the following: `void fun(const Type &a);` The signature does not need to have `const &`. The type `Type` must be such that an object of type `InputIt` can be dereferenced and then implicitly converted to `Type`. ​ | | Type requirements | | -`InputIt` must meet the requirements of [LegacyInputIterator](../named_req/inputiterator "cpp/named req/InputIterator"). | | -`ForwardIt` must meet the requirements of [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"). | | -`UnaryFunction` must meet the requirements of [MoveConstructible](../named_req/moveconstructible "cpp/named req/MoveConstructible"). Does not have to be [CopyConstructible](../named_req/copyconstructible "cpp/named req/CopyConstructible") | | -`UnaryFunction2` must meet the requirements of [CopyConstructible](../named_req/copyconstructible "cpp/named req/CopyConstructible"). | ### Return value An iterator equal to `first + n`, or more formally, to `[std::advance](http://en.cppreference.com/w/cpp/iterator/advance)(first, n)`. ### Complexity Exactly `n` applications of `f`. ### Exceptions The overload with a template parameter named `ExecutionPolicy` reports errors as follows: * If execution of a function invoked as part of the algorithm throws an exception and `ExecutionPolicy` is one of the [standard policies](execution_policy_tag_t "cpp/algorithm/execution policy tag t"), `[std::terminate](../error/terminate "cpp/error/terminate")` is called. For any other `ExecutionPolicy`, the behavior is implementation-defined. * If the algorithm fails to allocate memory, `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` is thrown. ### Possible implementation See also the implementation in [libstdc++](https://github.com/gcc-mirror/gcc/blob/d9375e490072d1aae73a93949aa158fcd2a27018/libstdc%2B%2B-v3/include/pstl/algorithm_impl.h#L82), [libc++](https://github.com/llvm-mirror/libcxx/blob/a12cb9d211019d99b5875b6d8034617cbc24c2cc/include/algorithm#L896) and [MSVC stdlib](https://github.com/microsoft/STL/blob/ff83542af4b683fb2f2dea1423fd6c50fe3e13b0/stl/inc/algorithm#L246). | | | --- | | ``` template<class InputIt, class Size, class UnaryFunction> InputIt for_each_n(InputIt first, Size n, UnaryFunction f) { for (Size i = 0; i < n; ++first, (void) ++i) { f(*first); } return first; } ``` | ### Example ``` #include <algorithm> #include <iostream> #include <vector> int main() { std::vector<int> ns{1, 2, 3, 4, 5}; for (auto n: ns) std::cout << n << ", "; std::cout << '\n'; std::for_each_n(ns.begin(), 3, [](auto& n){ n *= 2; }); for (auto n: ns) std::cout << n << ", "; std::cout << '\n'; } ``` Output: ``` 1, 2, 3, 4, 5, 2, 4, 6, 4, 5, ``` ### See also | | | | --- | --- | | [transform](transform "cpp/algorithm/transform") | applies a function to a range of elements, storing results in a destination range (function template) | | [range-`for` loop](../language/range-for "cpp/language/range-for")(C++11) | executes loop over range | | [for\_each](for_each "cpp/algorithm/for each") | applies a function to a range of elements (function template) | | [ranges::for\_each\_n](ranges/for_each_n "cpp/algorithm/ranges/for each n") (C++20) | applies a function object to the first n elements of a sequence (niebloid) | cpp std::unique std::unique =========== | Defined in header `[<algorithm>](../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | | (1) | | | ``` template< class ForwardIt > ForwardIt unique( ForwardIt first, ForwardIt last ); ``` | (until C++20) | | ``` template< class ForwardIt > constexpr ForwardIt unique( ForwardIt first, ForwardIt last ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt > ForwardIt unique( ExecutionPolicy&& policy, ForwardIt first, ForwardIt last ); ``` | (2) | (since C++17) | | | (3) | | | ``` template< class ForwardIt, class BinaryPredicate > ForwardIt unique( ForwardIt first, ForwardIt last, BinaryPredicate p ); ``` | (until C++20) | | ``` template< class ForwardIt, class BinaryPredicate > constexpr ForwardIt unique( ForwardIt first, ForwardIt last, BinaryPredicate p ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt, class BinaryPredicate > ForwardIt unique( ExecutionPolicy&& policy, ForwardIt first, ForwardIt last, BinaryPredicate p ); ``` | (4) | (since C++17) | Eliminates all except the first element from every consecutive group of equivalent elements from the range `[first, last)` and returns a past-the-end iterator for the new *logical* end of the range. Removing is done by shifting the elements in the range in such a way that elements to be erased are overwritten. 1) Elements are compared using `operator==`. The behavior is undefined if it is not an [equivalence relation](https://en.wikipedia.org/wiki/equivalence_relation "enwiki:equivalence relation"). 3) Elements are compared using the given binary predicate `p`. The behavior is undefined if it is not an equivalence relation. 2,4) Same as (1,3), but executed according to `policy`. These overloads do not participate in overload resolution unless `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ExecutionPolicy>>` (until C++20) `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<ExecutionPolicy>>` (since C++20) is true. ### Parameters | | | | | --- | --- | --- | | first, last | - | the range of elements to process | | policy | - | the execution policy to use. See [execution policy](execution_policy_tag_t "cpp/algorithm/execution policy tag t") for details. | | p | - | binary predicate which returns ​`true` if the elements should be treated as equal. The signature of the predicate function should be equivalent to the following: `bool pred(const Type1 &a, const Type2 &b);` While the signature does not need to have `const &`, the function must not modify the objects passed to it and must be able to accept all values of type (possibly const) `Type1` and `Type2` regardless of [value category](../language/value_category "cpp/language/value category") (thus, `Type1 &` is not allowed, nor is `Type1` unless for `Type1` a move is equivalent to a copy (since C++11)). The types `Type1` and `Type2` must be such that an object of type `ForwardIt` can be dereferenced and then implicitly converted to both of them. ​ | | Type requirements | | -`ForwardIt` must meet the requirements of [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"). | | -The type of dereferenced `ForwardIt` must meet the requirements of [MoveAssignable](../named_req/moveassignable "cpp/named req/MoveAssignable"). | ### Return value A `ForwardIt` to the new end of the range. ### Complexity For nonempty ranges, exactly `[std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(first,last) -1` applications of the corresponding predicate. ### Exceptions The overloads with a template parameter named `ExecutionPolicy` report errors as follows: * If execution of a function invoked as part of the algorithm throws an exception and `ExecutionPolicy` is one of the [standard policies](execution_policy_tag_t "cpp/algorithm/execution policy tag t"), `[std::terminate](../error/terminate "cpp/error/terminate")` is called. For any other `ExecutionPolicy`, the behavior is implementation-defined. * If the algorithm fails to allocate memory, `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` is thrown. ### Notes Relative order of the elements that remain is preserved and the *physical* size of the container is unchanged. Iterators in `[r, last)` (if any), where `r` is the return value, are still dereferenceable, but the elements themselves have unspecified values. A call to `unique` is typically followed by a call to a container's `erase` member function, which erases the unspecified values and reduces the *physical* size of the container to match its new *logical* size. ### Possible implementation See also the implementations in [libstdc++](https://github.com/gcc-mirror/gcc/blob/7f2f4b87910506effb8dffffc60eeb2451573126/libstdc%2B%2B-v3/include/bits/stl_algo.h#L919-L1000), [libc++](https://github.com/llvm/llvm-project/blob/134723edd5bf06ff6ec8aca7b87c56e5bd70ccae/libcxx/include/__algorithm/unique_copy.h), and [MSVC STL](https://github.com/microsoft/STL/blob/472161105d596192194d4715ccad307c6c163b4a/stl/inc/algorithm#L3804-L3848). | First version | | --- | | ``` template<class ForwardIt> ForwardIt unique(ForwardIt first, ForwardIt last) { if (first == last) return last; ForwardIt result = first; while (++first != last) { if (!(*result == *first) && ++result != first) { *result = std::move(*first); } } return ++result; } ``` | | Second version | | ``` template<class ForwardIt, class BinaryPredicate> ForwardIt unique(ForwardIt first, ForwardIt last, BinaryPredicate p) { if (first == last) return last; ForwardIt result = first; while (++first != last) { if (!p(*result, *first) && ++result != first) { *result = std::move(*first); } } return ++result; } ``` | ### Example ``` #include <algorithm> #include <iostream> #include <vector> int main() { // a vector containing several duplicate elements std::vector<int> v{1,2,1,1,3,3,3,4,5,4}; auto print = [&] (int id) { std::cout << "@" << id << ": "; for (int i : v) std::cout << i << ' '; std::cout << '\n'; }; print(1); // remove consecutive (adjacent) duplicates auto last = std::unique(v.begin(), v.end()); // v now holds {1 2 1 3 4 5 4 x x x}, where 'x' is indeterminate v.erase(last, v.end()); print(2); // sort followed by unique, to remove all duplicates std::sort(v.begin(), v.end()); // {1 1 2 3 4 4 5} print(3); last = std::unique(v.begin(), v.end()); // v now holds {1 2 3 4 5 x x}, where 'x' is indeterminate v.erase(last, v.end()); print(4); } ``` Output: ``` @1: 1 2 1 1 3 3 3 4 5 4 @2: 1 2 1 3 4 5 4 @3: 1 1 2 3 4 4 5 @4: 1 2 3 4 5 ``` ### See also | | | | --- | --- | | [adjacent\_find](adjacent_find "cpp/algorithm/adjacent find") | finds the first two adjacent items that are equal (or satisfy a given predicate) (function template) | | [unique\_copy](unique_copy "cpp/algorithm/unique copy") | creates a copy of some range of elements that contains no consecutive duplicates (function template) | | [removeremove\_if](remove "cpp/algorithm/remove") | removes elements satisfying specific criteria (function template) | | [unique](../container/list/unique "cpp/container/list/unique") | removes consecutive duplicate elements (public member function of `std::list<T,Allocator>`) | | [unique](../container/forward_list/unique "cpp/container/forward list/unique") (C++11) | removes consecutive duplicate elements (public member function of `std::forward_list<T,Allocator>`) | | [ranges::unique](ranges/unique "cpp/algorithm/ranges/unique") (C++20) | removes consecutive duplicate elements in a range (niebloid) |
programming_docs
cpp std::next_permutation std::next\_permutation ====================== | Defined in header `[<algorithm>](../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | | (1) | | | ``` template< class BidirIt > bool next_permutation( BidirIt first, BidirIt last ); ``` | (until C++20) | | ``` template< class BidirIt > constexpr bool next_permutation( BidirIt first, BidirIt last ); ``` | (since C++20) | | | (2) | | | ``` template< class BidirIt, class Compare > bool next_permutation( BidirIt first, BidirIt last, Compare comp ); ``` | (until C++20) | | ``` template< class BidirIt, class Compare > constexpr bool next_permutation( BidirIt first, BidirIt last, Compare comp ); ``` | (since C++20) | Permutes the range `[first, last)` into the next permutation, where the set of all permutations is ordered lexicographically with respect to `operator<` or `comp`. Returns `true` if such a "next permutation" exists; otherwise transforms the range into the lexicographically first permutation (as if by `std::sort(first, last, comp)`) and returns `false`. ### Parameters | | | | | --- | --- | --- | | first, last | - | the range of elements to permute | | comp | - | comparison function object (i.e. an object that satisfies the requirements of [Compare](../named_req/compare "cpp/named req/Compare")) which returns ​`true` if the first argument is *less* than the second. The signature of the comparison function should be equivalent to the following: `bool cmp(const Type1 &a, const Type2 &b);` While the signature does not need to have `const &`, the function must not modify the objects passed to it and must be able to accept all values of type (possibly const) `Type1` and `Type2` regardless of [value category](../language/value_category "cpp/language/value category") (thus, `Type1 &` is not allowed, nor is `Type1` unless for `Type1` a move is equivalent to a copy (since C++11)). The types `Type1` and `Type2` must be such that an object of type `BidirIt` can be dereferenced and then implicitly converted to both of them. ​ | | Type requirements | | -`BidirIt` must meet the requirements of [ValueSwappable](../named_req/valueswappable "cpp/named req/ValueSwappable") and [LegacyBidirectionalIterator](../named_req/bidirectionaliterator "cpp/named req/BidirectionalIterator"). | ### Return value `true` if the new permutation is lexicographically greater than the old. `false` if the last permutation was reached and the range was reset to the first permutation. ### Exceptions Any exceptions thrown from iterator operations or the element swap. ### Complexity At most N/2 swaps, where `N = [std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(first, last)`. Averaged over the entire sequence of permutations, typical implementations use about 3 comparisons and 1.5 swaps per call. ### Notes Implementations (e.g. [MSVC STL](https://github.com/microsoft/STL/blob/main/stl/src/vector_algorithms.cpp)) may enable vectorization when the iterator type satisfies [LegacyContiguousIterator](../named_req/contiguousiterator "cpp/named req/ContiguousIterator") and swapping its value type calls neither non-trivial special member function nor [ADL](../language/adl "cpp/language/adl")-found `swap`. ### Possible implementation | | | --- | | ``` template<class BidirIt> bool next_permutation(BidirIt first, BidirIt last) { auto r_first = std::make_reverse_iterator(last); auto r_last = std::make_reverse_iterator(first); auto left = std::is_sorted_until(r_first, r_last); if(left != r_last){ auto right = std::upper_bound(r_first, left, *left); std::iter_swap(left, right); } std::reverse(left.base(), last); return left != r_last; } ``` | ### Example The following code prints all three permutations of the string "aba" ``` #include <algorithm> #include <string> #include <iostream> int main() { std::string s = "aba"; std::sort(s.begin(), s.end()); do { std::cout << s << '\n'; } while(std::next_permutation(s.begin(), s.end())); } ``` Output: ``` aab aba baa ``` ### See also | | | | --- | --- | | [is\_permutation](is_permutation "cpp/algorithm/is permutation") (C++11) | determines if a sequence is a permutation of another sequence (function template) | | [prev\_permutation](prev_permutation "cpp/algorithm/prev permutation") | generates the next smaller lexicographic permutation of a range of elements (function template) | | [ranges::next\_permutation](ranges/next_permutation "cpp/algorithm/ranges/next permutation") (C++20) | generates the next greater lexicographic permutation of a range of elements (niebloid) | cpp std::inclusive_scan std::inclusive\_scan ==================== | Defined in header `[<numeric>](../header/numeric "cpp/header/numeric")` | | | | --- | --- | --- | | | (1) | | | ``` template< class InputIt, class OutputIt > OutputIt inclusive_scan( InputIt first, InputIt last, OutputIt d_first ); ``` | (since C++17) (until C++20) | | ``` template< class InputIt, class OutputIt > constexpr OutputIt inclusive_scan( InputIt first, InputIt last, OutputIt d_first ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt1, class ForwardIt2 > ForwardtIt2 inclusive_scan( ExecutionPolicy&& policy, ForwardIt1 first, ForwardIt1 last, ForwardIt2 d_first ); ``` | (2) | (since C++17) | | | (3) | | | ``` template< class InputIt, class OutputIt, class BinaryOperation > OutputIt inclusive_scan( InputIt first, InputIt last, OutputIt d_first, BinaryOperation binary_op ); ``` | (since C++17) (until C++20) | | ``` template< class InputIt, class OutputIt, class BinaryOperation > constexpr OutputIt inclusive_scan( InputIt first, InputIt last, OutputIt d_first, BinaryOperation binary_op ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt1, class ForwardIt2, class BinaryOperation > ForwardIt2 inclusive_scan( ExecutionPolicy&& policy, ForwardIt1 first, ForwardIt1 last, ForwardIt2 d_first, BinaryOperation binary_op ); ``` | (4) | (since C++17) | | | (5) | | | ``` template< class InputIt, class OutputIt, class BinaryOperation, class T > OutputIt inclusive_scan( InputIt first, InputIt last, OutputIt d_first, BinaryOperation binary_op, T init ); ``` | (since C++17) (until C++20) | | ``` template< class InputIt, class OutputIt, class BinaryOperation, class T > constexpr OutputIt inclusive_scan( InputIt first, InputIt last, OutputIt d_first, BinaryOperation binary_op, T init ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt1, class ForwardIt2, class BinaryOperation, class T > ForwardIt2 inclusive_scan( ExecutionPolicy&& policy, ForwardIt1 first, ForwardIt1 last, ForwardIt2 d_first, BinaryOperation binary_op, T init ); ``` | (6) | (since C++17) | Computes an inclusive prefix sum operation using `binary_op` (or `[std::plus](http://en.cppreference.com/w/cpp/utility/functional/plus)<>()` for overloads (1-2)) for the range `[first, last)`, using `init` as the initial value (if provided), and writes the results to the range beginning at `d_first`. "inclusive" means that the i-th input element is included in the i-th sum. Formally, assigns through each iterator `i` in [d\_first, d\_first + (last - first)) the value of: * for overloads (1-4), the generalized noncommutative sum of `*j...` for every `j` in [first, first + (i - d\_first + 1)) over `binary_op` * for overloads (5-6), the generalized noncommutative sum of `init, *j...` for every `j` in [first, first + (i - d\_first + 1)) over `binary_op` where generalized noncommutative sum GNSUM(op, a 1, ..., a N) is defined as follows: * if N=1, a 1 * if N > 1, op(GNSUM(op, a 1, ..., a K), GNSUM(op, a M, ..., a N)) for any K where 1 < K+1 = M ≤ N In other words, the summation operations may be performed in arbitrary order, and the behavior is nondeterministic if `binary_op` is not associative. Overloads (2,4,6) are executed according to `policy`. These overloads do not participate in overload resolution unless `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ExecutionPolicy>>` (until C++20) `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<ExecutionPolicy>>` (since C++20) is true. `binary_op` shall not invalidate iterators (including the end iterators) or subranges, nor modify elements in the ranges [first, last) or [d\_first, d\_first + (last - first)). Otherwise, the behavior is undefined. ### Parameters | | | | | --- | --- | --- | | first, last | - | the range of elements to sum | | d\_first | - | the beginning of the destination range; may be equal to `first` | | policy | - | the execution policy to use. See [execution policy](execution_policy_tag_t "cpp/algorithm/execution policy tag t") for details. | | init | - | the initial value (optional) | | binary\_op | - | binary [FunctionObject](../named_req/functionobject "cpp/named req/FunctionObject") that will be applied in to the result of dereferencing the input iterators, the results of other `binary_op`, and `init` (if provided). | | Type requirements | | -`InputIt` must meet the requirements of [LegacyInputIterator](../named_req/inputiterator "cpp/named req/InputIterator"). | | -`OutputIt` must meet the requirements of [LegacyOutputIterator](../named_req/outputiterator "cpp/named req/OutputIterator"). | | -`ForwardIt1` must meet the requirements of [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"). | | -`ForwardIt2` must meet the requirements of [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"). | | -If `init` is not provided, `decltype(first)`'s value\_type must be [MoveConstructible](../named_req/moveconstructible "cpp/named req/MoveConstructible") and `binary_op(*first, *first)` must be convertible to `decltype(first)`'s value type. | | -`T (if init is provided)` must meet the requirements of [MoveConstructible](../named_req/moveconstructible "cpp/named req/MoveConstructible"). All of `binary_op(init, *first)`, `binary_op(init, init)`, and `binary_op(*first, *first)` must be convertible to T | ### Return value Iterator to the element past the last element written. ### Complexity O(last - first) applications of the binary operation. ### Exceptions The overloads with a template parameter named `ExecutionPolicy` report errors as follows: * If execution of a function invoked as part of the algorithm throws an exception and `ExecutionPolicy` is one of the [standard policies](execution_policy_tag_t "cpp/algorithm/execution policy tag t"), `[std::terminate](../error/terminate "cpp/error/terminate")` is called. For any other `ExecutionPolicy`, the behavior is implementation-defined. * If the algorithm fails to allocate memory, `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` is thrown. ### Example ``` #include <functional> #include <iostream> #include <iterator> #include <numeric> #include <vector> int main() { std::vector data {3, 1, 4, 1, 5, 9, 2, 6}; std::cout << "exclusive sum: "; std::exclusive_scan(data.begin(), data.end(), std::ostream_iterator<int>(std::cout, " "), 0); std::cout << "\ninclusive sum: "; std::inclusive_scan(data.begin(), data.end(), std::ostream_iterator<int>(std::cout, " ")); std::cout << "\n\nexclusive product: "; std::exclusive_scan(data.begin(), data.end(), std::ostream_iterator<int>(std::cout, " "), 1, std::multiplies<>{}); std::cout << "\ninclusive product: "; std::inclusive_scan(data.begin(), data.end(), std::ostream_iterator<int>(std::cout, " "), std::multiplies<>{}); } ``` Output: ``` exclusive sum: 0 3 4 8 9 14 23 25 inclusive sum: 3 4 8 9 14 23 25 31 exclusive product: 1 3 3 12 12 60 540 1080 inclusive product: 3 3 12 12 60 540 1080 6480 ``` ### See also | | | | --- | --- | | [adjacent\_difference](adjacent_difference "cpp/algorithm/adjacent difference") | computes the differences between adjacent elements in a range (function template) | | [accumulate](accumulate "cpp/algorithm/accumulate") | sums up a range of elements (function template) | | [partial\_sum](partial_sum "cpp/algorithm/partial sum") | computes the partial sum of a range of elements (function template) | | [transform\_inclusive\_scan](transform_inclusive_scan "cpp/algorithm/transform inclusive scan") (C++17) | applies an invocable, then calculates inclusive scan (function template) | | [exclusive\_scan](exclusive_scan "cpp/algorithm/exclusive scan") (C++17) | similar to `[std::partial\_sum](partial_sum "cpp/algorithm/partial sum")`, excludes the ith input element from the ith sum (function template) | cpp std::set_union std::set\_union =============== | Defined in header `[<algorithm>](../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | | (1) | | | ``` template< class InputIt1, class InputIt2, class OutputIt > OutputIt set_union( InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2, OutputIt d_first ); ``` | (until C++20) | | ``` template< class InputIt1, class InputIt2, class OutputIt > constexpr OutputIt set_union( InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2, OutputIt d_first ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt1, class ForwardIt2, class ForwardIt3 > ForwardIt3 set_union( ExecutionPolicy&& policy, ForwardIt1 first1, ForwardIt1 last1, ForwardIt2 first2, ForwardIt2 last2, ForwardIt3 d_first ); ``` | (2) | (since C++17) | | | (3) | | | ``` template< class InputIt1, class InputIt2, class OutputIt, class Compare > OutputIt set_union( InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2, OutputIt d_first, Compare comp ); ``` | (until C++20) | | ``` template< class InputIt1, class InputIt2, class OutputIt, class Compare > constexpr OutputIt set_union( InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2, OutputIt d_first, Compare comp ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt1, class ForwardIt2, class ForwardIt3, class Compare > ForwardIt3 set_union( ExecutionPolicy&& policy, ForwardIt1 first1, ForwardIt1 last1, ForwardIt2 first2, ForwardIt2 last2, ForwardIt3 d_first, Compare comp ); ``` | (4) | (since C++17) | Constructs a sorted union beginning at `d_first` consisting of the set of elements present in one or both sorted ranges `[first1, last1)` and `[first2, last2)`. If some element is found `m` times in `[first1, last1)` and `n` times in `[first2, last2)`, then all `m` elements will be copied from `[first1, last1)` to `d_first`, preserving order, and then exactly `[std::max](http://en.cppreference.com/w/cpp/algorithm/max)(n-m, 0)` elements will be copied from `[first2, last2)` to `d_first`, also preserving order. The resulting range cannot overlap with either of the input ranges. 1) Elements are compared using `operator<` and the ranges must be sorted with respect to the same. 3) Elements are compared using the given binary comparison function `comp` and the ranges must be sorted with respect to the same. 2,4) Same as (1,3), but executed according to `policy`. These overloads do not participate in overload resolution unless `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ExecutionPolicy>>` (until C++20) `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<ExecutionPolicy>>` (since C++20) is true. ### Parameters | | | | | --- | --- | --- | | first1, last1 | - | the first input sorted range | | first2, last2 | - | the second input sorted range | | d\_first | - | the beginning of the output range | | policy | - | the execution policy to use. See [execution policy](execution_policy_tag_t "cpp/algorithm/execution policy tag t") for details. | | comp | - | comparison function object (i.e. an object that satisfies the requirements of [Compare](../named_req/compare "cpp/named req/Compare")) which returns ​`true` if the first argument is *less* than (i.e. is ordered *before*) the second. The signature of the comparison function should be equivalent to the following: `bool cmp(const Type1 &a, const Type2 &b);` While the signature does not need to have `const &`, the function must not modify the objects passed to it and must be able to accept all values of type (possibly const) `Type1` and `Type2` regardless of [value category](../language/value_category "cpp/language/value category") (thus, `Type1 &` is not allowed, nor is `Type1` unless for `Type1` a move is equivalent to a copy (since C++11)). The types `Type1` and `Type2` must be such that objects of types `InputIt1` and `InputIt2` can be dereferenced and then implicitly converted to both `Type1` and `Type2`. ​ | | Type requirements | | -`InputIt1, InputIt2` must meet the requirements of [LegacyInputIterator](../named_req/inputiterator "cpp/named req/InputIterator"). | | -`ForwardIt1, ForwardIt2, ForwardIt3` must meet the requirements of [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"). | | -`OutputIt` must meet the requirements of [LegacyOutputIterator](../named_req/outputiterator "cpp/named req/OutputIterator"). | ### Return value Iterator past the end of the constructed range. ### Complexity At most \(\scriptsize 2\cdot(N\_1+N\_2)-1\)2·(N 1+N 2)-1 comparisons, where \(\scriptsize N\_1\)N 1 and \(\scriptsize N\_2\)N 2 are `[std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(first1, last1)` and `[std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(first2, last2)`, respectively. ### Exceptions The overloads with a template parameter named `ExecutionPolicy` report errors as follows: * If execution of a function invoked as part of the algorithm throws an exception and `ExecutionPolicy` is one of the [standard policies](execution_policy_tag_t "cpp/algorithm/execution policy tag t"), `[std::terminate](../error/terminate "cpp/error/terminate")` is called. For any other `ExecutionPolicy`, the behavior is implementation-defined. * If the algorithm fails to allocate memory, `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` is thrown. ### Notes This algorithm performs a similar task as `[std::merge](http://en.cppreference.com/w/cpp/algorithm/merge)` does. Both consume two sorted input ranges and produce a sorted output with elements from both inputs. The difference between these two algorithms is with handling values from both input ranges which compare equivalent (see notes on [LessThanComparable](../named_req/lessthancomparable "cpp/named req/LessThanComparable")). If any equivalent values appeared `n` times in the first range and `m` times in the second, `std::merge` would output all `n+m` occurrences whereas `std::set_union` would output `[std::max](http://en.cppreference.com/w/cpp/algorithm/max)(n, m)` ones only. So `std::merge` outputs exactly `[std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(first1, last1) + [std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(first2, last2)` values and `std::set_union` may produce fewer. ### Possible implementation | First version | | --- | | ``` template<class InputIt1, class InputIt2, class OutputIt> OutputIt set_union(InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2, OutputIt d_first) { for (; first1 != last1; ++d_first) { if (first2 == last2) return std::copy(first1, last1, d_first); if (*first2 < *first1) { *d_first = *first2++; } else { *d_first = *first1; if (!(*first1 < *first2)) ++first2; ++first1; } } return std::copy(first2, last2, d_first); } ``` | | Second version | | ``` template<class InputIt1, class InputIt2, class OutputIt, class Compare> OutputIt set_union(InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2, OutputIt d_first, Compare comp) { for (; first1 != last1; ++d_first) { if (first2 == last2) { // Finished range 2, include the rest of range 1: return std::copy(first1, last1, d_first); } if (comp(*first2, *first1)) { *d_first = *first2++; } else { *d_first = *first1; if (!comp(*first1, *first2)) { // Equivalent => don't need to include *first2. ++first2; } ++first1; } } // Finished range 1, include the rest of range 2: return std::copy(first2, last2, d_first); } ``` | ### Example Example with vectors : ``` #include <vector> #include <iostream> #include <algorithm> #include <iterator> int main() { { std::vector<int> v1 = {1, 2, 3, 4, 5}; std::vector<int> v2 = { 3, 4, 5, 6, 7}; std::vector<int> dest1; std::set_union(v1.begin(), v1.end(), v2.begin(), v2.end(), std::back_inserter(dest1)); for (const auto &i : dest1) { std::cout << i << ' '; } std::cout << '\n'; } { std::vector<int> v1 = {1, 2, 3, 4, 5, 5, 5}; std::vector<int> v2 = { 3, 4, 5, 6, 7}; std::vector<int> dest1; std::set_union(v1.begin(), v1.end(), v2.begin(), v2.end(), std::back_inserter(dest1)); for (const auto &i : dest1) { std::cout << i << ' '; } std::cout << '\n'; } } ``` Output: ``` 1 2 3 4 5 6 7 1 2 3 4 5 5 5 6 7 ``` ### See also | | | | --- | --- | | [includes](includes "cpp/algorithm/includes") | returns true if one sequence is a subsequence of another (function template) | | [merge](merge "cpp/algorithm/merge") | merges two sorted ranges (function template) | | [set\_difference](set_difference "cpp/algorithm/set difference") | computes the difference between two sets (function template) | | [set\_intersection](set_intersection "cpp/algorithm/set intersection") | computes the intersection of two sets (function template) | | [set\_symmetric\_difference](set_symmetric_difference "cpp/algorithm/set symmetric difference") | computes the symmetric difference between two sets (function template) | | [ranges::set\_union](ranges/set_union "cpp/algorithm/ranges/set union") (C++20) | computes the union of two sets (niebloid) |
programming_docs
cpp std::transform_exclusive_scan std::transform\_exclusive\_scan =============================== | Defined in header `[<numeric>](../header/numeric "cpp/header/numeric")` | | | | --- | --- | --- | | | (1) | | | ``` template< class InputIt, class OutputIt, class T, class BinaryOperation, class UnaryOperation> OutputIt transform_exclusive_scan( InputIt first, InputIt last, OutputIt d_first, T init, BinaryOperation binary_op, UnaryOperation unary_op ); ``` | (since C++17) (until C++20) | | ``` template< class InputIt, class OutputIt, class T, class BinaryOperation, class UnaryOperation> constexpr OutputIt transform_exclusive_scan( InputIt first, InputIt last, OutputIt d_first, T init, BinaryOperation binary_op, UnaryOperation unary_op ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt1, class ForwardIt2, class T, class BinaryOperation, class UnaryOperation > ForwardIt2 transform_exclusive_scan( ExecutionPolicy&& policy, ForwardIt1 first, ForwardIt1 last, ForwardIt2 d_first, T init, BinaryOperation binary_op, UnaryOperation unary_op ); ``` | (2) | (since C++17) | Transforms each element in the range `[first, last)` with `unary_op`, then computes an exclusive prefix sum operation using `binary_op` over the resulting range, with `init` as the initial value, and writes the results to the range beginning at `d_first`. "exclusive" means that the i-th input element is not included in the i-th sum. Formally, assigns through each iterator `i` in [d\_first, d\_first + (last - first)) the value of the generalized noncommutative sum of `init, unary_op(*j)...` for every `j` in [first, first + (i - d\_first)) over `binary_op`, where generalized noncommutative sum GNSUM(op, a 1, ..., a N) is defined as follows: * if N=1, a 1 * if N > 1, op(GNSUM(op, a 1, ..., a K), GNSUM(op, a M, ..., a N)) for any K where 1 < K+1 = M ≤ N In other words, the summation operations may be performed in arbitrary order, and the behavior is nondeterministic if `binary_op` is not associative. Overload (2) is executed according to `policy`. This overload does not participate in overload resolution unless `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ExecutionPolicy>>` (until C++20) `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<ExecutionPolicy>>` (since C++20) is true. `unary_op` and `binary_op` shall not invalidate iterators (including the end iterators) or subranges, nor modify elements in the ranges [first, last) or [d\_first, d\_first + (last - first)). Otherwise, the behavior is undefined. ### Parameters | | | | | --- | --- | --- | | first, last | - | the range of elements to sum | | d\_first | - | the beginning of the destination range, may be equal to `first` | | policy | - | the execution policy to use. See [execution policy](execution_policy_tag_t "cpp/algorithm/execution policy tag t") for details. | | init | - | the initial value | | unary\_op | - | unary [FunctionObject](../named_req/functionobject "cpp/named req/FunctionObject") that will be applied to each element of the input range. The return type must be acceptable as input to `binary_op`. | | binary\_op | - | binary [FunctionObject](../named_req/functionobject "cpp/named req/FunctionObject") that will be applied in to the result of `unary_op`, the results of other `binary_op`, and `init`. | | Type requirements | | -`InputIt` must meet the requirements of [LegacyInputIterator](../named_req/inputiterator "cpp/named req/InputIterator"). | | -`OutputIt` must meet the requirements of [LegacyOutputIterator](../named_req/outputiterator "cpp/named req/OutputIterator"). | | -`ForwardIt1, ForwardIt2` must meet the requirements of [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"). | | -`T` must meet the requirements of [MoveConstructible](../named_req/moveconstructible "cpp/named req/MoveConstructible"). All of `binary_op(init, unary_op(*first))`, `binary_op(init, init)`, and `binary_op(unary_op(*first), unary_op(*first))` must be convertible to `T`. | ### Return value Iterator to the element past the last element written. ### Complexity O(last - first) applications of each of `binary_op` and `unary_op`. ### Exceptions The overload with a template parameter named `ExecutionPolicy` reports errors as follows: * If execution of a function invoked as part of the algorithm throws an exception and `ExecutionPolicy` is one of the [standard policies](execution_policy_tag_t "cpp/algorithm/execution policy tag t"), `[std::terminate](../error/terminate "cpp/error/terminate")` is called. For any other `ExecutionPolicy`, the behavior is implementation-defined. * If the algorithm fails to allocate memory, `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` is thrown. ### Notes `unary_op` is not applied to `init`. ### Example ``` #include <functional> #include <iostream> #include <iterator> #include <numeric> #include <vector> int main() { std::vector data {3, 1, 4, 1, 5, 9, 2, 6}; auto times_10 = [](int x) { return x * 10; }; std::cout << "10 times exclusive sum: "; std::transform_exclusive_scan(data.begin(), data.end(), std::ostream_iterator<int>(std::cout, " "), 0, std::plus<int>{}, times_10); std::cout << "\n10 times inclusive sum: "; std::transform_inclusive_scan(data.begin(), data.end(), std::ostream_iterator<int>(std::cout, " "), std::plus<int>{}, times_10); } ``` Output: ``` 10 times exclusive sum: 0 30 40 80 90 140 230 250 10 times inclusive sum: 30 40 80 90 140 230 250 310 ``` ### See also | | | | --- | --- | | [partial\_sum](partial_sum "cpp/algorithm/partial sum") | computes the partial sum of a range of elements (function template) | | [exclusive\_scan](exclusive_scan "cpp/algorithm/exclusive scan") (C++17) | similar to `[std::partial\_sum](partial_sum "cpp/algorithm/partial sum")`, excludes the ith input element from the ith sum (function template) | | [transform\_inclusive\_scan](transform_inclusive_scan "cpp/algorithm/transform inclusive scan") (C++17) | applies an invocable, then calculates inclusive scan (function template) | cpp std::ranges::for_each, std::ranges::for_each_result std::ranges::for\_each, std::ranges::for\_each\_result ====================================================== | Defined in header `[<algorithm>](../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | Call signature | | | | ``` template< std::input_iterator I, std::sentinel_for<I> S, class Proj = std::identity, std::indirectly_unary_invocable<std::projected<I, Proj>> Fun > constexpr for_each_result<I, Fun> for_each( I first, S last, Fun f, Proj proj = {} ); ``` | (1) | (since C++20) | | ``` template< ranges::input_range R, class Proj = std::identity, std::indirectly_unary_invocable<std::projected<ranges::iterator_t<R>, Proj>> Fun > constexpr for_each_result<ranges::borrowed_iterator_t<R>, Fun> for_each( R&& r, Fun f, Proj proj = {} ); ``` | (2) | (since C++20) | | Helper types | | | | ``` template< class I, class F > using for_each_result = ranges::in_fun_result<I, F>; ``` | (3) | (since C++20) | 1) Applies the given function object `f` to the result of the value projected by each iterator in the range `[first, last)`, in order. 2) Same as (1), but uses `r` as the source range, as if using `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r)` as `first` and `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r)` as `last`. For both overloads, if the iterator type is mutable, `f` may modify the elements of the range through the dereferenced iterator. If `f` returns a result, the result is ignored. The function-like entities described on this page are *niebloids*, that is: * Explicit template argument lists cannot be specified when calling any of them. * None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl"). * When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited. In practice, they may be implemented as function objects, or with special compiler extensions. ### Parameters | | | | | --- | --- | --- | | first, last | - | iterator-sentinel pair denoting the range to apply the function to | | r | - | the range of elements to apply the function to | | f | - | the function to apply to the projected range | | proj | - | projection to apply to the elements | ### Return value `{std::[ranges::next](http://en.cppreference.com/w/cpp/iterator/ranges/next)(std::move(first), last), std::move(f)}` ### Complexity Exactly `last` - `first` applications of `f` and `proj`. ### Possible implementation | | | --- | | ``` struct for_each_fn { template<std::input_iterator I, std::sentinel_for<I> S, class Proj = std::identity, std::indirectly_unary_invocable<std::projected<I, Proj>> Fun> constexpr ranges::for_each_result<I, Fun> operator()(I first, S last, Fun f, Proj proj = {}) const { for (; first != last; ++first) { std::invoke(f, std::invoke(proj, *first)); } return {std::move(first), std::move(f)}; } template<ranges::input_range R, class Proj = std::identity, std::indirectly_unary_invocable<std::projected<ranges::iterator_t<R>, Proj>> Fun> constexpr ranges::for_each_result<ranges::borrowed_iterator_t<R>, Fun> operator()(R&& r, Fun f, Proj proj = {}) const { return (*this)(ranges::begin(r), ranges::end(r), std::move(f), std::ref(proj)); } }; inline constexpr for_each_fn for_each; ``` | ### Example The following example uses a [lambda expression](../../language/lambda "cpp/language/lambda") to increment all of the elements of a vector and then uses an overloaded `operator()` in a functor to compute their sum. Note that to compute the sum, it is recommended to use the dedicated algorithm `[std::accumulate](../accumulate "cpp/algorithm/accumulate")`. ``` #include <algorithm> #include <cassert> #include <iostream> #include <string> #include <utility> #include <vector> struct Sum { void operator()(int n) { sum += n; } int sum{0}; }; int main() { std::vector<int> nums{3, 4, 2, 8, 15, 267}; auto print = [](const auto& n) { std::cout << ' ' << n; }; namespace ranges = std::ranges; std::cout << "before:"; ranges::for_each(std::as_const(nums), print); print('\n'); ranges::for_each(nums, [](int& n){ ++n; }); // calls Sum::operator() for each number auto [i, s] = ranges::for_each(nums.begin(), nums.end(), Sum()); assert(i == nums.end()); std::cout << "after: "; ranges::for_each(nums.cbegin(), nums.cend(), print); std::cout << "\n" "sum: " << s.sum << '\n'; using pair = std::pair<int, std::string>; std::vector<pair> pairs{{1,"one"}, {2,"two"}, {3,"tree"}}; std::cout << "project the pair::first: "; ranges::for_each(pairs, print, [](const pair& p) { return p.first; }); std::cout << "\n" "project the pair::second:"; ranges::for_each(pairs, print, &pair::second); print('\n'); } ``` Output: ``` before: 3 4 2 8 15 267 after: 4 5 3 9 16 268 sum: 305 project the pair::first: 1 2 3 project the pair::second: one two tree ``` ### See also | | | | --- | --- | | [range-`for` loop](../../language/range-for "cpp/language/range-for")(C++11) | executes loop over range | | [ranges::transform](transform "cpp/algorithm/ranges/transform") (C++20) | applies a function to a range of elements (niebloid) | | [ranges::for\_each\_n](for_each_n "cpp/algorithm/ranges/for each n") (C++20) | applies a function object to the first n elements of a sequence (niebloid) | | [for\_each](../for_each "cpp/algorithm/for each") | applies a function to a range of elements (function template) | cpp std::ranges::sort std::ranges::sort ================= | Defined in header `[<algorithm>](../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | Call signature | | | | ``` template< std::random_access_iterator I, std::sentinel_for<I> S, class Comp = ranges::less, class Proj = std::identity > requires std::sortable<I, Comp, Proj> constexpr I sort( I first, S last, Comp comp = {}, Proj proj = {} ); ``` | (1) | (since C++20) | | ``` template< ranges::random_access_range R, class Comp = ranges::less, class Proj = std::identity > requires std::sortable<ranges::iterator_t<R>, Comp, Proj> constexpr ranges::borrowed_iterator_t<R> sort( R&& r, Comp comp = {}, Proj proj = {} ); ``` | (2) | (since C++20) | Sorts the elements in the range `[first, last)` in non-descending order. The order of equivalent elements is not guaranteed to be preserved. A sequence is sorted with respect to a comparator `comp` if for any iterator `it` pointing to the sequence and any non-negative integer `n` such that `it + n` is a valid iterator pointing to an element of the sequence, `[std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(comp, [std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(proj, \*(it + n)), [std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(proj, \*it))` evaluates to `false`. 1) Elements are compared using the given binary comparison function `comp`. 2) Same as (1), but uses `r` as the source range, as if using `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r)` as `first` and `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r)` as `last`. The function-like entities described on this page are *niebloids*, that is: * Explicit template argument lists cannot be specified when calling any of them. * None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl"). * When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited. In practice, they may be implemented as function objects, or with special compiler extensions. ### Parameters | | | | | --- | --- | --- | | first, last | - | iterator-sentinel defining the range to sort | | r | - | the range to sort | | comp | - | comparison to apply to the projected elements | | proj | - | projection to apply to the elements | ### Return value An iterator equal to `last`. ### Complexity \(\scriptsize \mathcal{O}(N\cdot\log{(N)})\)𝓞(N·log(N)) comparisons and projections, where `N = [ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(first, last)`. ### Possible implementation Note that typical implementations use [introsort](https://en.wikipedia.org/wiki/Introsort "enwiki:Introsort"). See also the implementation in [MSVC STL](https://github.com/microsoft/STL/blob/e745bad3b1d05b5b19ec652d68abb37865ffa454/stl/inc/algorithm#L7575-L7641) and [libstdc++](https://github.com/gcc-mirror/gcc/blob/54258e22b0846aaa6bd3265f592feb161eecda75/libstdc%2B%2B-v3/include/bits/ranges_algo.h#L1808-L1834). | | | --- | | ``` struct sort_fn { template< std::random_access_iterator I, std::sentinel_for<I> S, class Comp = ranges::less, class Proj = std::identity > requires std::sortable<I, Comp, Proj> constexpr I operator()( I first, S last, Comp comp = {}, Proj proj = {} ) const { if (first == last) return first; I last_iter = ranges::next(first, last); ranges::make_heap(first, last_iter, std::ref(comp), std::ref(proj)); ranges::sort_heap(first, last_iter, std::ref(comp), std::ref(proj)); return last_iter; } template< ranges::random_access_range R, class Comp = ranges::less, class Proj = std::identity > requires std::sortable<ranges::iterator_t<R>, Comp, Proj> constexpr ranges::borrowed_iterator_t<R> operator()( R&& r, Comp comp = {}, Proj proj = {} ) const { return (*this)(ranges::begin(r), ranges::end(r), std::move(comp), std::move(proj)); } }; inline constexpr sort_fn sort{}; ``` | ### Notes `[std::sort](../sort "cpp/algorithm/sort")` uses `[std::iter\_swap](../iter_swap "cpp/algorithm/iter swap")` to swap elements, whereas `ranges::sort` instead uses `[ranges::iter\_swap](../../iterator/ranges/iter_swap "cpp/iterator/ranges/iter swap")` (which performs ADL for `iter_swap`, unlike `[std::iter\_swap](../iter_swap "cpp/algorithm/iter swap")`). ### Example ``` #include <algorithm> #include <array> #include <functional> #include <iomanip> #include <iostream> void print(auto comment, auto const& seq, char term = ' ') { for (std::cout << comment << '\n'; auto const& elem : seq) std::cout << elem << term; std::cout << '\n'; } struct Particle { std::string name; double mass; // MeV template<class Os> friend Os& operator<< (Os& os, Particle const& p) { return os << std::left << std::setw(8) << p.name << " : " << p.mass << ' '; } }; int main() { std::array s {5, 7, 4, 2, 8, 6, 1, 9, 0, 3}; namespace ranges = std::ranges; ranges::sort(s); print("Sort using the default operator<", s); ranges::sort(s, ranges::greater()); print("Sort using a standard library compare function object", s); struct { bool operator()(int a, int b) const { return a < b; } } customLess; ranges::sort(s.begin(), s.end(), customLess); print("Sort using a custom function object", s); ranges::sort(s, [](int a, int b) { return a > b; }); print("Sort using a lambda expression", s); Particle particles[] { {"Electron", 0.511}, {"Muon", 105.66}, {"Tau", 1776.86}, {"Positron", 0.511}, {"Proton", 938.27}, {"Neutron", 939.57}, }; ranges::sort(particles, {}, &Particle::name); print("\nSort by name using a projection", particles, '\n'); ranges::sort(particles, {}, &Particle::mass); print("Sort by mass using a projection", particles, '\n'); } ``` Output: ``` Sort using the default operator< 0 1 2 3 4 5 6 7 8 9 Sort using a standard library compare function object 9 8 7 6 5 4 3 2 1 0 Sort using a custom function object 0 1 2 3 4 5 6 7 8 9 Sort using a lambda expression 9 8 7 6 5 4 3 2 1 0 Sort by name using a projection Electron : 0.511 Muon : 105.66 Neutron : 939.57 Positron : 0.511 Proton : 938.27 Tau : 1776.86 Sort by mass using a projection Electron : 0.511 Positron : 0.511 Muon : 105.66 Proton : 938.27 Neutron : 939.57 Tau : 1776.86 ``` ### See also | | | | --- | --- | | [ranges::partial\_sort](partial_sort "cpp/algorithm/ranges/partial sort") (C++20) | sorts the first N elements of a range (niebloid) | | [ranges::stable\_sort](stable_sort "cpp/algorithm/ranges/stable sort") (C++20) | sorts a range of elements while preserving order between equal elements (niebloid) | | [ranges::partition](partition "cpp/algorithm/ranges/partition") (C++20) | divides a range of elements into two groups (niebloid) | | [sort](../sort "cpp/algorithm/sort") | sorts a range into ascending order (function template) |
programming_docs
cpp std::ranges::copy_backward, std::ranges::copy_backward_result std::ranges::copy\_backward, std::ranges::copy\_backward\_result ================================================================ | Defined in header `[<algorithm>](../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | Call signature | | | | ``` template< std::bidirectional_iterator I1, std::sentinel_for<I1> S1, std::bidirectional_iterator I2 > requires std::indirectly_copyable<I1, I2> constexpr copy_backward_result<I1, I2> copy_backward( I1 first, S1 last, I2 result ); ``` | (1) | (since C++20) | | ``` template< ranges::bidirectional_range R, std::bidirectional_iterator I > requires std::indirectly_copyable<ranges::iterator_t<R>, I> constexpr copy_backward_result<ranges::borrowed_iterator_t<R>, I> copy_backward( R&& r, I result ); ``` | (2) | (since C++20) | | Helper types | | | | ``` template< class I1, class I2 > using copy_backward_result = ranges::in_out_result<I1, I2>; ``` | (3) | (since C++20) | 1) Copies the elements from the range, defined by `[first, last)`, to another range `[result - N, result)`, where `N = [ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(first, last)`. The elements are copied in reverse order (the last element is copied first), but their relative order is preserved. The behavior is undefined if `result` is within `(first, last]`. In such a case `std::[ranges::copy](http://en.cppreference.com/w/cpp/ranges-algorithm-placeholder/copy)` can be used instead. 2) Same as (1), but uses `r` as the source range, as if using `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r)` as `first`, and `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r)` as `last`. The function-like entities described on this page are *niebloids*, that is: * Explicit template argument lists cannot be specified when calling any of them. * None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl"). * When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited. In practice, they may be implemented as function objects, or with special compiler extensions. ### Parameters | | | | | --- | --- | --- | | first | - | the beginning of the range of elements to copy from | | last | - | the end of the range of elements to copy from | | r | - | the range of the elements to copy from | | result | - | the end of the destination range | ### Return value `{last, result - N}`. ### Complexity Exactly `N` assignments. ### Notes When copying overlapping ranges, `ranges::copy` is appropriate when copying to the left (beginning of the destination range is outside the source range) while `ranges::copy_backward` is appropriate when copying to the right (end of the destination range is outside the source range). ### Possible implementation | | | --- | | ``` struct copy_backward_fn { template<std::bidirectional_iterator I1, std::sentinel_for<I1> S1, std::bidirectional_iterator I2> requires std::indirectly_copyable<I1, I2> constexpr ranges::copy_backward_result<I1, I2> operator()( I1 first, S1 last, I2 result ) const { I1 last1{ ranges::next(first, std::move(last)) }; for (I1 i{ last1 }; i != first; *--result = *--i); return { std::move(last1), std::move(result) }; } template<ranges::bidirectional_range R, std::bidirectional_iterator I> requires std::indirectly_copyable<ranges::iterator_t<R>, I> constexpr ranges::copy_backward_result<ranges::borrowed_iterator_t<R>, I> operator()( R&& r, I result ) const { return (*this)(ranges::begin(r), ranges::end(r), std::move(result)); } }; inline constexpr copy_backward_fn copy_backward{}; ``` | ### Example ``` #include <algorithm> #include <iostream> #include <ranges> #include <string_view> #include <vector> void print(std::string_view rem, std::ranges::forward_range auto const& r) { for (std::cout << rem << ": "; auto const& elem : r) std::cout << elem << ' '; std::cout << '\n'; } int main() { const auto src = {1, 2, 3, 4}; print("src", src); std::vector<int> dst (src.size() + 2); std::ranges::copy_backward(src, dst.end()); print("dst", dst); std::ranges::fill(dst, 0); const auto [in, out] = std::ranges::copy_backward(src.begin(), src.end() - 2, dst.end()); print("dst", dst); std::cout << "(in - src.begin) == " << std::distance(src.begin(), in) << '\n' << "(out - dst.begin) == " << std::distance(dst.begin(), out) << '\n'; } ``` Output: ``` src: 1 2 3 4 dst: 0 0 1 2 3 4 dst: 0 0 0 0 1 2 (in - src.begin) == 2 (out - dst.begin) == 4 ``` ### See also | | | | --- | --- | | [ranges::copyranges::copy\_if](copy "cpp/algorithm/ranges/copy") (C++20)(C++20) | copies a range of elements to a new location (niebloid) | | [ranges::copy\_n](copy_n "cpp/algorithm/ranges/copy n") (C++20) | copies a number of elements to a new location (niebloid) | | [ranges::remove\_copyranges::remove\_copy\_if](remove_copy "cpp/algorithm/ranges/remove copy") (C++20)(C++20) | copies a range of elements omitting those that satisfy specific criteria (niebloid) | | [ranges::replace\_copyranges::replace\_copy\_if](replace_copy "cpp/algorithm/ranges/replace copy") (C++20)(C++20) | copies a range, replacing elements satisfying specific criteria with another value (niebloid) | | [ranges::reverse\_copy](reverse_copy "cpp/algorithm/ranges/reverse copy") (C++20) | creates a copy of a range that is reversed (niebloid) | | [ranges::rotate\_copy](rotate_copy "cpp/algorithm/ranges/rotate copy") (C++20) | copies and rotate a range of elements (niebloid) | | [ranges::unique\_copy](unique_copy "cpp/algorithm/ranges/unique copy") (C++20) | creates a copy of some range of elements that contains no consecutive duplicates (niebloid) | | [ranges::move](move "cpp/algorithm/ranges/move") (C++20) | moves a range of elements to a new location (niebloid) | | [ranges::move\_backward](move_backward "cpp/algorithm/ranges/move backward") (C++20) | moves a range of elements to a new location in backwards order (niebloid) | | [copy\_backward](../copy_backward "cpp/algorithm/copy backward") | copies a range of elements in backwards order (function template) | cpp std::ranges::fill_n std::ranges::fill\_n ==================== | Defined in header `[<algorithm>](../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | Call signature | | | | ``` template< class T, std::output_iterator<const T&> O > constexpr O fill_n( O first, std::iter_difference_t<O> n, const T& value ); ``` | | (since C++20) | Assigns the given `value` to all elements in the range `[first, first + n)`. The function-like entities described on this page are *niebloids*, that is: * Explicit template argument lists cannot be specified when calling any of them. * None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl"). * When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited. In practice, they may be implemented as function objects, or with special compiler extensions. ### Parameters | | | | | --- | --- | --- | | first | - | the beginning of the range of elements to modify | | n | - | number of elements to modify | | value | - | the value to be assigned | ### Return value An output iterator that compares equal to `first + n`. ### Complexity Exactly `n` assignments. ### Possible implementation | | | --- | | ``` struct fill_n_fn { template<class T, std::output_iterator<const T&> O> constexpr O operator()(O first, std::iter_difference_t<O> n, const T& value) const { for (std::iter_difference_t<O> i{}; i != n; *first = value, ++first, ++i); return first; } }; inline constexpr fill_n_fn fill_n{}; ``` | ### Example ``` #include <algorithm> #include <iostream> #include <string> #include <vector> auto print(const auto& v) { for (const auto& elem : v) { std::cout << elem << " "; } std::cout << '\n'; } int main() { constexpr auto n{8}; std::vector<std::string> v(n, "░░"); print(v); std::ranges::fill_n(v.begin(), n, "▓▓"); print(v); } ``` Output: ``` ░░ ░░ ░░ ░░ ░░ ░░ ░░ ░░ ▓▓ ▓▓ ▓▓ ▓▓ ▓▓ ▓▓ ▓▓ ▓▓ ``` ### See also | | | | --- | --- | | [ranges::fill](fill "cpp/algorithm/ranges/fill") (C++20) | assigns a range of elements a certain value (niebloid) | | [ranges::copy\_n](copy_n "cpp/algorithm/ranges/copy n") (C++20) | copies a number of elements to a new location (niebloid) | | [ranges::generate](generate "cpp/algorithm/ranges/generate") (C++20) | saves the result of a function in a range (niebloid) | | [ranges::transform](transform "cpp/algorithm/ranges/transform") (C++20) | applies a function to a range of elements (niebloid) | | [fill\_n](../fill_n "cpp/algorithm/fill n") | copy-assigns the given value to N elements in a range (function template) | cpp std::ranges::contains, std::ranges::contains_subrange std::ranges::contains, std::ranges::contains\_subrange ====================================================== | Defined in header `[<algorithm>](../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | Call signature | | | | ``` template< std::input_iterator I, std::sentinel_for<I> S, class T, class Proj = std::identity > requires std::indirect_binary_predicate<ranges::equal_to, std::projected<I, Proj>, const T*> constexpr bool contains( I first, S last, const T& value, Proj proj = {} ); ``` | (1) | (since C++23) | | ``` template< ranges::input_range R, class T, class Proj = std::identity > requires std::indirect_binary_predicate<ranges::equal_to, std::projected<ranges::iterator_t<R>, Proj>, const T*> constexpr bool contains( R&& r, const T& value, Proj proj = {} ); ``` | (2) | (since C++23) | | ``` template< std::forward_iterator I1, std::sentinel_for<I1> S1, std::forward_iterator I2, std::sentinel_for<I2> S2, class Pred = ranges::equal_to, class Proj1 = std::identity, class Proj2 = std::identity > requires std::indirectly_comparable<I1, I2, Pred, Proj1, Proj2> constexpr bool contains_subrange( I1 first1, S1 last1, I2 first2, S2 last2, Pred pred = {}, Proj1 proj1 = {}, Proj2 proj2 = {} ); ``` | (3) | (since C++23) | | ``` template< ranges::forward_range R1, ranges::forward_range R2, class Pred = ranges::equal_to, class Proj1 = std::identity, class Proj2 = std::identity > requires std::indirectly_comparable<ranges::iterator_t<R1>, ranges::iterator_t<R2>, Pred, Proj1, Proj2> constexpr bool contains_subrange( R1&& r1, R2&& r2, Pred pred = {}, Proj1 proj1 = {}, Proj2 proj2 = {} ); ``` | (4) | (since C++23) | 1) Search-based algorithm that checks whether or not a given range contains a value with iterator-sentinel pairs. 2) Same as (1) but uses `r` as the source range, as if using `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r)` as `first` and `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r)` as `last`. 3) Search-based algorithm that checks whether or not a given range is a subrange of another range with iterator-sentinel pairs. 4) Same as (3) but uses `r1` as the first source range and `r2` as the second source range, as if using `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r1)` as `first1`, `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r1)` as `last1`, `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r2)` as `first2`, and `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r2)` as `last2`. The function-like entities described on this page are *niebloids*, that is: * Explicit template argument lists cannot be specified when calling any of them. * None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl"). * When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited. In practice, they may be implemented as function objects, or with special compiler extensions. ### Parameters | | | | | --- | --- | --- | | first, last | - | the range of elements to examine | | r | - | the range of the elements to examine | | value | - | value to compare the elements to | | pred | - | predicate to apply to the projected elements | | proj | - | projection to apply to the elements | ### Return value 1-2) : `[ranges::find](http://en.cppreference.com/w/cpp/algorithm/ranges/find)(std::move(first), last, value, proj) != last` 3-4) : `first2 == last2 || ![ranges::search](http://en.cppreference.com/w/cpp/algorithm/ranges/search)(first1, last1, first2, last2, pred, proj1, proj2).empty()` ### Complexity At most `last` - `first` applications of the predicate and projection. ### Notes Up until C++20, we've had to write `std::[ranges::find](http://en.cppreference.com/w/cpp/algorithm/ranges/find)(r, value) != std::[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r)` to determine if a single value is inside a range. And to check if a range contains a subrange of interest, we use `not std::[ranges::search](http://en.cppreference.com/w/cpp/algorithm/ranges/search)(haystack, needle).empty()`. While this is accurate, it isn't necessarily convenient, and it hardly expresses intent (especially in the latter case). Being able to say `std::ranges::contains(r, value)` addresses both of these points. `ranges::contains_subrange`, same as `[ranges::search](search "cpp/algorithm/ranges/search")`, but as opposed to `[std::search](../search "cpp/algorithm/search")`, provides no access to [Searchers](https://en.cppreference.com/mwiki/index.php?title=cpp/named_req/Searcher&action=edit&redlink=1 "cpp/named req/Searcher (page does not exist)") (such as [Boyer-Moore](../../utility/functional#Searchers "cpp/utility/functional")). | [Feature-test](../../utility/feature_test "cpp/utility/feature test") macro | | --- | | [`__cpp_lib_ranges_contains`](../../feature_test#Library_features "cpp/feature test") | ### Possible implementation | First version | | --- | | ``` struct __contains_fn { template< std::input_iterator I, std::sentinel_for<I> S, class T, class Proj = std::identity > requires std::indirect_binary_predicate<ranges::equal_to, std::projected<I, Proj>, const T*> constexpr bool operator()(I first, S last, const T& value, Proj proj = {}) const { return ranges::find(std::move(first), last, value, proj) != last; } template< ranges::input_range R, class T, class Proj = std::identity > requires std::indirect_binary_predicate<ranges::equal_to, std::projected<ranges::iterator_t<R>, Proj>, const T*> constexpr bool operator()(R&& r, const T& value, Proj proj = {}) const { return (*this)(ranges::begin(r), ranges::end(r), std::move(value), proj); } }; inline constexpr __contains_fn contains {}; ``` | | Second version | | ``` struct __contains_subrange_fn { template< std::forward_iterator I1, std::sentinel_for<I1> S1, std::forward_iterator I2, std::sentinel_for<I2> S2, class Pred = ranges::equal_to, class Proj1 = std::identity, class Proj2 = std::identity > requires std::indirectly_comparable<I1, I2, Pred, Proj1, Proj2> constexpr bool operator()(I1 first1, S1 last1, I2 first2, S2 last2, Pred pred = {}, Proj1 proj1 = {}, Proj2 proj2 = {}) const { return (first2 == last2) || !ranges::search(first1, last1, first2, last2, pred, proj1, proj2).empty(); } template< ranges::forward_range R1, ranges::forward_range R2, class Pred = ranges::equal_to, class Proj1 = std::identity, class Proj2 = std::identity > requires std::indirectly_comparable<ranges::iterator_t<R1>, ranges::iterator_t<R2>, Pred, Proj1, Proj2> constexpr bool operator()(R1&& r1, R2&& r2, Pred pred = {}, Proj1 proj1 = {}, Proj2 proj2 = {}) const { return (*this)(ranges::begin(r1), ranges::end(r1), ranges::begin(r2), ranges::end(r2), std::move(pred), std::move(proj1), std::move(proj2)); } }; inline constexpr __contains_subrange_fn contains_subrange {}; ``` | ### Example ``` #include <algorithm> #include <array> int main() { constexpr auto haystack = std::array { 3, 1, 4, 1, 5 }; constexpr auto needle = std::array { 1, 4, 1 }; constexpr auto bodkin = std::array { 2, 5, 2 }; auto increment = [](int x) { return ++x; }; auto decrement = [](int x) { return --x; }; static_assert( std::ranges::contains(haystack, 4) and not std::ranges::contains(haystack, 6) and std::ranges::contains_subrange(haystack, needle) and not std::ranges::contains_subrange(haystack, bodkin) and std::ranges::contains(haystack, 6, increment) and not std::ranges::contains(haystack, 1, increment) and std::ranges::contains_subrange(haystack, bodkin, {}, increment) and not std::ranges::contains_subrange(haystack, bodkin, {}, decrement) and std::ranges::contains_subrange(haystack, bodkin, {}, {}, decrement) ); } ``` ### See also | | | | --- | --- | | [ranges::findranges::find\_ifranges::find\_if\_not](find "cpp/algorithm/ranges/find") (C++20)(C++20)(C++20) | finds the first element satisfying specific criteria (niebloid) | | [ranges::search](search "cpp/algorithm/ranges/search") (C++20) | searches for a range of elements (niebloid) | | [ranges::binary\_search](binary_search "cpp/algorithm/ranges/binary search") (C++20) | determines if an element exists in a partially-ordered range (niebloid) | | [ranges::all\_ofranges::any\_ofranges::none\_of](all_any_none_of "cpp/algorithm/ranges/all any none of") (C++20)(C++20)(C++20) | checks if a predicate is `true` for all, any or none of the elements in a range (niebloid) | cpp std::ranges::partition_point std::ranges::partition\_point ============================= | Defined in header `[<algorithm>](../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | Call signature | | | | ``` template< std::forward_iterator I, std::sentinel_for<I> S, class Proj = std::identity, std::indirect_unary_predicate<std::projected<I, Proj>> Pred > constexpr I partition_point( I first, S last, Pred pred, Proj proj = {} ); ``` | (1) | (since C++20) | | ``` template< ranges::forward_range R, class Proj = std::identity, std::indirect_unary_predicate< std::projected<ranges::iterator_t<R>, Proj>> Pred > constexpr ranges::borrowed_iterator_t<R> partition_point( R&& r, Pred pred, Proj proj = {} ); ``` | (2) | (since C++20) | Examines the partitioned (as if by `[ranges::partition](partition "cpp/algorithm/ranges/partition")`) range `[first, last)` or `r` and locates the end of the first partition, that is, the projected element that does not satisfy `pred` or `last` if all projected elements satisfy `pred`. The function-like entities described on this page are *niebloids*, that is: * Explicit template argument lists cannot be specified when calling any of them. * None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl"). * When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited. In practice, they may be implemented as function objects, or with special compiler extensions. ### Parameters | | | | | --- | --- | --- | | first, last | - | iterator-sentinel defining the partially-ordered range to examine | | r | - | the partially-ordered range to examine | | pred | - | predicate to apply to the projected elements | | proj | - | projection to apply to the elements | ### Return value The iterator past the end of the first partition within `[first, last)` or the iterator equal to `last` if all projected elements satisfy `pred`. ### Complexity Given `N = [ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(first, last)`, performs O(log N) applications of the predicate `pred` and projection `proj`. However, if sentinels don't model `[std::sized\_sentinel\_for](http://en.cppreference.com/w/cpp/iterator/sized_sentinel_for)<I>`, the number of iterator increments is O(N). ### Notes This algorithm is a more general form of `ranges::lower_bound`, which can be expressed in terms of `ranges::partition_point` with the predicate `[&](auto const& e) { return [std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(pred, e, value); });`. ### Example ``` #include <algorithm> #include <array> #include <iostream> #include <iterator> auto print_seq = [](auto rem, auto first, auto last) { for (std::cout << rem; first != last; std::cout << *first++ << ' ') {} std::cout << '\n'; }; int main() { std::array v = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; auto is_even = [](int i){ return i % 2 == 0; }; std::ranges::partition(v, is_even); print_seq("After partitioning, v: ", v.cbegin(), v.cend()); const auto pp = std::ranges::partition_point(v, is_even); const auto i = std::ranges::distance(v.cbegin(), pp); std::cout << "Partition point is at " << i << "; v[" << i << "] = " << *pp << '\n'; print_seq("First partition (all even elements): ", v.cbegin(), pp); print_seq("Second partition (all odd elements): ", pp, v.cend()); } ``` Possible output: ``` After partitioning, v: 2 4 6 8 5 3 7 1 9 Partition point is at 4; v[4] = 5 First partition (all even elements): 2 4 6 8 Second partition (all odd elements): 5 3 7 1 9 ``` ### See also | | | | --- | --- | | [ranges::is\_sorted](is_sorted "cpp/algorithm/ranges/is sorted") (C++20) | checks whether a range is sorted into ascending order (niebloid) | | [ranges::lower\_bound](lower_bound "cpp/algorithm/ranges/lower bound") (C++20) | returns an iterator to the first element *not less* than the given value (niebloid) | | [partition\_point](../partition_point "cpp/algorithm/partition point") (C++11) | locates the partition point of a partitioned range (function template) |
programming_docs
cpp std::ranges::copy_n, std::ranges::copy_n_result std::ranges::copy\_n, std::ranges::copy\_n\_result ================================================== | Defined in header `[<algorithm>](../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | Call signature | | | | ``` template< std::input_iterator I, std::weakly_incrementable O > requires std::indirectly_copyable<I, O> constexpr copy_n_result<I, O> copy_n( I first, std::iter_difference_t<I> n, O result ); ``` | (1) | (since C++20) | | Helper type | | | | ``` template< class I, class O > using copy_n_result = ranges::in_out_result<I, O>; ``` | (2) | (since C++20) | 1) Copies exactly `n` values from the range beginning at `first` to the range beginning at `result` by performing `*(result + i) = *(first + i)` for each integer in `[0, n)`. The behavior is undefined if `result` is within the range `[first, first + n)` (`[ranges::copy\_backward](copy_backward "cpp/algorithm/ranges/copy backward")` might be used instead in this case). The function-like entities described on this page are *niebloids*, that is: * Explicit template argument lists cannot be specified when calling any of them. * None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl"). * When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited. In practice, they may be implemented as function objects, or with special compiler extensions. ### Parameters | | | | | --- | --- | --- | | first | - | the beginning of the range of elements to copy from | | n | - | number of the elements to copy | | result | - | the beginning of the destination range | ### Return value `ranges::copy_n_result{first + n, result + n}` or more formally, a value of type `[ranges::in\_out\_result](return_types/in_out_result "cpp/algorithm/ranges/return types/in out result")` that contains an `[std::input\_iterator](../../iterator/input_iterator "cpp/iterator/input iterator")` iterator equals to `[ranges::next](http://en.cppreference.com/w/cpp/iterator/ranges/next)(first, n)` and a `[std::weakly\_incrementable](../../iterator/weakly_incrementable "cpp/iterator/weakly incrementable")` iterator equals to `[ranges::next](http://en.cppreference.com/w/cpp/iterator/ranges/next)(result, n)`. ### Complexity Exactly `n` assignments. ### Notes In practice, implementations of `std::ranges::copy_n` may avoid multiple assignments and use bulk copy functions such as `[std::memmove](../../string/byte/memmove "cpp/string/byte/memmove")` if the value type is [TriviallyCopyable](../../named_req/triviallycopyable "cpp/named req/TriviallyCopyable") and the iterator types satisfy [`contiguous_iterator`](../../iterator/contiguous_iterator "cpp/iterator/contiguous iterator"). Alternativelly, such copy acceleration can be injected during an optimization phase of a compiler. When copying overlapping ranges, `std::ranges::copy_n` is appropriate when copying to the left (beginning of the destination range is outside the source range) while `std::ranges::copy_backward` is appropriate when copying to the right (end of the destination range is outside the source range). ### Possible implementation | | | --- | | ``` struct copy_n_fn { template<std::input_iterator I, std::weakly_incrementable O> requires std::indirectly_copyable<I, O> constexpr ranges::copy_n_result<I, O> operator()(I first, std::iter_difference_t<I> n, O result) const { for (std::iter_difference_t<I> i{}; i != n; ++i, ++first, ++result) *result = *first; return {std::move(first), std::move(result)}; } }; inline constexpr copy_n_fn copy_n{}; ``` | ### Example ``` #include <algorithm> #include <iterator> #include <iostream> #include <iomanip> #include <string> #include <string_view> int main() { const std::string_view in {"ABCDEFGH"}; std::string out; std::ranges::copy_n(in.begin(), 4, std::back_inserter(out)); std::cout << std::quoted(out) << '\n'; out = "abcdefgh"; const auto res = std::ranges::copy_n(in.begin(), 5, out.begin()); std::cout << "*(res.in): '" << *(res.in) << "', distance: " << std::distance(std::begin(in), res.in) << '\n' << "*(res.out): '" << *(res.out) << "', distance: " << std::distance(std::begin(out), res.out) << '\n'; } ``` Output: ``` "ABCD" *(res.in): 'F', distance: 5 *(res.out): 'f', distance: 5 ``` ### See also | | | | --- | --- | | [ranges::copyranges::copy\_if](copy "cpp/algorithm/ranges/copy") (C++20)(C++20) | copies a range of elements to a new location (niebloid) | | [ranges::copy\_backward](copy_backward "cpp/algorithm/ranges/copy backward") (C++20) | copies a range of elements in backwards order (niebloid) | | [ranges::remove\_copyranges::remove\_copy\_if](remove_copy "cpp/algorithm/ranges/remove copy") (C++20)(C++20) | copies a range of elements omitting those that satisfy specific criteria (niebloid) | | [ranges::replace\_copyranges::replace\_copy\_if](replace_copy "cpp/algorithm/ranges/replace copy") (C++20)(C++20) | copies a range, replacing elements satisfying specific criteria with another value (niebloid) | | [ranges::reverse\_copy](reverse_copy "cpp/algorithm/ranges/reverse copy") (C++20) | creates a copy of a range that is reversed (niebloid) | | [ranges::rotate\_copy](rotate_copy "cpp/algorithm/ranges/rotate copy") (C++20) | copies and rotate a range of elements (niebloid) | | [ranges::unique\_copy](unique_copy "cpp/algorithm/ranges/unique copy") (C++20) | creates a copy of some range of elements that contains no consecutive duplicates (niebloid) | | [ranges::move](move "cpp/algorithm/ranges/move") (C++20) | moves a range of elements to a new location (niebloid) | | [ranges::move\_backward](move_backward "cpp/algorithm/ranges/move backward") (C++20) | moves a range of elements to a new location in backwards order (niebloid) | | [copy\_n](../copy_n "cpp/algorithm/copy n") (C++11) | copies a number of elements to a new location (function template) | cpp std::ranges::nth_element std::ranges::nth\_element ========================= | Defined in header `[<algorithm>](../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | Call signature | | | | ``` template< std::random_access_iterator I, std::sentinel_for<I> S, class Comp = ranges::less, class Proj = std::identity > requires std::sortable<I, Comp, Proj> constexpr I nth_element( I first, I nth, S last, Comp comp = {}, Proj proj = {} ); ``` | (1) | (since C++20) | | ``` template< ranges::random_access_range R, class Comp = ranges::less, class Proj = std::identity > requires std::sortable<iterator_t<R>, Comp, Proj> constexpr ranges::borrowed_iterator_t<R> nth_element( R&& r, iterator_t<R> nth, Comp comp = {}, Proj proj = {} ); ``` | (2) | (since C++20) | Reorders the elements in `[first, last)` such that: * The element pointed at by `nth` is changed to whatever element would occur in that position if `[first, last)` were sorted with respect to `comp` and `proj`. * All of the elements before this new `nth` element are *less than or equal to* the elements after the new `nth` element. That is, for every iterator *i*, *j* in the ranges `[first, nth)`, `[nth, last)` respectively, the expression `[std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(comp, [std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(proj, \*j), [std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(proj, \*i))` evaluates to `false`. * If `nth == last` then the function has no effect. 1) Elements are compared using the given binary comparison function object `comp` and projection object `proj`. 2) Same as (1), but uses `r` as the range, as if using `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r)` as `first` and `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r)` as `last`. The function-like entities described on this page are *niebloids*, that is: * Explicit template argument lists cannot be specified when calling any of them. * None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl"). * When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited. In practice, they may be implemented as function objects, or with special compiler extensions. ### Parameters | | | | | --- | --- | --- | | first, last | - | the range of elements to reorder | | r | - | the range of elements to reorder | | nth | - | the iterator defining the partition point | | comp | - | comparator used to compare the projected elements | | proj | - | projection to apply to the elements | ### Return value 1) An iterator equal to `last`. 2) Same as (1) if `r` is an lvalue or of a [`borrowed_range`](../../ranges/borrowed_range "cpp/ranges/borrowed range") type. Otherwise returns `[std::ranges::dangling](../../ranges/dangling "cpp/ranges/dangling")`. ### Complexity Linear in `[ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(first, last)` on average. ### Notes The algorithm used is typically [introselect](https://en.wikipedia.org/wiki/Introselect "enwiki:Introselect") although other [selection algorithms](https://en.wikipedia.org/wiki/Selection_algorithm "enwiki:Selection algorithm") with suitable average-case complexity are allowed. ### Possible implementation See also the implementation in [MSVC STL](https://github.com/microsoft/STL/blob/e745bad3b1d05b5b19ec652d68abb37865ffa454/stl/inc/algorithm#L8429-L8499) and [libstdc++](https://github.com/gcc-mirror/gcc/blob/54258e22b0846aaa6bd3265f592feb161eecda75/libstdc%2B%2B-v3/include/bits/ranges_algo.h#L2052-L2080). ### Example ``` #include <algorithm> #include <array> #include <functional> #include <iostream> #include <ranges> #include <string_view> void print(std::string_view rem, std::ranges::input_range auto const& a) { for (std::cout << rem; const auto e : a) std::cout << e << ' '; std::cout << "\n"; } int main() { std::array v{5, 6, 4, 3, 2, 6, 7, 9, 3}; print("Before nth_element: ", v); std::ranges::nth_element(v, v.begin() + v.size()/2); print("After nth_element: ", v); std::cout << "The median is: " << v[v.size()/2] << '\n'; std::ranges::nth_element(v, v.begin() + 1, std::greater<int>()); print("After nth_element: ", v); std::cout << "The second largest element is: " << v[1] << '\n'; std::cout << "The largest element is: " << v[0] << "\n\n"; using namespace std::literals; std::array names { "Diva"sv, "Cornelius"sv, "Munro"sv, "Rhod"sv, "Zorg"sv, "Korben"sv, "Bender"sv, "Leeloo"sv, }; print("Before nth_element: ", names); auto fifth_element {std::ranges::next(names.begin(), 4)}; std::ranges::nth_element(names, fifth_element); print("After nth_element: ", names); std::cout << "The 5th element is: " << *fifth_element << '\n'; } ``` Output: ``` Before nth_element: 5 6 4 3 2 6 7 9 3 After nth_element: 2 3 3 4 5 6 6 7 9 The median is: 5 After nth_element: 9 7 6 6 5 4 3 3 2 The second largest element is: 7 The largest element is: 9 Before nth_element: Diva Cornelius Munro Rhod Zorg Korben Bender Leeloo After nth_element: Diva Cornelius Bender Korben Leeloo Rhod Munro Zorg The 5th element is: Leeloo ``` ### See also | | | | --- | --- | | [ranges::max\_element](max_element "cpp/algorithm/ranges/max element") (C++20) | returns the largest element in a range (niebloid) | | [ranges::min\_element](min_element "cpp/algorithm/ranges/min element") (C++20) | returns the smallest element in a range (niebloid) | | [ranges::partition](partition "cpp/algorithm/ranges/partition") (C++20) | divides a range of elements into two groups (niebloid) | | [ranges::partial\_sort](partial_sort "cpp/algorithm/ranges/partial sort") (C++20) | sorts the first N elements of a range (niebloid) | | [nth\_element](../nth_element "cpp/algorithm/nth element") | partially sorts the given range making sure that it is partitioned by the given element (function template) | cpp std::ranges::fill std::ranges::fill ================= | Defined in header `[<algorithm>](../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | Call signature | | | | ``` template< class T, std::output_iterator<const T&> O, std::sentinel_for<O> S > constexpr O fill( O first, S last, const T& value ); ``` | (1) | (since C++20) | | ``` template< class T, ranges::output_range<const T&> R > constexpr ranges::borrowed_iterator_t<R> fill( R&& r, const T& value ); ``` | (2) | (since C++20) | 1) Assigns the given `value` to the elements in the range `[first, last)`. 2) Same as (1), but uses `r` as the source range, as if using `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r)` as `first` and `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r)` as `last`. The function-like entities described on this page are *niebloids*, that is: * Explicit template argument lists cannot be specified when calling any of them. * None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl"). * When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited. In practice, they may be implemented as function objects, or with special compiler extensions. ### Parameters | | | | | --- | --- | --- | | first, last | - | the range of elements to modify | | r | - | the range of elements to modify | | value | - | the value to be assigned | ### Return value An output iterator that compares equal to `last`. ### Complexity Exactly `last - first` assignments. ### Possible implementation | | | --- | | ``` struct fill_fn { template< class T, std::output_iterator<const T&> O, std::sentinel_for<O> S > constexpr O operator()( O first, S last, const T& value ) const { while (first != last) { *first++ = value; } return first; } template< class T, ranges::output_range<const T&> R > constexpr ranges::borrowed_iterator_t<R> operator()( R&& r, const T& value ) const { return (*this)(ranges::begin(r), ranges::end(r), value); } }; inline constexpr fill_fn fill; ``` | ### Example The following code uses `ranges::fill()` to set all of the elements of a `vector` of `int`s first to -1, then to 10. ``` #include <algorithm> #include <vector> #include <iostream> int main() { std::vector<int> v{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; namespace ranges = std::ranges; ranges::fill(v.begin(), v.end(), -1); for (auto elem : v) { std::cout << elem << " "; } std::cout << "\n"; ranges::fill(v, 10); for (auto elem : v) { std::cout << elem << " "; } std::cout << "\n"; } ``` Output: ``` -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 10 10 10 10 10 10 10 10 10 10 ``` ### See also | | | | --- | --- | | [ranges::fill\_n](fill_n "cpp/algorithm/ranges/fill n") (C++20) | assigns a value to a number of elements (niebloid) | | [ranges::copyranges::copy\_if](copy "cpp/algorithm/ranges/copy") (C++20)(C++20) | copies a range of elements to a new location (niebloid) | | [ranges::generate](generate "cpp/algorithm/ranges/generate") (C++20) | saves the result of a function in a range (niebloid) | | [ranges::transform](transform "cpp/algorithm/ranges/transform") (C++20) | applies a function to a range of elements (niebloid) | | [fill](../fill "cpp/algorithm/fill") | copy-assigns the given value to every element in a range (function template) | cpp std::ranges::swap_ranges, std::ranges::swap_ranges_result std::ranges::swap\_ranges, std::ranges::swap\_ranges\_result ============================================================ | Defined in header `[<algorithm>](../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | Call signature | | | | ``` template< std::input_iterator I1, std::sentinel_for<I1> S1, std::input_iterator I2, std::sentinel_for<I2> S2 > requires std::indirectly_swappable<I1, I2> constexpr swap_ranges_result<I1, I2> swap_ranges( I1 first1, S1 last1, I2 first2, S2 last2 ); ``` | (1) | (since C++20) | | ``` template< ranges::input_range R1, ranges::input_range R2 > requires std::indirectly_swappable<ranges::iterator_t<R1>, ranges::iterator_t<R2>> constexpr swap_ranges_result<ranges::borrowed_iterator_t<R1>, ranges::borrowed_iterator_t<R2>> swap_ranges( R1&& r1, R2&& r2 ); ``` | (2) | (since C++20) | | Helper types | | | | ``` template< class I1, class I2 > using swap_ranges_result = ranges::in_in_result<I1, I2>; ``` | (3) | (since C++20) | 1) Exchanges elements between first range `[first1, first1 + M)` and second range `[first2, first2 + M)` via `[ranges::iter\_swap](http://en.cppreference.com/w/cpp/iterator/ranges/iter_swap)(first1 + i, first2 + i)`, where `M = [ranges::min](http://en.cppreference.com/w/cpp/algorithm/ranges/min)([ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(first1, last1), [ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(first2, last2))`. The ranges `[first1, last1)` and `[first2, last2)` must not overlap. 2) Same as (1), but uses `r1` as the first range and `r2` as the second range, as if using `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r1)` as `first1`, `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r1)` as `last1`, `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r2)` as `first2`, and `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r2)` as `last2`. The function-like entities described on this page are *niebloids*, that is: * Explicit template argument lists cannot be specified when calling any of them. * None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl"). * When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited. In practice, they may be implemented as function objects, or with special compiler extensions. ### Parameters | | | | | --- | --- | --- | | first1, last1 | - | the first range of elements to swap | | first2, last2 | - | the second range of elements to swap | | r1 | - | the first range of elements to swap | | r2 | - | the second range of elements to swap. | ### Return value `{first1 + M, first2 + M}`. ### Complexity Exactly `M` swaps. ### Notes Implementations (e.g. [MSVC STL](https://github.com/microsoft/STL/blob/main/stl/src/vector_algorithms.cpp)) may enable vectorization when the iterator type models [`contiguous_iterator`](../../iterator/contiguous_iterator "cpp/iterator/contiguous iterator") and swapping its value type calls neither non-trivial special member function nor [ADL](../../language/adl "cpp/language/adl")-found `swap`. ### Possible implementation | | | --- | | ``` struct swap_ranges_fn { template<std::input_iterator I1, std::sentinel_for<I1> S1, std::input_iterator I2, std::sentinel_for<I2> S2> requires std::indirectly_swappable<I1, I2> constexpr ranges::swap_ranges_result<I1, I2> operator() ( I1 first1, S1 last1, I2 first2, S2 last2 ) const { for (; !(first1 == last1 or first2 == last2); ++first1, ++first2) ranges::iter_swap(first1, first2); return {std::move(first1), std::move(first2)}; } template<ranges::input_range R1, ranges::input_range R2> requires std::indirectly_swappable<ranges::iterator_t<R1>, ranges::iterator_t<R2>> constexpr ranges::swap_ranges_result<ranges::borrowed_iterator_t<R1>, ranges::borrowed_iterator_t<R2>> operator() ( R1&& r1, R2&& r2 ) const { return (*this)(ranges::begin(r1), ranges::end(r1), ranges::begin(r2), ranges::end(r2)); } }; inline constexpr swap_ranges_fn swap_ranges{}; ``` | ### Example ``` #include <algorithm> #include <iostream> #include <list> #include <string_view> #include <vector> auto print(std::string_view name, auto const& seq, std::string_view term = "\n") { std::cout << name << " : "; for (const auto& elem : seq) std::cout << elem << ' '; std::cout << term; } int main() { std::vector<char> p {'A', 'B', 'C', 'D', 'E'}; std::list<char> q {'1', '2', '3', '4', '5', '6'}; print("p", p); print("q", q, "\n\n"); // swap p[0, 2) and q[1, 3): std::ranges::swap_ranges(p.begin(), p.begin() + 4, std::ranges::next(q.begin(), 1), std::ranges::next(q.begin(), 3)); print("p", p); print("q", q, "\n\n"); // swap p[0, 5) and q[0, 5): std::ranges::swap_ranges(p, q); print("p", p); print("q", q); } ``` Output: ``` p : A B C D E q : 1 2 3 4 5 6 p : 2 3 C D E q : 1 A B 4 5 6 p : 1 A B 4 5 q : 2 3 C D E 6 ``` ### See also | | | | --- | --- | | [iter\_swap](../../iterator/ranges/iter_swap "cpp/iterator/ranges/iter swap") (C++20) | swaps the values referenced by two dereferenceable objects (customization point object) | | [ranges::swap](../../utility/ranges/swap "cpp/utility/ranges/swap") (C++20) | swaps the values of two objects (customization point object) | | [swap\_ranges](../swap_ranges "cpp/algorithm/swap ranges") | swaps two ranges of elements (function template) | | [iter\_swap](../iter_swap "cpp/algorithm/iter swap") | swaps the elements pointed to by two iterators (function template) | | [swap](../swap "cpp/algorithm/swap") | swaps the values of two objects (function template) |
programming_docs
cpp std::ranges::mismatch, std::ranges::mismatch_result std::ranges::mismatch, std::ranges::mismatch\_result ==================================================== | Defined in header `[<algorithm>](../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | Call signature | | | | ``` template< std::input_iterator I1, std::sentinel_for<I1> S1, std::input_iterator I2, std::sentinel_for<I2> S2, class Pred = ranges::equal_to, class Proj1 = std::identity, class Proj2 = std::identity > requires std::indirectly_comparable<I1, I2, Pred, Proj1, Proj2> constexpr mismatch_result<I1, I2> mismatch( I1 first1, S1 last1, I2 first2, S2 last2, Pred pred = {}, Proj1 proj1 = {}, Proj2 proj2 = {} ); ``` | (1) | (since C++20) | | ``` template< ranges::input_range R1, ranges::input_range R2, class Pred = ranges::equal_to, class Proj1 = std::identity, class Proj2 = std::identity > requires std::indirectly_comparable< ranges::iterator_t<R1>, ranges::iterator_t<R2>, Pred, Proj1, Proj2> constexpr mismatch_result<ranges::borrowed_iterator_t<R1>, ranges::borrowed_iterator_t<R2>> mismatch( R1&& r1, R2&& r2, Pred pred = {}, Proj1 proj1 = {}, Proj2 proj2 = {} ); ``` | (2) | (since C++20) | | Helper types | | | | ``` template<class I1, class I2> using mismatch_result = ranges::in_in_result<I1, I2>; ``` | (3) | (since C++20) | Returns the first mismatching pair of projected elements from two ranges: one defined by `[first1, last1)` or `r1` and another defined by `[first2,last2)` or `r2`. 1) Elements are compared using the given binary predicate `p`. 2) Same as (1), but uses `r` as the source range, as if using `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r)` as `first` and `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r)` as `last`. The function-like entities described on this page are *niebloids*, that is: * Explicit template argument lists cannot be specified when calling any of them. * None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl"). * When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited. In practice, they may be implemented as function objects, or with special compiler extensions. ### Parameters | | | | | --- | --- | --- | | first1, last1 | - | an iterator-sentinel pair denoting the first range of the elements to compare | | r1 | - | the first range of the elements to compare | | first2, last2 | - | an iterator-sentinel pair denoting the second range of the elements to compare | | r2 | - | the second range of the elements to compare | | pred | - | predicate to apply to the projected elements | | proj1 | - | projection to apply to the first range of elements | | proj2 | - | projection to apply to the second range of elements | ### Return value `ranges::mismatch_result` with iterators to the first two non-equal elements. If no mismatches are found when the comparison reaches `last1` or `last2`, whichever happens first, the object holds the end iterator and the corresponding iterator from the other range. ### Complexity At most min(`last1` - `first1`, `last2` - `first2`) applications of the predicate and corresponding projections. ### Possible implementation | | | --- | | ``` struct mismatch_fn { template<std::input_iterator I1, std::sentinel_for<I1> S1, std::input_iterator I2, std::sentinel_for<I2> S2, class Pred = ranges::equal_to, class Proj1 = std::identity, class Proj2 = std::identity> requires std::indirectly_comparable<I1, I2, Pred, Proj1, Proj2> constexpr std::mismatch_result<I1, I2> operator()(I1 first1, S1 last1, I2 first2, S2 last2, Pred pred = {}, Proj1 proj1 = {}, Proj2 proj2 = {}) const { for (; first1 != last1 && first2 != last2; ++first1, (void)++first2) { if (!std::invoke(pred, std::invoke(proj1, *first1), std::invoke(proj2, *first2))) { break; } } return {first1, first2}; } template<ranges::input_range R1, ranges::input_range R2, class Pred = ranges::equal_to, class Proj1 = std::identity, class Proj2 = std::identity > requires std::indirectly_comparable<ranges::iterator_t<R1>, ranges::iterator_t<R2>, Pred, Proj1, Proj2> constexpr ranges::mismatch_result<ranges::borrowed_iterator_t<R1>, ranges::borrowed_iterator_t<R2>> operator()(R1&& r1, R2&& r2, Pred pred = {}, Proj1 proj1 = {}, Proj2 proj2 = {}) const { return (*this)(ranges::begin(r1), ranges::end(r1), ranges::begin(r2), ranges::end(r2), std::ref(pred), std::ref(proj1), std::ref(proj2)); } }; inline constexpr mismatch_fn mismatch; ``` | ### Example This program determines the longest substring that is simultaneously found at the very beginning of the given string and at the very end of it, in reverse order (possibly overlapping). ``` #include <algorithm> #include <cstddef> #include <iostream> #include <ranges> #include <string_view> constexpr std::string_view mirror_ends(const std::string_view in) { const auto end = std::ranges::mismatch(in, in | std::views::reverse).in1; const std::size_t length = std::ranges::distance(in.begin(), end); return { in.cbegin(), length }; } int main() { std::cout << mirror_ends("abXYZba") << '\n' << mirror_ends("abca") << '\n' << mirror_ends("ABBA") << '\n' << mirror_ends("level") << '\n'; using namespace std::literals::string_view_literals; static_assert("123"sv == mirror_ends("123!@#321")); static_assert("radar"sv == mirror_ends("radar")); } ``` Output: ``` ab a ABBA level ``` ### See also | | | | --- | --- | | [ranges::equal](equal "cpp/algorithm/ranges/equal") (C++20) | determines if two sets of elements are the same (niebloid) | | [ranges::findranges::find\_ifranges::find\_if\_not](find "cpp/algorithm/ranges/find") (C++20)(C++20)(C++20) | finds the first element satisfying specific criteria (niebloid) | | [ranges::lexicographical\_compare](lexicographical_compare "cpp/algorithm/ranges/lexicographical compare") (C++20) | returns true if one range is lexicographically less than another (niebloid) | | [ranges::search](search "cpp/algorithm/ranges/search") (C++20) | searches for a range of elements (niebloid) | | [mismatch](../mismatch "cpp/algorithm/mismatch") | finds the first position where two ranges differ (function template) | cpp std::ranges::inplace_merge std::ranges::inplace\_merge =========================== | Defined in header `[<algorithm>](../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | Call signature | | | | ``` template< std::bidirectional_iterator I, std::sentinel_for<I> S, class Comp = ranges::less, class Proj = std::identity > requires std::sortable<I, Comp, Proj> I inplace_merge( I first, I middle, S last, Comp comp = {}, Proj proj = {} ); ``` | (1) | (since C++20) | | ``` template< ranges::bidirectional_range R, class Comp = ranges::less, class Proj = std::identity > requires std::sortable<ranges::iterator_t<R>, Comp, Proj> ranges::borrowed_iterator_t<R> inplace_merge( R&& r, ranges::iterator_t<R> middle, Comp comp = {}, Proj proj = {} ); ``` | (2) | (since C++20) | Merges two consecutive *sorted* ranges `[first, middle)` and `[middle, last)` into one *sorted* range `[first, last)`. A sequence is said to be *sorted* with respect to the comparator `comp` and projection `proj` if for any iterator `it` pointing to the sequence and any non-negative integer `n` such that `it + n` is a valid iterator pointing to an element of the sequence, `[std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(comp, [std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(proj, \*(it + n)), [std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(proj, \*it)))` evaluates to `false`. This merge function is *stable*, which means that for equivalent elements in the original two ranges, the elements from the first range (preserving their original order) precede the elements from the second range (preserving their original order). 1) Elements are compared using the given binary comparison function `comp` and projection object `proj`, and the ranges must be sorted with respect to the same. 2) Same as (1), but uses `r` as the range, as if using `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r)` as `first`, and `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r)` as `last`. The function-like entities described on this page are *niebloids*, that is: * Explicit template argument lists cannot be specified when calling any of them. * None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl"). * When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited. In practice, they may be implemented as function objects, or with special compiler extensions. ### Parameters | | | | | --- | --- | --- | | first | - | the beginning of the first sorted range | | middle | - | the end of the first range and the beginning of the second range | | last | - | the end of the second sorted range | | r | - | the range of elements to merge inplace | | comp | - | comparison to apply to the projected elements | | proj | - | projection to apply to the elements in the range. | ### Return value An iterator equal to `last`. ### Complexity Exactly `N−1` comparisons, if additional memory buffer is available, where `N = [ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(first, last)`. Otherwise, \(\scriptsize \mathcal{O}(N\cdot\log{(N)})\)𝓞(N•log(N)) comparisons. Additionally, twice as many projections as comparisons in both cases. ### Notes This function attempts to allocate a temporary buffer. If the allocation fails, the less efficient algorithm is chosen. ### Possible implementation This implementation only shows the slower algorithm used when no additional memory is available. See also the implementation in [MSVC STL](https://github.com/microsoft/STL/blob/e745bad3b1d05b5b19ec652d68abb37865ffa454/stl/inc/algorithm#L7131-L7235) and [libstdc++](https://github.com/gcc-mirror/gcc/blob/54258e22b0846aaa6bd3265f592feb161eecda75/libstdc%2B%2B-v3/include/bits/ranges_algo.h#L2573-L2602). | | | --- | | ``` struct inplace_merge_fn { template<std::bidirectional_iterator I, std::sentinel_for<I> S, class Comp = ranges::less, class Proj = std::identity> requires std::sortable<I, Comp, Proj> I operator()(I first, I middle, S last, Comp comp = {}, Proj proj = {}) const { I last_it = ranges::next(middle, last); inplace_merge_slow(first, middle, last_it, ranges::distance(first, middle), ranges::distance(middle, last_it), std::ref(comp), std::ref(proj)); return last_it; } template<ranges::bidirectional_range R, class Comp = ranges::less, class Proj = std::identity> requires std::sortable<ranges::iterator_t<R>, Comp, Proj> ranges::borrowed_iterator_t<R> operator()(R&& r, ranges::iterator_t<R> middle, Comp comp = {}, Proj proj = {}) const { return (*this)(ranges::begin(r), std::move(middle), ranges::end(r), std::move(comp), std::move(proj)); } private: template<class I, class Comp, class Proj> static void inplace_merge_slow(I first, I middle, I last, std::iter_difference_t<I> n1, std::iter_difference_t<I> n2, Comp comp, Proj proj) { if (n1 == 0 || n2 == 0) return; if (n1 + n2 == 2 && comp(proj(*middle), proj(*first))) { ranges::iter_swap(first, middle); return; } I cut1 = first, cut2 = middle; std::iter_difference_t<I> d1{}, d2{}; if (n1 > n2) { d1 = n1 / 2; ranges::advance(cut1, d1); cut2 = ranges::lower_bound(middle, last, *cut1, std::ref(comp), std::ref(proj)); d2 = ranges::distance(middle, cut2); } else { d2 = n2 / 2; ranges::advance(cut2, d2); cut1 = ranges::upper_bound(first, middle, *cut2, std::ref(comp), std::ref(proj)); d1 = ranges::distance(first, cut1); } I new_middle = ranges::rotate(cut1, middle, cut2); inplace_merge_slow(first, cut1, new_middle, d1, d2, std::ref(comp), std::ref(proj)); inplace_merge_slow(new_middle, cut2, last, n1 - d1, n2 - d2, std::ref(comp), std::ref(proj)); } }; inline constexpr inplace_merge_fn inplace_merge{}; ``` | ### Example ``` #include <algorithm> #include <complex> #include <functional> #include <iostream> #include <iterator> #include <vector> void print(auto const& v, auto const& rem, int middle = -1) { for (int i{}; auto n : v) std::cout << (i++ == middle ? "│ " : "") << n << ' '; std::cout << rem << '\n'; } template <std::random_access_iterator I, std::sentinel_for<I> S> requires std::sortable<I> void merge_sort(I first, S last) { if (last - first > 1) { I middle {first + (last - first) / 2}; merge_sort(first, middle); merge_sort(middle, last); std::ranges::inplace_merge(first, middle, last); } } int main() { // custom merge-sort demo std::vector v {8, 2, 0, 4, 9, 8, 1, 7, 3}; print(v, ": before sort"); merge_sort(v.begin(), v.end()); print(v, ": after sort\n"); // merging with comparison function object and projection using CI = std::complex<int>; std::vector<CI> r { {0,1}, {0,2}, {0,3}, {1,1}, {1,2} }; const auto middle { std::ranges::next(r.begin(), 3) }; auto comp { std::ranges::less{} }; auto proj { [](CI z) { return z.imag(); } }; print(r, ": before merge", middle - r.begin()); std::ranges::inplace_merge(r, middle, comp, proj); print(r, ": after merge"); } ``` Output: ``` 8 2 0 4 9 8 1 7 3 : before sort 0 1 2 3 4 7 8 8 9 : after sort (0,1) (0,2) (0,3) │ (1,1) (1,2) : before merge (0,1) (1,1) (0,2) (1,2) (0,3) : after merge ``` ### See also | | | | --- | --- | | [ranges::merge](merge "cpp/algorithm/ranges/merge") (C++20) | merges two sorted ranges (niebloid) | | [ranges::set\_union](set_union "cpp/algorithm/ranges/set union") (C++20) | computes the union of two sets (niebloid) | | [ranges::is\_sorted](is_sorted "cpp/algorithm/ranges/is sorted") (C++20) | checks whether a range is sorted into ascending order (niebloid) | | [ranges::sort](sort "cpp/algorithm/ranges/sort") (C++20) | sorts a range into ascending order (niebloid) | | [inplace\_merge](../inplace_merge "cpp/algorithm/inplace merge") | merges two ordered ranges in-place (function template) | cpp std::ranges::move_backward, std::ranges::move_backward_result std::ranges::move\_backward, std::ranges::move\_backward\_result ================================================================ | Defined in header `[<algorithm>](../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | Call signature | | | | ``` template< std::bidirectional_iterator I1, std::sentinel_for<I1> S1, std::bidirectional_iterator I2 > requires std::indirectly_movable<I1, I2> constexpr move_backward_result<I1, I2> move_backward( I1 first, S1 last, I2 result ); ``` | (1) | (since C++20) | | ``` template< ranges::bidirectional_range R, std::bidirectional_iterator I > requires std::indirectly_movable<ranges::iterator_t<R>, I> constexpr move_backward_result<ranges::borrowed_iterator_t<R>, I> move_backward( R&& r, I result ); ``` | (2) | (since C++20) | | Helper types | | | | ``` template< class I, class O > using move_backward_result = ranges::in_out_result<I, O>; ``` | (3) | (since C++20) | 1) Moves the elements in the range, defined by `[first, last)`, to another range `[result - N, result)`, where `N = [ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(first, last)`. The elements are moved in reverse order (the last element is moved first), but their relative order is preserved. The behavior is undefined if `result` is within `(first, last]`. In such a case, `[ranges::move](move "cpp/algorithm/ranges/move")` may be used instead. 2) Same as (1), but uses `r` as the source range, as if using `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r)` as `first`, and `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r)` as `last`. The elements in the *moved-from* range will still contain valid values of the appropriate type, but not necessarily the same values as before the move, as if using `\*(result - n) = [ranges::iter\_move](http://en.cppreference.com/w/cpp/iterator/ranges/iter_move)(last - n)` for each integer `n`, where `0 ≤ n < N`. The function-like entities described on this page are *niebloids*, that is: * Explicit template argument lists cannot be specified when calling any of them. * None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl"). * When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited. In practice, they may be implemented as function objects, or with special compiler extensions. ### Parameters | | | | | --- | --- | --- | | first | - | the beginning of the range of elements to move | | last | - | the end of the range of elements to move | | r | - | the range of the elements to move | | result | - | the end of the destination range | ### Return value `{last, result - N}`. ### Complexity 1) Exactly `N` move assignments. 2) Exactly `[ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(r)` move assignments. ### Notes When moving overlapping ranges, `[ranges::move](move "cpp/algorithm/ranges/move")` is appropriate when moving to the left (beginning of the destination range is outside the source range) while `ranges::move_backward` is appropriate when moving to the right (end of the destination range is outside the source range). ### Possible implementation | | | --- | | ``` struct move_backward_fn { template<std::bidirectional_iterator I1, std::sentinel_for<I1> S1, std::bidirectional_iterator I2> requires std::indirectly_movable<I1, I2> constexpr ranges::move_backward_result<I1, I2> operator()( I1 first, S1 last, I2 result ) const { auto i {last}; for (; i != first; *--result = ranges::iter_move(--i)); return {std::move(last), std::move(result)}; } template<ranges::bidirectional_range R, std::bidirectional_iterator I> requires std::indirectly_movable<ranges::iterator_t<R>, I> constexpr ranges::move_backward_result<ranges::borrowed_iterator_t<R>, I> operator()( R&& r, I result ) const { return (*this)(ranges::begin(r), ranges::end(r), std::move(result)); } }; inline constexpr move_backward_fn move_backward{}; ``` | ### Example ``` #include <algorithm> #include <iostream> #include <string> #include <string_view> #include <vector> using Vec = std::vector<std::string>; void print(std::string_view rem, Vec const& vec) { std::cout << rem << "[" << vec.size() << "]: "; for (const std::string& s : vec) std::cout << (s.size() ? s : std::string{"·"}) << ' '; std::cout << '\n'; } int main() { Vec a{"▁", "▂", "▃", "▄", "▅", "▆", "▇", "█"}; Vec b(a.size()); print("Before move:\n" "a", a); print("b", b); std::ranges::move_backward(a, b.end()); print("\n" "Move a >> b:\n" "a", a); print("b", b); std::ranges::move_backward(b.begin(), b.end(), a.end()); print("\n" "Move b >> a:\n" "a", a); print("b", b); std::ranges::move_backward(a.begin(), a.begin()+3, a.end()); print("\n" "Overlapping move a[0, 3) >> a[5, 8):\n" "a", a); } ``` Possible output: ``` Before move: a[8]: ▁ ▂ ▃ ▄ ▅ ▆ ▇ █ b[8]: · · · · · · · · Move a >> b: a[8]: · · · · · · · · b[8]: ▁ ▂ ▃ ▄ ▅ ▆ ▇ █ Move b >> a: a[8]: ▁ ▂ ▃ ▄ ▅ ▆ ▇ █ b[8]: · · · · · · · · Overlapping move a[0, 3) >> a[5, 8): a[8]: · · · ▄ ▅ ▁ ▂ ▃ ``` ### See also | | | | --- | --- | | [ranges::move](move "cpp/algorithm/ranges/move") (C++20) | moves a range of elements to a new location (niebloid) | | [ranges::copyranges::copy\_if](copy "cpp/algorithm/ranges/copy") (C++20)(C++20) | copies a range of elements to a new location (niebloid) | | [ranges::copy\_backward](copy_backward "cpp/algorithm/ranges/copy backward") (C++20) | copies a range of elements in backwards order (niebloid) | | [move](../move "cpp/algorithm/move") (C++11) | moves a range of elements to a new location (function template) | | [move](../../utility/move "cpp/utility/move") (C++11) | obtains an rvalue reference (function template) |
programming_docs
cpp std::ranges::ends_with std::ranges::ends\_with ======================= | Defined in header `[<algorithm>](../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | Call signature | | | | ``` template< std::input_iterator I1, std::sentinel_for<I1> S1, std::input_iterator I2, std::sentinel_for<I2> S2, class Pred = ranges::equal_to, class Proj1 = std::identity, class Proj2 = std::identity > requires (std::forward_iterator<I1> || std::sized_sentinel_for<S1, I1>) && (std::forward_iterator<I2> || std::sized_sentinel_for<S2, I2>) && std::indirectly_comparable<I1, I2, Pred, Proj1, Proj2> constexpr bool ends_with( I1 first1, S1 last1, I2 first2, S2 last2, Pred pred = {}, Proj1 proj1 = {}, Proj2 proj2 = {} ); ``` | (1) | (since C++23) | | ``` template< ranges::input_range R1, ranges::input_range R2, class Pred = ranges::equal_to, class Proj1 = std::identity, class Proj2 = std::identity > requires (ranges::forward_range<R1> || ranges::sized_range<R1>) && (ranges::forward_range<R2> || ranges::sized_range<R2>) && std::indirectly_comparable<ranges::iterator_t<R1>, ranges::iterator_t<R2>, Pred, Proj1, Proj2> constexpr bool ends_with( R1&& r1, R2&& r2, Pred pred = {}, Proj1 proj1 = {}, Proj2 proj2 = {} ); ``` | (2) | (since C++23) | Checks whether the second range matches the suffix of the first range. 1) Let `N1` and `N2` be `[ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(first1, last1)` and `[ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(first2, last2)` respectively. If `N1 < N2`, returns `false`. Otherwise, returns `true` if only if every element in the range `[first2, last2)` is equal to the corresponding element in `[first1 + N1 - N2, last1)`. Comparison is done by applying the binary predicate `pred` to elements in two ranges projected by `proj1` and `proj2` respectively. 2) Same as (1), but uses `r1` and `r2` as the source ranges, as if using `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r1)` as `first1`, `ranges:begin(r2)` as `first2`, `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r1)` as `last1`, and `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r2)` as `last2`. The function-like entities described on this page are *niebloids*, that is: * Explicit template argument lists cannot be specified when calling any of them. * None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl"). * When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited. In practice, they may be implemented as function objects, or with special compiler extensions. ### Parameters | | | | | --- | --- | --- | | first1, last1 | - | the range of elements to examine | | r1 | - | the range of elements to examine | | first2, last2 | - | the range of elements to be used as the suffix | | r2 | - | the range of elements to be used as the suffix | | pred | - | the binary predicate that compares the projected elements | | proj1 | - | the projection to apply to the elements of the range to examine | | proj2 | - | the projection to apply to the elements of the range to be used as the suffix | ### Return value `true` if the second range matches the suffix of the first range, `false` otherwise. ### Complexity Generally linear: at most `min(N1, N2)` applications of the predicate and both projections. The predicate and both projections are not applied if `N1 < N2`. If both `N1` and `N2` can be calculated in constant time (i.e. both iterator-sentinel type pairs model [`sized_sentinel_for`](../../iterator/sized_sentinel_for "cpp/iterator/sized sentinel for"), or both range types model [`sized_range`](../../ranges/sized_range "cpp/ranges/sized range")) and `N1 < N2`, the time complexity is constant. ### Possible implementation | | | --- | | ``` struct ends_with_fn { template<std::input_iterator I1, std::sentinel_for<I1> S1, std::input_iterator I2, std::sentinel_for<I2> S2, class Pred = ranges::equal_to, class Proj1 = std::identity, class Proj2 = std::identity> requires (std::forward_iterator<I1> || std::sized_sentinel_for<S1, I1>) && (std::forward_iterator<I2> || std::sized_sentinel_for<S2, I2>) && std::indirectly_comparable<I1, I2, Pred, Proj1, Proj2> constexpr bool operator()(I1 first1, S1 last1, I2 first2, S2 last2, Pred pred = {}, Proj1 proj1 = {}, Proj2 proj2 = {}) const { const auto n1 = ranges::distance(first1, last1); const auto n2 = ranges::distance(first2, last2); if (n1 < n2) return false; ranges::advance(first1, n1 - n2); return ranges::equal(std::move(first1), std::move(last1), std::move(first2), std::move(last2), std::move(pred), std::move(proj1), std::move(proj2)); } template<ranges::input_range R1, ranges::input_range R2, class Pred = ranges::equal_to, class Proj1 = std::identity, class Proj2 = std::identity> requires (ranges::forward_range<R1> || ranges::sized_range<R1>) && (ranges::forward_range<R2> || ranges::sized_range<R2>) && std::indirectly_comparable<ranges::iterator_t<R1>, ranges::iterator_t<R2>, Pred, Proj1, Proj2> constexpr bool operator()(R1&& r1, R2&& r2, Pred pred = {}, Proj1 proj1 = {}, Proj2 proj2 = {}) const { return (*this)(ranges::begin(r1), ranges::end(r1), ranges::begin(r2), ranges::end(r2), std::move(pred), std::move(proj1), std::move(proj2)); } }; inline constexpr ends_with_fn ends_with{}; ``` | ### Notes | [Feature-test](../../utility/feature_test "cpp/utility/feature test") macro | Value | Std | | --- | --- | --- | | [`__cpp_lib_ranges_starts_ends_with`](../../feature_test#Library_features "cpp/feature test") | `202106L` | (C++23) | ### Example ``` #include <algorithm> #include <array> #include <iostream> int main() { std::cout << std::boolalpha << std::ranges::ends_with("static_cast", "cast") << '\n' << std::ranges::ends_with("const_cast", "cast") << '\n' << std::ranges::ends_with("reinterpret_cast", "cast") << '\n' << std::ranges::ends_with("dynamic_cast", "cast") << '\n' << std::ranges::ends_with("move", "cast") << '\n' << std::ranges::ends_with("move_if_noexcept", "cast") << '\n' << std::ranges::ends_with("forward", "cast") << '\n'; static_assert( ! std::ranges::ends_with("as_const", "cast") and !! std::ranges::ends_with("bit_cast", "cast") and ! std::ranges::ends_with("to_underlying", "cast") and !! std::ranges::ends_with(std::array{1,2,3,4}, std::array{3,4}) and ! std::ranges::ends_with(std::array{1,2,3,4}, std::array{4,5}) ); } ``` Output: ``` true true true true false false false ``` ### See also | | | | --- | --- | | [ranges::starts\_with](starts_with "cpp/algorithm/ranges/starts with") (C++23) | checks whether a range starts with another range (niebloid) | | [ends\_with](../../string/basic_string/ends_with "cpp/string/basic string/ends with") (C++20) | checks if the string ends with the given suffix (public member function of `std::basic_string<CharT,Traits,Allocator>`) | | [ends\_with](../../string/basic_string_view/ends_with "cpp/string/basic string view/ends with") (C++20) | checks if the string view ends with the given suffix (public member function of `std::basic_string_view<CharT,Traits>`) | cpp std::ranges::pop_heap std::ranges::pop\_heap ====================== | Defined in header `[<algorithm>](../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | Call signature | | | | ``` template< std::random_access_iterator I, std::sentinel_for<I> S, class Comp = ranges::less, class Proj = std::identity > requires std::sortable<I, Comp, Proj> constexpr I pop_heap( I first, S last, Comp comp = {}, Proj proj = {} ); ``` | (1) | (since C++20) | | ``` template< ranges::random_access_range R, class Comp = ranges::less, class Proj = std::identity > requires std::sortable<ranges::iterator_t<R>, Comp, Proj> constexpr ranges::borrowed_iterator_t<R> pop_heap( R&& r, Comp comp = {}, Proj proj = {} ); ``` | (2) | (since C++20) | Swaps the value in the position `first` and the value in the position `last-1` and makes the subrange `[first, last-1)` into a [*max heap*](https://en.wikipedia.org/wiki/Binary_heap "enwiki:Binary heap"). This has the effect of removing the first element from the heap defined by the range `[first, last)`. 1) Elements are compared using the given binary comparison function `comp` and projection object `proj`. 2) Same as (1), but uses `r` as the range, as if using `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r)` as `first` and `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r)` as `last`. The function-like entities described on this page are *niebloids*, that is: * Explicit template argument lists cannot be specified when calling any of them. * None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl"). * When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited. In practice, they may be implemented as function objects, or with special compiler extensions. ### Parameters | | | | | --- | --- | --- | | first, last | - | the range of elements defining the valid nonempty heap to modify | | r | - | the range of elements defining the valid nonempty heap to modify | | pred | - | predicate to apply to the projected elements | | proj | - | projection to apply to the elements | ### Return value An iterator equal to `last`. ### Complexity Given `N = [ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(first, last)`, at most \(\scriptsize 2\log{(N)}\)2log(N) comparisons and \(\scriptsize 4\log{(N)}\)4log(N) projections. ### Notes A *max heap* is a range of elements `[f, l)`, arranged with respect to comparator `comp` and projection `proj`, that has the following properties: * With `N = l-f`, `p = f[(i-1)/2]`, and `q = f[i]`, for all `0 < i < N`, the expression `[std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(comp, [std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(proj, p), [std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(proj, q))` evaluates to `false`. * A new element can be added using `[ranges::push\_heap](push_heap "cpp/algorithm/ranges/push heap")`, in \(\scriptsize \mathcal{O}(\log N)\)𝓞(log N) time. * The first element can be removed using `ranges::pop_heap`, in \(\scriptsize \mathcal{O}(\log N)\)𝓞(log N) time. ### Example ``` #include <algorithm> #include <array> #include <iostream> #include <iterator> #include <string_view> template <class I = int*> void print(std::string_view rem, I first = {}, I last = {}, std::string_view term = "\n") { for (std::cout << rem; first != last; ++first) { std::cout << *first << ' '; } std::cout << term; } int main() { std::array v { 3, 1, 4, 1, 5, 9, 2, 6, 5, 3 }; print("initially, v: ", v.cbegin(), v.cend()); std::ranges::make_heap(v); print("make_heap, v: ", v.cbegin(), v.cend()); print("convert heap into sorted array:"); for (auto n {std::ssize(v)}; n >= 0; --n) { std::ranges::pop_heap(v.begin(), v.begin() + n); print("[ ", v.cbegin(), v.cbegin() + n, "] "); print("[ ", v.cbegin() + n, v.cend(), "]\n"); } } ``` Output: ``` initially, v: 3 1 4 1 5 9 2 6 5 3 make_heap, v: 9 6 4 5 5 3 2 1 1 3 convert heap into sorted array: [ 6 5 4 3 5 3 2 1 1 9 ] [ ] [ 5 5 4 3 1 3 2 1 6 ] [ 9 ] [ 5 3 4 1 1 3 2 5 ] [ 6 9 ] [ 4 3 3 1 1 2 5 ] [ 5 6 9 ] [ 3 2 3 1 1 4 ] [ 5 5 6 9 ] [ 3 2 1 1 3 ] [ 4 5 5 6 9 ] [ 2 1 1 3 ] [ 3 4 5 5 6 9 ] [ 1 1 2 ] [ 3 3 4 5 5 6 9 ] [ 1 1 ] [ 2 3 3 4 5 5 6 9 ] [ 1 ] [ 1 2 3 3 4 5 5 6 9 ] [ ] [ 1 1 2 3 3 4 5 5 6 9 ] ``` ### See also | | | | --- | --- | | [ranges::push\_heap](push_heap "cpp/algorithm/ranges/push heap") (C++20) | adds an element to a max heap (niebloid) | | [ranges::is\_heap](is_heap "cpp/algorithm/ranges/is heap") (C++20) | checks if the given range is a max heap (niebloid) | | [ranges::is\_heap\_until](is_heap_until "cpp/algorithm/ranges/is heap until") (C++20) | finds the largest subrange that is a max heap (niebloid) | | [ranges::make\_heap](make_heap "cpp/algorithm/ranges/make heap") (C++20) | creates a max heap out of a range of elements (niebloid) | | [ranges::sort\_heap](sort_heap "cpp/algorithm/ranges/sort heap") (C++20) | turns a max heap into a range of elements sorted in ascending order (niebloid) | | [pop\_heap](../pop_heap "cpp/algorithm/pop heap") | removes the largest element from a max heap (function template) | cpp std::ranges::merge, std::ranges::merge_result std::ranges::merge, std::ranges::merge\_result ============================================== | Defined in header `[<algorithm>](../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | Call signature | | | | ``` template< std::input_iterator I1, std::sentinel_for<I1> S1, std::input_iterator I2, std::sentinel_for<I2> S2, std::weakly_incrementable O, class Comp = ranges::less, class Proj1 = std::identity, class Proj2 = std::identity > requires std::mergeable<I1, I2, O, Comp, Proj1, Proj2> constexpr merge_result<I1, I2, O> merge( I1 first1, S1 last1, I2 first2, S2 last2, O result, Comp comp = {}, Proj1 proj1 = {}, Proj2 proj2 = {} ); ``` | (1) | (since C++20) | | ``` template< ranges::input_range R1, ranges::input_range R2, std::weakly_incrementable O, class Comp = ranges::less, class Proj1 = std::identity, class Proj2 = std::identity > requires std::mergeable<ranges::iterator_t<R1>, ranges::iterator_t<R2>, O, Comp, Proj1, Proj2> constexpr merge_result<ranges::borrowed_iterator_t<R1>, ranges::borrowed_iterator_t<R2>, O> merge( R1&& r1, R2&& r2, O result, Comp comp = {}, Proj1 proj1 = {}, Proj2 proj2 = {} ); ``` | (2) | (since C++20) | | Helper types | | | | ``` template<class I1, class I2, class O> using merge_result = ranges::in_in_out_result<I1, I2, O>; ``` | (3) | (since C++20) | Merges two *sorted* ranges `[first1, last1)` and `[first2, last2)` into one *sorted* range beginning at `result`. A sequence is said to be *sorted* with respect to the comparator `comp` if for any iterator `it` pointing to the sequence and any non-negative integer `n` such that `it + n` is a valid iterator pointing to an element of the sequence, `[std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(comp, [std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(proj2, \*(it + n)), [std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(proj1, \*it)))` evaluates to `false`. 1) Elements are compared using the given binary comparison function `comp`. 2) Same as (1), but uses `r1` as the first range and `r2` as the second range, as if using `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r1)` as `first1`, `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r1)` as `last1`, `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r2)` as `first2`, and `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r2)` as `last2`. The behavior is undefined if the destination range overlaps either of the input ranges (the input ranges may overlap each other). This merge function is *stable*, which means that for equivalent elements in the original two ranges, the elements from the first range (preserving their original order) precede the elements from the second range (preserving their original order). The function-like entities described on this page are *niebloids*, that is: * Explicit template argument lists cannot be specified when calling any of them. * None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl"). * When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited. In practice, they may be implemented as function objects, or with special compiler extensions. ### Parameters | | | | | --- | --- | --- | | first1, last1 | - | the first input sorted range | | first2, last2 | - | the second input sorted range | | result | - | the beginning of the output range | | comp | - | comparison to apply to the projected elements | | proj1 | - | projection to apply to the elements in the first range | | proj2 | - | projection to apply to the elements in the second range | ### Return value `{last1, last2, result_last}`, where `result_last` is the end of the constructed range. ### Complexity At most `N−1` comparisons and applications of each projection, where `N = [ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(first1, last1) + [ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(first2, last12)`. ### Notes This algorithm performs a similar task as `[ranges::set\_union](http://en.cppreference.com/w/cpp/algorithm/ranges/set_union)` does. Both consume two sorted input ranges and produce a sorted output with elements from both inputs. The difference between these two algorithms is with handling values from both input ranges which compare equivalent (see notes on [LessThanComparable](../../named_req/lessthancomparable "cpp/named req/LessThanComparable")). If any equivalent values appeared `n` times in the first range and `m` times in the second, `ranges::merge` would output all `n+m` occurrences whereas `[ranges::set\_union](set_union "cpp/algorithm/ranges/set union")` would output `max(n, m)` ones only. So `ranges::merge` outputs exactly `N` values and `[ranges::set\_union](set_union "cpp/algorithm/ranges/set union")` may produce fewer. ### Possible implementation | | | --- | | ``` struct merge_fn { template< std::input_iterator I1, std::sentinel_for<I1> S1, std::input_iterator I2, std::sentinel_for<I2> S2, std::weakly_incrementable O, class Comp = ranges::less, class Proj1 = std::identity, class Proj2 = std::identity > requires std::mergeable<I1, I2, O, Comp, Proj1, Proj2> constexpr ranges::merge_result<I1, I2, O> operator()( I1 first1, S1 last1, I2 first2, S2 last2, O result, Comp comp = {}, Proj1 proj1 = {}, Proj2 proj2 = {} ) const { for (; !(first1 == last1 or first2 == last2); ++result) { if (std::invoke(comp, std::invoke(proj2, *first2), std::invoke(proj1, *first1))) *result = *first2, ++first2; else *result = *first1, ++first1; } auto ret1 {ranges::copy(std::move(first1), std::move(last1), std::move(result))}; auto ret2 {ranges::copy(std::move(first2), std::move(last2), std::move(ret1.out))}; return { std::move(ret1.in), std::move(ret2.in), std::move(ret2.out) }; } template< ranges::input_range R1, ranges::input_range R2, std::weakly_incrementable O, class Comp = ranges::less, class Proj1 = std::identity, class Proj2 = std::identity > requires std::mergeable<ranges::iterator_t<R1>, ranges::iterator_t<R2>, O, Comp, Proj1, Proj2> constexpr ranges::merge_result<ranges::borrowed_iterator_t<R1>, ranges::borrowed_iterator_t<R2>, O> operator()( R1&& r1, R2&& r2, O result, Comp comp = {}, Proj1 proj1 = {}, Proj2 proj2 = {} ) const { return (*this)(ranges::begin(r1), ranges::end(r1), ranges::begin(r2), ranges::end(r2), std::move(result), std::move(comp), std::move(proj1), std::move(proj2)); } }; inline constexpr merge_fn merge{}; ``` | ### Example ``` #include <algorithm> #include <iostream> #include <iterator> #include <vector> void print(const auto& in1, const auto& in2, auto first, auto last) { std::cout << "{ "; for (const auto& e : in1) { std::cout << e << ' '; } std::cout << "} +\n{ "; for (const auto& e : in2) { std::cout << e << ' '; } std::cout << "} =\n{ "; while (!(first == last)) { std::cout << *first++ << ' '; } std::cout << "}\n\n"; } int main() { std::vector<int> in1, in2, out; in1 = {1, 2, 3, 4, 5}; in2 = { 3, 4, 5, 6, 7}; out.resize(in1.size() + in2.size()); const auto ret = std::ranges::merge(in1, in2, out.begin()); print(in1, in2, out.begin(), ret.out); in1 = {1, 2, 3, 4, 5, 5, 5}; in2 = { 3, 4, 5, 6, 7}; out.clear(); out.reserve(in1.size() + in2.size()); std::ranges::merge(in1, in2, std::back_inserter(out)); print(in1, in2, out.cbegin(), out.cend()); } ``` Output: ``` { 1 2 3 4 5 } + { 3 4 5 6 7 } = { 1 2 3 3 4 4 5 5 6 7 } { 1 2 3 4 5 5 5 } + { 3 4 5 6 7 } = { 1 2 3 3 4 4 5 5 5 5 6 7 } ``` ### See also | | | | --- | --- | | [ranges::inplace\_merge](inplace_merge "cpp/algorithm/ranges/inplace merge") (C++20) | merges two ordered ranges in-place (niebloid) | | [ranges::is\_sorted](is_sorted "cpp/algorithm/ranges/is sorted") (C++20) | checks whether a range is sorted into ascending order (niebloid) | | [ranges::set\_union](set_union "cpp/algorithm/ranges/set union") (C++20) | computes the union of two sets (niebloid) | | [ranges::sort](sort "cpp/algorithm/ranges/sort") (C++20) | sorts a range into ascending order (niebloid) | | [ranges::stable\_sort](stable_sort "cpp/algorithm/ranges/stable sort") (C++20) | sorts a range of elements while preserving order between equal elements (niebloid) | | [merge](../merge "cpp/algorithm/merge") | merges two sorted ranges (function template) |
programming_docs
cpp std::ranges::lower_bound std::ranges::lower\_bound ========================= | Defined in header `[<algorithm>](../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | Call signature | | | | ``` template< std::forward_iterator I, std::sentinel_for<I> S, class T, class Proj = std::identity, std::indirect_strict_weak_order< const T*, std::projected<I, Proj>> Comp = ranges::less > constexpr I lower_bound( I first, S last, const T& value, Comp comp = {}, Proj proj = {} ); ``` | (1) | (since C++20) | | ``` template< ranges::forward_range R, class T, class Proj = std::identity, std::indirect_strict_weak_order< const T*, std::projected<ranges::iterator_t<R>, Proj>> Comp = ranges::less > constexpr ranges::borrowed_iterator_t<R> lower_bound( R&& r, const T& value, Comp comp = {}, Proj proj = {} ); ``` | (2) | (since C++20) | 1) Returns an iterator pointing to the first element in the range `[first, last)` that is *not less* than (i.e. greater or equal to) `value`, or `last` if no such element is found. The range `[first, last)` must be partitioned with respect to the expression `comp(element, value)`, i.e., all elements for which the expression is `true` must precede all elements for which the expression is `false`. A fully-sorted range meets this criterion. 2) Same as (1), but uses `r` as the source range, as if using `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r)` as `first` and `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r)` as `last`. The function-like entities described on this page are *niebloids*, that is: * Explicit template argument lists cannot be specified when calling any of them. * None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl"). * When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited. In practice, they may be implemented as function objects, or with special compiler extensions. ### Parameters | | | | | --- | --- | --- | | first, last | - | iterator-sentinel pair defining the partially-ordered range to examine | | r | - | the partially-ordered range to examine | | value | - | value to compare the elements to | | pred | - | predicate to apply to the projected elements | | proj | - | projection to apply to the elements | ### Return value Iterator pointing to the first element that is *not less* than `value`, or `last` if no such element is found. ### Complexity The number of comparisons and applications of the projection performed are logarithmic in the distance between `first` and `last` (At most log 2(last - first) + O(1) comparisons and applications of the projection). However, for an iterator that does not model [`random_access_iterator`](../../iterator/random_access_iterator "cpp/iterator/random access iterator"), the number of iterator increments is linear. ### Possible implementation | | | --- | | ``` struct lower_bound_fn { template<std::forward_iterator I, std::sentinel_for<I> S, class T, class Proj = std::identity, std::indirect_strict_weak_order< const T*, std::projected<I, Proj>> Comp = ranges::less> constexpr I operator()( I first, S last, const T& value, Comp comp = {}, Proj proj = {} ) const { I it; std::iter_difference_t<I> count, step; count = std::ranges::distance(first, last); while (count > 0) { it = first; step = count / 2; ranges::advance(it, step, last); if (comp(std::invoke(proj, *it), value)) { first = ++it; count -= step + 1; } else { count = step; } } return first; } template<ranges::forward_range R, class T, class Proj = std::identity, std::indirect_strict_weak_order< const T*, std::projected<ranges::iterator_t<R>, Proj>> Comp = ranges::less> constexpr ranges::borrowed_iterator_t<R> operator()( R&& r, const T& value, Comp comp = {}, Proj proj = {} ) const { return (*this)(ranges::begin(r), ranges::end(r), value, std::ref(comp), std::ref(proj)); } }; inline constexpr lower_bound_fn lower_bound; ``` | ### Example ``` #include <algorithm> #include <iostream> #include <iterator> #include <vector> namespace ranges = std::ranges; template<std::forward_iterator I, std::sentinel_for<I> S, class T, class Proj = std::identity, std::indirect_strict_weak_order< const T*, std::projected<I, Proj>> Comp = ranges::less> constexpr I binary_find(I first, S last, const T& value, Comp comp = {}, Proj proj = {}) { first = ranges::lower_bound(first, last, value, comp, proj); return first != last && !comp(value, proj(*first)) ? first : last; } int main() { std::vector data = { 1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5 }; auto lower = ranges::lower_bound(data, 4); auto upper = ranges::upper_bound(data, 4); ranges::copy(lower, upper, std::ostream_iterator<int>(std::cout, " ")); std::cout << '\n'; // classic binary search, returning a value only if it is present data = { 1, 2, 4, 8, 16 }; auto it = binary_find(data.cbegin(), data.cend(), 8); //< choosing '5' will return end() if(it != data.cend()) std::cout << *it << " found at index "<< ranges::distance(data.cbegin(), it); } ``` Output: ``` 4 4 4 4 8 found at index 3 ``` ### See also | | | | --- | --- | | [ranges::equal\_range](equal_range "cpp/algorithm/ranges/equal range") (C++20) | returns range of elements matching a specific key (niebloid) | | [ranges::partition](partition "cpp/algorithm/ranges/partition") (C++20) | divides a range of elements into two groups (niebloid) | | [ranges::partition\_point](partition_point "cpp/algorithm/ranges/partition point") (C++20) | locates the partition point of a partitioned range (niebloid) | | [ranges::upper\_bound](upper_bound "cpp/algorithm/ranges/upper bound") (C++20) | returns an iterator to the first element *greater* than a certain value (niebloid) | | [lower\_bound](../lower_bound "cpp/algorithm/lower bound") | returns an iterator to the first element *not less* than the given value (function template) | cpp std::ranges::push_heap std::ranges::push\_heap ======================= | Defined in header `[<algorithm>](../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | Call signature | | | | ``` template< std::random_access_iterator I, std::sentinel_for<I> S, class Comp = ranges::less, class Proj = std::identity > requires std::sortable<I, Comp, Proj> constexpr I push_heap( I first, S last, Comp comp = {}, Proj proj = {} ); ``` | (1) | (since C++20) | | ``` template< ranges::random_access_range R, class Comp = ranges::less, class Proj = std::identity > requires std::sortable<ranges::iterator_t<R>, Comp, Proj> constexpr ranges::borrowed_iterator_t<R> push_heap( R&& r, Comp comp = {}, Proj proj = {} ); ``` | (2) | (since C++20) | Inserts the element at the position `last-1` into the [*max heap*](https://en.wikipedia.org/wiki/Binary_heap "enwiki:Binary heap") defined by the range `[first, last-1)`. 1) Elements are compared using the given binary comparison function `comp` and projection object `proj`. 2) Same as (1), but uses `r` as the range, as if using `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r)` as `first` and `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r)` as `last`. The function-like entities described on this page are *niebloids*, that is: * Explicit template argument lists cannot be specified when calling any of them. * None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl"). * When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited. In practice, they may be implemented as function objects, or with special compiler extensions. ### Parameters | | | | | --- | --- | --- | | first, last | - | the range of elements defining the heap to modify | | r | - | the range of elements defining the heap to modify | | pred | - | predicate to apply to the projected elements | | proj | - | projection to apply to the elements | ### Return value An iterator equal to `last`. ### Complexity Given `N = [ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(first, last)`, at most \(\scriptsize \log{(N)}\)log(N) comparisons and \(\scriptsize 2\log{(N)}\)2log(N) projections. ### Notes A *max heap* is a range of elements `[f, l)`, arranged with respect to comparator `comp` and projection `proj`, that has the following properties: * With `N = l-f`, `p = f[(i-1)/2]`, and `q = f[i]`, for all `0 < i < N`, the expression `[std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(comp, [std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(proj, p), [std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(proj, q))` evaluates to `false`. * A new element can be added using `ranges::push_heap`, in \(\scriptsize \mathcal{O}(\log N)\)𝓞(log N) time. * The first element can be removed using `[ranges::pop\_heap](pop_heap "cpp/algorithm/ranges/pop heap")`, in \(\scriptsize \mathcal{O}(\log N)\)𝓞(log N) time. ### Possible implementation | | | --- | | ``` struct push_heap_fn { template< std::random_access_iterator I, std::sentinel_for<I> S, class Comp = ranges::less, class Proj = std::identity > requires std::sortable<I, Comp, Proj> constexpr I operator()( I first, S last, Comp comp = {}, Proj proj = {} ) const { const auto n {ranges::distance(first, last)}; const auto length {n}; if (n > 1) { I last {first + n}; n = (n - 2) / 2; I i {first + n}; if (std::invoke(comp, std::invoke(proj, *i), std::invoke(proj, *--last))) { std::iter_value_t<I> v {ranges::iter_move(last)}; do { *last = ranges::iter_move(i); last = i; if (n == 0) break; n = (n - 1) / 2; i = first + n; } while (std::invoke(comp, std::invoke(proj, *i), std::invoke(proj, v))); *last = std::move(v); } } return first + length; } template< ranges::random_access_range R, class Comp = ranges::less, class Proj = std::identity > requires std::sortable<ranges::iterator_t<R>, Comp, Proj> constexpr ranges::borrowed_iterator_t<R> operator()( R&& r, Comp comp = {}, Proj proj = {} ) const { return (*this)(ranges::begin(r), ranges::end(r), std::move(comp), std::move(proj)); } }; inline constexpr push_heap_fn push_heap{}; ``` | ### Example ``` #include <algorithm> #include <cmath> #include <iostream> #include <vector> void out(const auto& what, int n = 1) { while (n-- > 0) std::cout << what; } void print(auto rem, auto const& v) { out(rem); for (auto e : v) { out(e), out(' '); } out('\n'); } void draw_heap(auto const& v); int main() { std::vector<int> v { 1, 6, 1, 8, 0, 3, }; print("source vector v: ", v); std::ranges::make_heap(v); print("after make_heap: ", v); draw_heap(v); v.push_back(9); print("before push_heap: ", v); draw_heap(v); std::ranges::push_heap(v); print("after push_heap: ", v); draw_heap(v); } void draw_heap(auto const& v) { auto bails = [](int n, int w) { auto b = [](int w) { out("┌"), out("─", w), out("┴"), out("─", w), out("┐"); }; if (!(n /= 2)) return; for (out(' ', w); n-- > 0; ) b(w), out(' ', w + w + 1); out('\n'); }; auto data = [](int n, int w, auto& first, auto last) { for(out(' ', w); n-- > 0 && first != last; ++first) out(*first), out(' ', w + w + 1); out('\n'); }; auto tier = [&](int t, int m, auto& first, auto last) { const int n {1 << t}; const int w {(1 << (m - t - 1)) - 1}; bails(n, w), data(n, w, first, last); }; const int m {static_cast<int>(std::ceil(std::log2(1 + v.size())))}; auto first {v.cbegin()}; for (int i{}; i != m; ++i) { tier(i, m, first, v.cend()); } } ``` Output: ``` source vector v: 1 6 1 8 0 3 after make_heap: 8 6 3 1 0 1 8 ┌─┴─┐ 6 3 ┌┴┐ ┌┴┐ 1 0 1 before push_heap: 8 6 3 1 0 1 9 8 ┌─┴─┐ 6 3 ┌┴┐ ┌┴┐ 1 0 1 9 after push_heap: 9 6 8 1 0 1 3 9 ┌─┴─┐ 6 8 ┌┴┐ ┌┴┐ 1 0 1 3 ``` ### See also | | | | --- | --- | | [ranges::is\_heap](is_heap "cpp/algorithm/ranges/is heap") (C++20) | checks if the given range is a max heap (niebloid) | | [ranges::is\_heap\_until](is_heap_until "cpp/algorithm/ranges/is heap until") (C++20) | finds the largest subrange that is a max heap (niebloid) | | [ranges::make\_heap](make_heap "cpp/algorithm/ranges/make heap") (C++20) | creates a max heap out of a range of elements (niebloid) | | [ranges::pop\_heap](pop_heap "cpp/algorithm/ranges/pop heap") (C++20) | removes the largest element from a max heap (niebloid) | | [ranges::sort\_heap](sort_heap "cpp/algorithm/ranges/sort heap") (C++20) | turns a max heap into a range of elements sorted in ascending order (niebloid) | | [push\_heap](../push_heap "cpp/algorithm/push heap") | adds an element to a max heap (function template) | cpp std::ranges::reverse_copy, std::ranges::reverse_copy_result std::ranges::reverse\_copy, std::ranges::reverse\_copy\_result ============================================================== | Defined in header `[<algorithm>](../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | Call signature | | | | ``` template< std::bidirectional_iterator I, std::sentinel_for<I> S, std::weakly_incrementable O > requires std::indirectly_copyable<I, O> constexpr reverse_copy_result<I, O> reverse_copy( I first, S last, O result ); ``` | (1) | (since C++20) | | ``` template< ranges::bidirectional_range R, std::weakly_incrementable O > requires std::indirectly_copyable<ranges::iterator_t<R>, O> constexpr reverse_copy_result<ranges::borrowed_iterator_t<R>, O> reverse_copy( R&& r, O result ); ``` | (2) | (since C++20) | | Helper types | | | | ``` template< class I, class O > using reverse_copy_result = ranges::in_out_result<I, O>; ``` | (3) | (since C++20) | 1) Copies the elements from the source range `[first, last)` to the destination range `[result, result + N)`, where `N` is `[ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(first, last)`, in such a way that the elements in the new range are in reverse order. Behaves as if by executing the assignment `*(result + N - 1 - i) = *(first + i)` once for each integer `i` in `[0, N)`. The behavior is undefined if the source and destination ranges overlap. 2) Same as (1), but uses `r` as the source range, as if using `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r)` as `first` and `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r)` as `last`. The function-like entities described on this page are *niebloids*, that is: * Explicit template argument lists cannot be specified when calling any of them. * None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl"). * When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited. In practice, they may be implemented as function objects, or with special compiler extensions. ### Parameters | | | | | --- | --- | --- | | first, last | - | the range of elements to copy | | r | - | the range of elements to copy | | result | - | the beginning of the destination range. | ### Return value `{last, result + N}`. ### Complexity Exactly `N` assignments. ### Notes Implementations (e.g. [MSVC STL](https://github.com/microsoft/STL/blob/main/stl/src/vector_algorithms.cpp)) may enable vectorization when the both iterator types model [`contiguous_iterator`](../../iterator/contiguous_iterator "cpp/iterator/contiguous iterator") and have the same value type, and the value type is [TriviallyCopyable](../../named_req/triviallycopyable "cpp/named req/TriviallyCopyable"). ### Possible implementation See also the implementations in [MSVC STL](https://github.com/microsoft/STL/blob/472161105d596192194d4715ccad307c6c163b4a/stl/inc/algorithm#L4245-L4323) and [libstdc++](https://github.com/gcc-mirror/gcc/blob/14d8a5ae472ca5743016f37da2dd4770d83dea21/libstdc%2B%2B-v3/include/bits/ranges_algo.h#L1330-L1359). | | | --- | | ``` struct reverse_copy_fn { template<std::bidirectional_iterator I, std::sentinel_for<I> S, std::weakly_incrementable O> requires std::indirectly_copyable<I, O> constexpr ranges::reverse_copy_result<I, O> operator() ( I first, S last, O result ) const { auto ret = ranges::next(first, last); for (; last != first; *result = *--last, ++result); return {std::move(ret), std::move(result)}; } template<ranges::bidirectional_range R, std::weakly_incrementable O> requires std::indirectly_copyable<ranges::iterator_t<R>, O> constexpr ranges::reverse_copy_result<ranges::borrowed_iterator_t<R>, O> operator() ( R&& r, O result ) const { return (*this)(ranges::begin(r), ranges::end(r), std::move(result)); } }; inline constexpr reverse_copy_fn reverse_copy{}; ``` | ### Example ``` #include <algorithm> #include <iostream> #include <string> int main() { std::string x{"12345"}, y(x.size(), ' '); std::cout << x << " → "; std::ranges::reverse_copy(x.begin(), x.end(), y.begin()); std::cout << y << " → "; std::ranges::reverse_copy(y, x.begin()); std::cout << x << '\n'; } ``` Output: ``` 12345 → 54321 → 12345 ``` ### See also | | | | --- | --- | | [ranges::reverse](reverse "cpp/algorithm/ranges/reverse") (C++20) | reverses the order of elements in a range (niebloid) | | [reverse\_copy](../reverse_copy "cpp/algorithm/reverse copy") | creates a copy of a range that is reversed (function template) | cpp std::ranges::transform, std::ranges::unary_transform_result, std::ranges::binary_transform_result std::ranges::transform, std::ranges::unary\_transform\_result, std::ranges::binary\_transform\_result ===================================================================================================== | Defined in header `[<algorithm>](../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | Call signature | | | | ``` template< std::input_iterator I, std::sentinel_for<I> S, std::weakly_incrementable O, std::copy_constructible F, class Proj = std::identity > requires std::indirectly_writable<O, std::indirect_result_t<F&, std::projected<I, Proj>>> constexpr unary_transform_result<I, O> transform( I first1, S last1, O result, F op, Proj proj = {} ); ``` | (1) | (since C++20) | | ``` template< ranges::input_range R, std::weakly_incrementable O, std::copy_constructible F, class Proj = std::identity > requires std::indirectly_writable<O, std::indirect_result_t<F&, std::projected<ranges::iterator_t<R>, Proj>>> constexpr unary_transform_result<ranges::borrowed_iterator_t<R>, O> transform( R&& r, O result, F op, Proj proj = {} ); ``` | (2) | (since C++20) | | ``` template< std::input_iterator I1, std::sentinel_for<I1> S1, std::input_iterator I2, std::sentinel_for<I2> S2, std::weakly_incrementable O, std::copy_constructible F, class Proj1 = std::identity, class Proj2 = std::identity > requires std::indirectly_writable<O, std::indirect_result_t<F&, std::projected<I1, Proj1>, std::projected<I2, Proj2>>> constexpr binary_transform_result<I1, I2, O> transform( I1 first1, S1 last1, I2 first2, S2 last2, O result, F binary_op, Proj1 proj1 = {}, Proj2 proj2 = {} ); ``` | (3) | (since C++20) | | ``` template< std::input_range R1, std::input_range R2, std::weakly_incrementable O, std::copy_constructible F, class Proj1 = std::identity, class Proj2 = std::identity > requires std::indirectly_writable<O, std::indirect_result_t<F&, std::projected<ranges::iterator_t<R1>, Proj1>, std::projected<ranges::iterator_t<R2>, Proj2>>> constexpr binary_transform_result<ranges::borrowed_iterator_t<R1>, ranges::borrowed_iterator_t<R2>, O> transform( R1&& r1, R2&& r2, O result, F binary_op, Proj1 proj1 = {}, Proj2 proj2 = {} ); ``` | (4) | (since C++20) | | Helper types | | | | ``` template < class I, class O > using unary_transform_result = ranges::in_out_result<I, O>; ``` | (5) | (since C++20) | | ``` template < class I1, class I2, class O > using binary_transform_result = ranges::in_in_out_result<I1, I2, O>; ``` | (6) | (since C++20) | Applies the given function to a range and stores the result in another range, beginning at `result`. 1) The unary operation `op` is applied to the range defined by `[first1, last1)` (after projecting with the projection `proj`). 2) Same as (1), but uses `r` as the source range, as if using `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r)` as `first` and `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r)` as `last`. 3) The binary operation `binary_op` is applied to pairs of elements from two ranges: one defined by `[first1, last1)` and the other defined by `[first2, last2)` (after respectively projecting with the projections `proj1` and `proj2`). 4) Same as (3), but uses `r1` as the first source range, as if using `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r1)` as `first1` and `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r1)` as `last1`, and similarly for `r2`. The function-like entities described on this page are *niebloids*, that is: * Explicit template argument lists cannot be specified when calling any of them. * None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl"). * When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited. In practice, they may be implemented as function objects, or with special compiler extensions. ### Parameters | | | | | --- | --- | --- | | first1, last1 | - | the first range of elements to transform | | r, r1 | - | the first range of elements to transform | | first2, last2 | - | the second range of elements to transform | | r2 | - | the second range of elements to transform | | result | - | the beginning of the destination range, may be equal to `first1` or `first2` | | op, binary\_op | - | operation to apply to the projected element(s) | | proj1 | - | projection to apply to the elements in the first range | | proj2 | - | projection to apply to the elements in the second range. | ### Return value 1-2) a `unary_transform_result` contains an input iterator equal to `last` and an output iterator to the element past the last element transformed. 3-4) a `binary_transform_result` contains input iterators to last transformed elements from ranges `[first1, last1)` and `[first2, last2)` as `in1` and `in2` respectively, and the output iterator to the element past the last element transformed as `out`. ### Complexity 1,2) Exactly `[ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(first1, last1)` applications of `op` and `proj`. 3,4) Exactly `[ranges::min](http://en.cppreference.com/w/cpp/algorithm/ranges/min)([ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(first1, last1), [ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(first2, last2))` applications of `binary_op` and projections. ### Possible implementation | | | --- | | ``` struct transform_fn { template< std::input_iterator I, std::sentinel_for<I> S, std::weakly_incrementable O, std::copy_constructible F, class Proj = std::identity > requires std::indirectly_writable<O, std::indirect_result_t<F&, std::projected<I, Proj>>> constexpr ranges::unary_transform_result<I, O> operator()( I first1, S last1, O result, F op, Proj proj = {} ) const { for (; first1 != last1; ++first1, (void)++result) { *result = std::invoke(op, std::invoke(proj, *first1)); } return {first1, result}; } template< ranges::input_range R, std::weakly_incrementable O, std::copy_constructible F, class Proj = std::identity > requires std::indirectly_writable<O, std::indirect_result_t<F&, std::projected<ranges::iterator_t<R>, Proj>>> constexpr ranges::unary_transform_result<ranges::borrowed_iterator_t<R>, O> operator()( R&& r, O result, F op, Proj proj = {} ) const { return (*this)(ranges::begin(r), ranges::end(r), result, std::ref(op), std::ref(proj)); } template< std::input_iterator I1, std::sentinel_for<I1> S1, std::input_iterator I2, std::sentinel_for<I2> S2, std::weakly_incrementable O, std::copy_constructible F, class Proj1 = std::identity, class Proj2 = std::identity > requires std::indirectly_writable<O, std::indirect_result_t<F&, std::projected<I1, Proj1>, std::projected<I2, Proj2>>> constexpr ranges::binary_transform_result<I1, I2, O> operator()( I1 first1, S1 last1, I2 first2, S2 last2, O result, F binary_op, Proj1 proj1 = {}, Proj2 proj2 = {} ) const { for (; first1 != last1 && first2 != last2; ++first1, (void)++first2, (void)++result) { *result = std::invoke(binary_op, std::invoke(proj1, *first1), std::invoke(proj2, *first2)); } return {first1, first2, result}; } template< ranges::input_range R1, ranges::input_range R2, std::weakly_incrementable O, std::copy_constructible F, class Proj1 = std::identity, class Proj2 = std::identity > requires std::indirectly_writable<O, std::indirect_result_t<F&, std::projected<ranges::iterator_t<R1>, Proj1>, std::projected<ranges::iterator_t<R2>, Proj2>>> constexpr ranges::binary_transform_result<ranges::borrowed_iterator_t<R1>, ranges::borrowed_iterator_t<R2>, O> operator()( R1&& r1, R2&& r2, O result, F binary_op, Proj1 proj1 = {}, Proj2 proj2 = {} ) const { return (*this)(ranges::begin(r1), ranges::end(r1), ranges::begin(r2), ranges::end(r2), result, std::ref(binary_op), std::ref(proj1), std::ref(proj2)); } }; inline constexpr transform_fn transform; ``` | ### Notes `ranges::transform` does not guarantee in-order application of `op` or `binary_op`. To apply a function to a sequence in-order or to apply a function that modifies the elements of a sequence, use `[ranges::for\_each](for_each "cpp/algorithm/ranges/for each")`. ### Example The following code uses `ranges::transform` to convert a string in place to uppercase using the `std::toupper` function and then transforms each `char` to its ordinal value. Then `ranges::transform` with a projection is used to transform elements of `[std::vector](http://en.cppreference.com/w/cpp/container/vector)<Foo>` into chars to fill a `[std::string](../../string/basic_string "cpp/string/basic string")`. ``` #include <algorithm> #include <cctype> #include <functional> #include <iostream> #include <string> #include <vector> int main() { std::string s("hello"); namespace ranges = std::ranges; ranges::transform(s.begin(), s.end(), s.begin(), [](unsigned char c) -> unsigned char { return std::toupper(c); }); std::vector<std::size_t> ordinals; ranges::transform(s, std::back_inserter(ordinals), [](unsigned char c) -> std::size_t { return c; }); std::cout << s << ':'; for (auto ord : ordinals) { std::cout << ' ' << ord; } ranges::transform(ordinals, ordinals, ordinals.begin(), std::plus{}); std::cout << '\n'; for (auto ord : ordinals) { std::cout << ord << ' '; } std::cout << '\n'; struct Foo { char bar; }; const std::vector<Foo> f = { {'h'},{'e'},{'l'},{'l'},{'o'} }; std::string bar; ranges::transform(f, std::back_inserter(bar), &Foo::bar); std::cout << bar << '\n'; } ``` Output: ``` HELLO: 72 69 76 76 79 144 138 152 152 158 hello ``` ### See also | | | | --- | --- | | [ranges::for\_each](for_each "cpp/algorithm/ranges/for each") (C++20) | applies a function to a range of elements (niebloid) | | [ranges::transform\_viewviews::transform](../../ranges/transform_view "cpp/ranges/transform view") (C++20) | a [`view`](../../ranges/view "cpp/ranges/view") of a sequence that applies a transformation function to each element (class template) (range adaptor object) | | [transform](../transform "cpp/algorithm/transform") | applies a function to a range of elements, storing results in a destination range (function template) |
programming_docs
cpp std::ranges::shuffle std::ranges::shuffle ==================== | Defined in header `[<algorithm>](../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | Call signature | | | | ``` template< std::random_access_iterator I, std::sentinel_for<I> S, class Gen > requires std::permutable<I> && std::uniform_random_bit_generator<std::remove_reference_t<Gen>> I shuffle( I first, S last, Gen&& gen ); ``` | (1) | (since C++20) | | ``` template< ranges::random_access_range R, class Gen > requires std::permutable<ranges::iterator_t<R>> && std::uniform_random_bit_generator<std::remove_reference_t<Gen>> ranges::borrowed_iterator_t<R> shuffle( R&& r, Gen&& gen ); ``` | (2) | (since C++20) | 1) Reorders the elements in the given range `[first, last)` such that each possible permutation of those elements has equal probability of appearance. 2) Same as (1), but uses `r` as the range, as if using `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r)` as `first` and `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r)` as `last`. The function-like entities described on this page are *niebloids*, that is: * Explicit template argument lists cannot be specified when calling any of them. * None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl"). * When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited. In practice, they may be implemented as function objects, or with special compiler extensions. ### Parameters | | | | | --- | --- | --- | | first, last | - | the range of elements to shuffle randomly | | r | - | the range of elements to shuffle randomly | | gen | - | the random number generator | ### Return value An iterator equal to `last`. ### Complexity Exactly `(last - first) - 1` swaps. ### Possible implementation | | | --- | | ``` struct shuffle_fn { template<std::random_access_iterator I, std::sentinel_for<I> S, class Gen> requires std::permutable<I> && std::uniform_random_bit_generator<std::remove_reference_t<Gen>> I operator()( I first, S last, Gen&& gen ) const { using diff_t = std::iter_difference_t<I>; using distr_t = std::uniform_int_distribution<diff_t>; using param_t = typename distr_t::param_type; distr_t D; const auto n{ last - first }; for (diff_t i{1}; i < n; ++i) { ranges::iter_swap(first + i, first + D(gen, param_t(0, i))); } return ranges::next(first, last); } template<ranges::random_access_range R, class Gen> requires std::permutable<ranges::iterator_t<R>> && std::uniform_random_bit_generator<std::remove_reference_t<Gen>> ranges::borrowed_iterator_t<R> operator()( R&& r, Gen&& gen ) const { return (*this)(ranges::begin(r), ranges::end(r), std::forward<Gen>(gen)); } }; inline constexpr shuffle_fn shuffle{}; ``` | ### Example ``` #include <algorithm> #include <array> #include <iostream> #include <random> void print(const auto& a) { for (const auto e : a) { std::cout << e << ' '; } std::cout << "\n"; } int main() { std::array a{'A', 'B', 'C', 'D', 'E', 'F'}; print(a); std::random_device rd; std::mt19937 gen{rd()}; for (int i{}; i != 3; ++i) { std::ranges::shuffle(a, gen); print(a); } } ``` Possible output: ``` A B C D E F F E A C D B E C B F A D B A E C F D ``` ### See also | | | | --- | --- | | [ranges::next\_permutation](next_permutation "cpp/algorithm/ranges/next permutation") (C++20) | generates the next greater lexicographic permutation of a range of elements (niebloid) | | [ranges::prev\_permutation](prev_permutation "cpp/algorithm/ranges/prev permutation") (C++20) | generates the next smaller lexicographic permutation of a range of elements (niebloid) | | [random\_shuffleshuffle](../random_shuffle "cpp/algorithm/random shuffle") (until C++17)(C++11) | randomly re-orders elements in a range (function template) | cpp std::ranges::lexicographical_compare std::ranges::lexicographical\_compare ===================================== | Defined in header `[<algorithm>](../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | Call signature | | | | ``` template< std::input_iterator I1, std::sentinel_for<I1> S1, std::input_iterator I2, std::sentinel_for<I2> S2, class Proj1 = std::identity, class Proj2 = std::identity, std::indirect_strict_weak_order< std::projected<I1, Proj1>, std::projected<I2, Proj2>> Comp = ranges::less > constexpr bool lexicographical_compare( I1 first1, S1 last1, I2 first2, S2 last2, Comp comp = {}, Proj1 proj1 = {}, Proj2 proj2 = {} ); ``` | (1) | (since C++20) | | ``` template< ranges::input_range R1, ranges::input_range R2, class Proj1 = std::identity, class Proj2 = std::identity, std::indirect_strict_weak_order< std::projected<ranges::iterator_t<R1>, Proj1>, std::projected<ranges::iterator_t<R2>, Proj2>> Comp = ranges::less > constexpr bool lexicographical_compare( R1&& r1, R2&& r2, Comp comp = {}, Proj1 proj1 = {}, Proj2 proj2 = {} ); ``` | (2) | (since C++20) | Checks if the first range `[first1, last1)` is lexicographically *less* than the second range `[first2, last2)`. 1) Elements are compared using the given binary comparison function `comp`. 2) Same as (1), but uses `r` as the source range, as if using `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r)` as `first` and `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r)` as `last`. Lexicographical comparison is a operation with the following properties: * Two ranges are compared element by element. * The first mismatching element defines which range is lexicographically *less* or *greater* than the other. * If one range is a prefix of another, the shorter range is lexicographically *less* than the other. * If two ranges have equivalent elements and are of the same length, then the ranges are lexicographically *equal*. * An empty range is lexicographically *less* than any non-empty range. * Two empty ranges are lexicographically *equal*. The function-like entities described on this page are *niebloids*, that is: * Explicit template argument lists cannot be specified when calling any of them. * None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl"). * When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited. In practice, they may be implemented as function objects, or with special compiler extensions. ### Parameters | | | | | --- | --- | --- | | first1, last1 | - | the first range of elements to examine | | r1 | - | the first range of elements to examine | | first2, last2 | - | the second range of elements to examine | | r2 | - | the second range of elements to examine | | comp | - | comparison function to apply to the projected elements | | proj1 | - | projection to apply to the first range of elements | | proj2 | - | projection to apply to the second range of elements | ### Return value `true` if the first range is lexicographically *less* than the second. ### Complexity At most 2·min(N1, N2) applications of the comparison and corresponding projections, where `N1 = [ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(first1, last1)` and `N2 = [ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(first2, last2)`. ### Possible implementation | | | --- | | ``` struct lexicographical_compare_fn { template<std::input_iterator I1, std::sentinel_for<I1> S1, std::input_iterator I2, std::sentinel_for<I2> S2, class Proj1 = std::identity, class Proj2 = std::identity, std::indirect_strict_weak_order< std::projected<I1, Proj1>, std::projected<I2, Proj2>> Comp = ranges::less> constexpr bool operator()(I1 first1, S1 last1, I2 first2, S2 last2, Comp comp = {}, Proj1 proj1 = {}, Proj2 proj2 = {}) const { for ( ; (first1 != last1) && (first2 != last2); ++first1, (void) ++first2 ) { if (std::invoke(comp, std::invoke(proj1, *first1), std::invoke(proj2, *first2))) { return true; } if (std::invoke(comp, std::invoke(proj2, *first2), std::invoke(proj1, *first1))) { return false; } } return (first1 == last1) && (first2 != last2); } template< ranges::input_range R1, ranges::input_range R2, class Proj1 = std::identity, class Proj2 = std::identity, std::indirect_strict_weak_order< std::projected<ranges::iterator_t<R1>, Proj1>, std::projected<ranges::iterator_t<R2>, Proj2>> Comp = ranges::less > constexpr bool operator()(R1&& r1, R2&& r2, Comp comp = {}, Proj1 proj1 = {}, Proj2 proj2 = {}) const { return (*this)(ranges::begin(r1), ranges::end(r1), ranges::begin(r2), ranges::end(r2), std::ref(comp), std::ref(proj1), std::ref(proj2)); } }; inline constexpr lexicographical_compare_fn lexicographical_compare; ``` | ### Example ``` #include <algorithm> #include <iterator> #include <iostream> #include <vector> #include <random> int main() { std::vector<char> v1 {'a', 'b', 'c', 'd'}; std::vector<char> v2 {'a', 'b', 'c', 'd'}; namespace ranges = std::ranges; auto os = std::ostream_iterator<char>(std::cout, " "); std::mt19937 g{std::random_device{}()}; while (!ranges::lexicographical_compare(v1, v2)) { ranges::copy(v1, os); std::cout << ">= "; ranges::copy(v2, os); std::cout << '\n'; ranges::shuffle(v1, g); ranges::shuffle(v2, g); } ranges::copy(v1, os); std::cout << "< "; ranges::copy(v2, os); std::cout << '\n'; } ``` Possible output: ``` a b c d >= a b c d d a b c >= c b d a b d a c >= a d c b a c d b < c d a b ``` ### See also | | | | --- | --- | | [ranges::equal](equal "cpp/algorithm/ranges/equal") (C++20) | determines if two sets of elements are the same (niebloid) | | [lexicographical\_compare](../lexicographical_compare "cpp/algorithm/lexicographical compare") | returns true if one range is lexicographically less than another (function template) | cpp std::ranges::minmax, std::ranges::minmax_result std::ranges::minmax, std::ranges::minmax\_result ================================================ | Defined in header `[<algorithm>](../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | Call signature | | | | ``` template< class T, class Proj = std::identity, std::indirect_strict_weak_order< std::projected<const T*, Proj>> Comp = ranges::less > constexpr ranges::minmax_result<const T&> minmax( const T& a, const T& b, Comp comp = {}, Proj proj = {} ); ``` | (1) | (since C++20) | | ``` template< std::copyable T, class Proj = std::identity, std::indirect_strict_weak_order< std::projected<const T*, Proj>> Comp = ranges::less > constexpr ranges::minmax_result<T> minmax( std::initializer_list<T> r, Comp comp = {}, Proj proj = {} ); ``` | (2) | (since C++20) | | ``` template< ranges::input_range R, class Proj = std::identity, std::indirect_strict_weak_order< std::projected<ranges::iterator_t<R>, Proj>> Comp = ranges::less > requires std::indirectly_copyable_storable<ranges::iterator_t<R>, ranges::range_value_t<R>*> constexpr ranges::minmax_result<ranges::range_value_t<R>> minmax( R&& r, Comp comp = {}, Proj proj = {} ); ``` | (3) | (since C++20) | | Helper types | | | | ``` template< class T > using minmax_result = ranges::min_max_result<T>; ``` | (4) | (since C++20) | Returns the smallest and the greatest of the given projected values. 1) Returns references to the smaller and the greater of `a` and `b`. 2) Returns the smallest and the greatest of the values in the initializer list `r`. 3) Returns the smallest and the greatest of the values in the range `r`. The function-like entities described on this page are *niebloids*, that is: * Explicit template argument lists cannot be specified when calling any of them. * None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl"). * When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited. In practice, they may be implemented as function objects, or with special compiler extensions. ### Parameters | | | | | --- | --- | --- | | a, b | - | the values to compare | | r | - | a non-empty range of values to compare | | comp | - | comparison to apply to the projected elements | | proj | - | projection to apply to the elements. | ### Return value 1) `{b, a}` if, according to their respective projected value, `b` is smaller than `a`; otherwise it returns `{a, b}`. 2-3) `{s, l}`, where `s` and `l` are respectively the smallest and largest values in `r`, according to their projected value. If several values are equivalent to the smallest and largest, returns the leftmost smallest value, and the rightmost largest value. If the range is empty (as determined by `[ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(r)`), the behavior is undefined. ### Complexity 1) Exactly one comparison and two applications of the projection. 2-3) At most `3 / 2 \* [ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(r)` comparisons and twice as many applications of the projection. ### Possible implementation | | | --- | | ``` struct minmax_fn { template<class T, class Proj = std::identity, std::indirect_strict_weak_order< std::projected<const T*, Proj>> Comp = ranges::less> constexpr ranges::minmax_result<const T&> operator()( const T& a, const T& b, Comp comp = {}, Proj proj = {}) const { if (std::invoke(comp, std::invoke(proj, b), std::invoke(proj, a))) { return {b, a}; } return {a, b}; } template<std::copyable T, class Proj = std::identity, std::indirect_strict_weak_order< std::projected<const T*, Proj>> Comp = ranges::less> constexpr ranges::minmax_result<T> operator()( std::initializer_list<T> r, Comp comp = {}, Proj proj = {}) const { auto result = ranges::minmax_element(r, std::ref(comp), std::ref(proj)); return {*result.min, *result.max}; } template<ranges::input_range R, class Proj = std::identity, std::indirect_strict_weak_order< std::projected<ranges::iterator_t<R>, Proj>> Comp = ranges::less> requires std::indirectly_copyable_storable<ranges::iterator_t<R>, ranges::range_value_t<R>*> constexpr ranges::minmax_result<ranges::range_value_t<R>> operator()( R&& r, Comp comp = {}, Proj proj = {}) const { auto result = ranges::minmax_element(r, std::ref(comp), std::ref(proj)); return {std::move(*result.min), std::move(*result.max)}; } }; inline constexpr minmax_fn minmax; ``` | ### Notes For overload (1), if one of the parameters is a temporary, the reference returned becomes a dangling reference at the end of the full expression that contains the call to `minmax`: ``` int n = 1; auto p = std::ranges::minmax(n, n+1); int m = p.min; // ok int x = p.max; // undefined behavior // Note that structured bindings have the same issue auto [mm, xx] = std::ranges::minmax(n, n+1); xx; // undefined behavior ``` ### Example ``` #include <algorithm> #include <iostream> #include <random> #include <array> int main() { namespace ranges = std::ranges; constexpr std::array v{3, 1, 4, 1, 5, 9, 2, 6, 5}; std::random_device rd; std::mt19937_64 generator(rd()); std::uniform_int_distribution<> distribution(0, ranges::distance(v)); // [0..9] // auto bounds = ranges::minmax(distribution(generator), distribution(generator)); // UB: dangling references: bounds.min and bounds.max have the type `const int&`. const int x1 = distribution(generator); const int x2 = distribution(generator); auto bounds = ranges::minmax(x1, x2); // OK: got references to lvalues x1 and x2 std::cout << "v[" << bounds.min << ":" << bounds.max << "]: "; for (int i = bounds.min; i < bounds.max; ++i) { std::cout << v[i] << ' '; } std::cout << '\n'; auto [min, max] = ranges::minmax(v); std::cout << "smallest: " << min << ", " << "largest: " << max << '\n'; } ``` Possible output: ``` v[3:9]: 1 5 9 2 6 5 smallest: 1, largest: 9 ``` ### See also | | | | --- | --- | | [ranges::min](min "cpp/algorithm/ranges/min") (C++20) | returns the smaller of the given values (niebloid) | | [ranges::max](max "cpp/algorithm/ranges/max") (C++20) | returns the greater of the given values (niebloid) | | [ranges::minmax\_element](minmax_element "cpp/algorithm/ranges/minmax element") (C++20) | returns the smallest and the largest elements in a range (niebloid) | | [ranges::clamp](clamp "cpp/algorithm/ranges/clamp") (C++20) | clamps a value between a pair of boundary values (niebloid) | | [minmax](../minmax "cpp/algorithm/minmax") (C++11) | returns the smaller and larger of two elements (function template) | cpp std::ranges::partition_copy, std::ranges::partition_copy_result std::ranges::partition\_copy, std::ranges::partition\_copy\_result ================================================================== | Defined in header `[<algorithm>](../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | Call signature | | | | ``` template< std::input_iterator I, std::sentinel_for<I> S, std::weakly_incrementable O1, std::weakly_incrementable O2, class Proj = std::identity, std::indirect_unary_predicate<std::projected<I, Proj>> Pred > requires std::indirectly_copyable<I, O1> && std::indirectly_copyable<I, O2> constexpr partition_copy_result<I, O1, O2> partition_copy( I first, S last, O1 out_true, O2 out_false, Pred pred, Proj proj = {} ); ``` | (1) | (since C++20) | | ``` template< ranges::input_range R, std::weakly_incrementable O1, std::weakly_incrementable O2, class Proj = std::identity, std::indirect_unary_predicate<std::projected<iterator_t<R>, Proj>> Pred > requires std::indirectly_copyable<ranges::iterator_t<R>, O1> && std::indirectly_copyable<ranges::iterator_t<R>, O2> constexpr partition_copy_result<ranges::borrowed_iterator_t<R>, O1, O2> partition_copy( R&& r, O1 out_true, O2 out_false, Pred pred, Proj proj = {} ); ``` | (2) | (since C++20) | | Helper types | | | | ``` template<class I, class O1, class O2> using partition_copy_result = ranges::in_out_out_result<I, O1, O2>; ``` | (3) | (since C++20) | 1) Copies the elements from the input range `[first, last)` to two different output ranges depending on the value returned by the predicate `pred`. The elements that satisfy the predicate `pred` after projection by `proj` are copied to the range beginning at `out_true`. The rest of the elements are copied to the range beginning at `out_false`. The behavior is undefined if the input range overlaps either of the output ranges. 2) Same as (1), but uses `r` as the source range, as if using `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r)` as `first`, and `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r)` as `last`. The function-like entities described on this page are *niebloids*, that is: * Explicit template argument lists cannot be specified when calling any of them. * None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl"). * When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited. In practice, they may be implemented as function objects, or with special compiler extensions. ### Parameters | | | | | --- | --- | --- | | first, last | - | the input range of elements to copy from | | r | - | the input range of elements to copy from | | out\_true | - | the beginning of the output range for the elements that satisfy `pred` | | out\_false | - | the beginning of the output range for the elements that do not satisfy `pred` | | pred | - | predicate to apply to the projected elements | | proj | - | projection to apply to the elements | ### Return value `{last, o1, o2}`, where `o1` and `o2` are the ends of the output ranges respectively, after the copying is complete. ### Complexity Exactly `[ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(first, last)` applications of the corresponding predicate `comp` and any projection `proj`. ### Possible implementation | | | --- | | ``` struct partition_copy_fn { template <std::input_iterator I, std::sentinel_for<I> S, std::weakly_incrementable O1, std::weakly_incrementable O2, class Proj = std::identity, std::indirect_unary_predicate< std::projected<I, Proj>> Pred> requires std::indirectly_copyable<I, O1> && std::indirectly_copyable<I, O2> constexpr ranges::partition_copy_result<I, O1, O2> operator()( I first, S last, O1 out_true, O2 out_false, Pred pred, Proj proj = {} ) const { for (; first != last; ++first) if (!!std::invoke(pred, std::invoke(proj, *first))) *out_true = *first, ++out_true; else *out_false = *first, ++out_false; return {std::move(first), std::move(out_true), std::move(out_false)}; } template<ranges::input_range R, std::weakly_incrementable O1, std::weakly_incrementable O2, class Proj = std::identity, std::indirect_unary_predicate<std::projected<iterator_t<R>, Proj>> Pred> requires std::indirectly_copyable<ranges::iterator_t<R>, O1> && std::indirectly_copyable<ranges::iterator_t<R>, O2> constexpr ranges::partition_copy_result<ranges::borrowed_iterator_t<R>, O1, O2> operator()( R&& r, O1 out_true, O2 out_false, Pred pred, Proj proj = {} ) const { return (*this)(ranges::begin(r), ranges::end(r), std::move(out_true), std::move(out_false), std::move(pred), std::move(proj)); } }; inline constexpr partition_copy_fn partition_copy{}; ``` | ### Example ``` #include <algorithm> #include <cctype> #include <iostream> #include <vector> #include <iterator> int main() { const auto in = {'N', '3', 'U', 'M', '1', 'B', '4', 'E', '1', '5', 'R', '9'}; std::vector<int> o1(size(in)), o2(size(in)); auto pred = [](char c){ return std::isalpha(c); }; auto ret = std::ranges::partition_copy(in, o1.begin(), o2.begin(), pred); std::ostream_iterator<char> cout {std::cout, " "}; std::cout << "in = "; std::ranges::copy(in, cout); std::cout << "\no1 = "; std::copy(o1.begin(), ret.out1, cout); std::cout << "\no2 = "; std::copy(o2.begin(), ret.out2, cout); std::cout << '\n'; } ``` Output: ``` in = N 3 U M 1 B 4 E 1 5 R 9 o1 = N U M B E R o2 = 3 1 4 1 5 9 ``` ### See also | | | | --- | --- | | [ranges::partition](partition "cpp/algorithm/ranges/partition") (C++20) | divides a range of elements into two groups (niebloid) | | [ranges::stable\_partition](stable_partition "cpp/algorithm/ranges/stable partition") (C++20) | divides elements into two groups while preserving their relative order (niebloid) | | [ranges::copyranges::copy\_if](copy "cpp/algorithm/ranges/copy") (C++20)(C++20) | copies a range of elements to a new location (niebloid) | | [ranges::remove\_copyranges::remove\_copy\_if](remove_copy "cpp/algorithm/ranges/remove copy") (C++20)(C++20) | copies a range of elements omitting those that satisfy specific criteria (niebloid) | | [partition\_copy](../partition_copy "cpp/algorithm/partition copy") (C++11) | copies a range dividing the elements into two groups (function template) |
programming_docs
cpp std::ranges::set_symmetric_difference, std::ranges::set_symmetric_difference_result std::ranges::set\_symmetric\_difference, std::ranges::set\_symmetric\_difference\_result ======================================================================================== | Defined in header `[<algorithm>](../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | Call signature | | | | ``` template< std::input_iterator I1, std::sentinel_for<I1> S1, std::input_iterator I2, std::sentinel_for<I2> S2, std::weakly_incrementable O, class Comp = ranges::less, class Proj1 = std::identity, class Proj2 = std::identity > requires std::mergeable<I1, I2, O, Comp, Proj1, Proj2> constexpr set_symmetric_difference_result<I1, I2, O> set_symmetric_difference( I1 first1, S1 last1, I2 first2, S2 last2, O result, Comp comp = {}, Proj1 proj1 = {}, Proj2 proj2 = {} ); ``` | (1) | (since C++20) | | ``` template< ranges::input_range R1, ranges::input_range R2, std::weakly_incrementable O, class Comp = ranges::less, class Proj1 = std::identity, class Proj2 = std::identity > requires std::mergeable<ranges::iterator_t<R1>, ranges::iterator_t<R2>, O, Comp, Proj1, Proj2> constexpr set_symmetric_difference_result<ranges::borrowed_iterator_t<R1>, ranges::borrowed_iterator_t<R2>, O> set_symmetric_difference( R1&& r1, R2&& r2, O result, Comp comp = {}, Proj1 proj1 = {}, Proj2 proj2 = {} ); ``` | (2) | (since C++20) | | Helper types | | | | ``` template<class I1, class I2, class O> using set_symmetric_difference_result = ranges::in_in_out_result<I1, I2, O>; ``` | (3) | (since C++20) | Computes symmetric difference of two sorted ranges: the elements that are found in either of the ranges, but not in both of them are copied to the range beginning at `result`. The resulting range is also sorted. If some element is found `m` times in `[first1, last1)` and `n` times in `[first2, last2)`, it will be copied to `result` exactly `│m-n│` times. If `m>n`, then the last `m-n` of those elements are copied from `[first1,last1)`, otherwise the last `n-m` elements are copied from `[first2,last2)`. The resulting range cannot overlap with either of the input ranges. The behavior is undefined if. * the input ranges are not sorted with respect to `comp` and `proj1` or `proj2`, respectively, or * the resulting range overlaps with either of the input ranges. 1) Elements are compared using the given binary comparison function `comp`. 2) Same as (1), but uses `r1` as the first range and `r2` as the second range, as if using `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r1)` as `first1`, `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r1)` as `last1`, `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r2)` as `first2`, and `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r2)` as `last2`. The function-like entities described on this page are *niebloids*, that is: * Explicit template argument lists cannot be specified when calling any of them. * None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl"). * When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited. In practice, they may be implemented as function objects, or with special compiler extensions. ### Parameters | | | | | --- | --- | --- | | first1, last1 | - | iterator-sentinel pair denoting the first input sorted range | | first2, last2 | - | iterator-sentinel pair denoting the second input sorted range | | r1 | - | the first sorted input range | | r2 | - | the second sorted input range | | result | - | the beginning of the output range | | comp | - | comparison to apply to the projected elements | | proj1 | - | projection to apply to the elements in the first range | | proj2 | - | projection to apply to the elements in the second range | ### Return value `{last1, last2, result_last}`, where `result_last` is the end of the constructed range. ### Complexity At most \(\scriptsize 2\cdot(N\_1+N\_2)-1\)2·(N 1+N 2)-1 comparisons and applications of each projection, where \(\scriptsize N\_1\)N 1 and \(\scriptsize N\_2\)N 2 are `[ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(first1, last1)` and `[ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(first2, last2)`, respectively. ### Possible implementation | | | --- | | ``` struct set_symmetric_difference_fn { template< std::input_iterator I1, std::sentinel_for<I1> S1, std::input_iterator I2, std::sentinel_for<I2> S2, std::weakly_incrementable O, class Comp = ranges::less, class Proj1 = std::identity, class Proj2 = std::identity > requires std::mergeable<I1, I2, O, Comp, Proj1, Proj2> constexpr ranges::set_symmetric_difference_result<I1, I2, O> operator()( I1 first1, S1 last1, I2 first2, S2 last2, O result, Comp comp = {}, Proj1 proj1 = {}, Proj2 proj2 = {} ) const { while (!(first1 == last1 or first2 == last2)) { if (std::invoke(comp, std::invoke(proj1, *first1), std::invoke(proj2, *first2))) { *result = *first1; ++first1; ++result; } else if (std::invoke(comp, std::invoke(proj2, *first2), std::invoke(proj1, *first1))) { *result = *first2; ++first2; ++result; } else { ++first1; ++first2; } } auto res1 {ranges::copy(std::move(first1), std::move(last1), std::move(result))}; auto res2 {ranges::copy(std::move(first2), std::move(last2), std::move(res1.out))}; return {std::move(res1.in), std::move(res2.in), std::move(res2.out)}; } template< ranges::input_range R1, ranges::input_range R2, std::weakly_incrementable O, class Comp = ranges::less, class Proj1 = std::identity, class Proj2 = std::identity > requires std::mergeable<ranges::iterator_t<R1>, ranges::iterator_t<R2>, O, Comp, Proj1, Proj2> constexpr ranges::set_symmetric_difference_result< ranges::borrowed_iterator_t<R1>, ranges::borrowed_iterator_t<R2>, O> operator()( R1&& r1, R2&& r2, O result, Comp comp = {}, Proj1 proj1 = {}, Proj2 proj2 = {} ) const { return (*this)(ranges::begin(r1), ranges::end(r1), ranges::begin(r2), ranges::end(r2), std::move(result), std::move(comp), std::move(proj1), std::move(proj2)); } }; inline constexpr set_symmetric_difference_fn set_symmetric_difference{}; ``` | ### Example ``` #include <algorithm> #include <iostream> #include <iterator> #include <vector> void visualize_this(const auto& v, int min = 1, int max = 9) { for (auto i{min}; i <= max; ++i) { std::ranges::binary_search(v, i) ? std::cout << i : std::cout << '.'; std::cout << ' '; } std::cout << '\n'; } int main() { const auto in1 = {1, 3, 4, 6, 7, 9}; const auto in2 = {1, 4, 5, 6, 9}; std::vector<int> out; std::ranges::set_symmetric_difference(in1, in2, std::back_inserter(out)); visualize_this(in1); visualize_this(in2); visualize_this(out); } ``` Output: ``` 1 . 3 4 . 6 7 . 9 1 . . 4 5 6 . . 9 . . 3 . 5 . 7 . . ``` ### See also | | | | --- | --- | | [ranges::set\_union](set_union "cpp/algorithm/ranges/set union") (C++20) | computes the union of two sets (niebloid) | | [ranges::set\_difference](set_difference "cpp/algorithm/ranges/set difference") (C++20) | computes the difference between two sets (niebloid) | | [ranges::set\_intersection](set_intersection "cpp/algorithm/ranges/set intersection") (C++20) | computes the intersection of two sets (niebloid) | | [ranges::includes](includes "cpp/algorithm/ranges/includes") (C++20) | returns true if one sequence is a subsequence of another (niebloid) | | [set\_symmetric\_difference](../set_symmetric_difference "cpp/algorithm/set symmetric difference") | computes the symmetric difference between two sets (function template) | cpp std::ranges::find_end std::ranges::find\_end ====================== | Defined in header `[<algorithm>](../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | Call signature | | | | ``` template< std::forward_iterator I1, std::sentinel_for<I1> S1, std::forward_iterator I2, std::sentinel_for<I2> S2, class Pred = ranges::equal_to, class Proj1 = std::identity, class Proj2 = std::identity > requires std::indirectly_comparable<I1, I2, Pred, Proj1, Proj2> constexpr ranges::subrange<I1> find_end( I1 first1, S1 last1, I2 first2, S2 last2, Pred pred = {}, Proj1 proj1 = {}, Proj2 proj2 = {} ); ``` | (1) | (since C++20) | | ``` template< ranges::forward_range R1, ranges::forward_range R2, class Pred = ranges::equal_to, class Proj1 = std::identity, class Proj2 = std::identity > requires std::indirectly_comparable<ranges::iterator_t<R1>, ranges::iterator_t<R2>, Pred, Proj1, Proj2> constexpr ranges::borrowed_subrange_t<R1> find_end( R1&& r1, R2&& r2, Pred pred = {}, Proj1 proj1 = {}, Proj2 proj2 = {} ); ``` | (2) | (since C++20) | 1) Searches for the *last* occurrence of the sequence `[first2, last2)` in the range `[first1, last1)`, after projection with `proj1` and `proj2` respectively. The projected elements are compared using the binary predicate `pred`. 2) Same as (1), but uses `r1` as the first source range and `r2` as the second source range, as if using `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r1)` as `first1`, `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r1)` as `last1`, `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r2)` as `first2`, and `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r2)` as `last2`. The function-like entities described on this page are *niebloids*, that is: * Explicit template argument lists cannot be specified when calling any of them. * None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl"). * When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited. In practice, they may be implemented as function objects, or with special compiler extensions. ### Parameters | | | | | --- | --- | --- | | first1, last1 | - | the range of elements to examine (aka *haystack*) | | first2, last2 | - | the range of elements to search for (aka *needle*) | | r1 | - | the range of elements to examine (aka *haystack*) | | r2 | - | the range of elements to search for (aka *needle*) | | pred | - | binary predicate to compare the elements | | proj1 | - | projection to apply to the elements in the first range | | proj2 | - | projection to apply to the elements in the second range | ### Return value 1) `[ranges::subrange](http://en.cppreference.com/w/cpp/ranges/subrange)<I1>{}` value initialized with expression `{i, i + (i == last1 ? 0 : [ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(first2, last2))}` that denotes the last occurrence of the sequence `[first2, last2)` in range `[first1, last1)` (after projections with `proj1` and `proj2`). If `[first2, last2)` is empty or if no such sequence is found, the return value is effectively initialized with `{last1, last1}`. 2) Same as (1), except that the return type is `[ranges::borrowed\_subrange\_t](http://en.cppreference.com/w/cpp/ranges/borrowed_iterator_t)<R1>`. ### Complexity At most \(\scriptsize S\cdot(N-S+1)\)S·(N-S+1) applications of the corresponding predicate and each projection, where \(\scriptsize S\)S is `[ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(first2, last2)` and \(\scriptsize N\)N is `[ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(first1, last1)` for (1), or \(\scriptsize S\)S is `[ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(r2)` and \(\scriptsize N\)N is `[ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(r1)` for (2). ### Notes An implementation can improve efficiency of the search if the input iterators model `[std::bidirectional\_iterator](http://en.cppreference.com/w/cpp/iterator/bidirectional_iterator)` by searching from the end towards the begin. Modelling the `[std::random\_access\_iterator](http://en.cppreference.com/w/cpp/iterator/random_access_iterator)` may improve the comparison speed. All this however does not change the theoretical complexity of the worst case. ### Possible implementation | | | --- | | ``` struct find_end_fn { template<std::forward_iterator I1, std::sentinel_for<I1> S1, std::forward_iterator I2, std::sentinel_for<I2> S2, class Pred = ranges::equal_to, class Proj1 = std::identity, class Proj2 = std::identity> requires std::indirectly_comparable<I1, I2, Pred, Proj1, Proj2> constexpr ranges::subrange<I1> operator()(I1 first1, S1 last1, I2 first2, S2 last2, Pred pred = {}, Proj1 proj1 = {}, Proj2 proj2 = {}) const { if (first2 == last2) { auto last_it = ranges::next(first1, last1); return {last_it, last_it}; } auto result = ranges::search( std::move(first1), last1, first2, last2, pred, proj1, proj2); if (result.empty()) return result; for (;;) { auto new_result = ranges::search( std::next(result.begin()), last1, first2, last2, pred, proj1, proj2); if (new_result.empty()) return result; else result = std::move(new_result); } } template<ranges::forward_range R1, ranges::forward_range R2, class Pred = ranges::equal_to, class Proj1 = std::identity, class Proj2 = std::identity> requires std::indirectly_comparable<ranges::iterator_t<R1>, ranges::iterator_t<R2>, Pred, Proj1, Proj2> constexpr ranges::borrowed_subrange_t<R1> operator()(R1&& r1, R2&& r2, Pred pred = {}, Proj1 proj1 = {}, Proj2 proj2 = {}) const { return (*this)(ranges::begin(r1), ranges::end(r1), ranges::begin(r2), ranges::end(r2), std::move(pred), std::move(proj1), std::move(proj2)); } }; inline constexpr find_end_fn find_end{}; ``` | ### Example ``` #include <algorithm> #include <array> #include <cctype> #include <iostream> #include <ranges> #include <string_view> void print(const auto haystack, const auto needle) { const auto pos = std::distance(haystack.begin(), needle.begin()); std::cout << "In \""; for (const auto c : haystack) { std::cout << c; } std::cout << "\" found \""; for (const auto c : needle) { std::cout << c; } std::cout << "\" at position [" << pos << ".." << pos + needle.size() << ")\n" << std::string(4 + pos, ' ') << std::string(needle.size(), '^') << '\n'; } int main() { using namespace std::literals; constexpr auto secret{"password password word..."sv}; constexpr auto wanted{"password"sv}; constexpr auto found1 = std::ranges::find_end( secret.cbegin(), secret.cend(), wanted.cbegin(), wanted.cend()); print(secret, found1); constexpr auto found2 = std::ranges::find_end(secret, "word"sv); print(secret, found2); const auto found3 = std::ranges::find_end(secret, "ORD"sv, [](const char x, const char y) { // uses a binary predicate return std::tolower(x) == std::tolower(y); }); print(secret, found3); const auto found4 = std::ranges::find_end(secret, "SWORD"sv, {}, {}, [](char c) { return std::tolower(c); }); // projects the 2nd range print(secret, found4); static_assert(std::ranges::find_end(secret, "PASS"sv).empty()); // => not found } ``` Output: ``` In "password password word..." found "password" at position [9..17) ^^^^^^^^ In "password password word..." found "word" at position [18..22) ^^^^ In "password password word..." found "ord" at position [19..22) ^^^ In "password password word..." found "sword" at position [12..17) ^^^^^ ``` ### See also | | | | --- | --- | | [ranges::find\_lastranges::find\_last\_ifranges::find\_last\_if\_not](find_last "cpp/algorithm/ranges/find last") (C++23)(C++23)(C++23) | finds the last element satisfying specific criteria (niebloid) | | [ranges::findranges::find\_ifranges::find\_if\_not](find "cpp/algorithm/ranges/find") (C++20)(C++20)(C++20) | finds the first element satisfying specific criteria (niebloid) | | [ranges::find\_first\_of](find_first_of "cpp/algorithm/ranges/find first of") (C++20) | searches for any one of a set of elements (niebloid) | | [ranges::adjacent\_find](adjacent_find "cpp/algorithm/ranges/adjacent find") (C++20) | finds the first two adjacent items that are equal (or satisfy a given predicate) (niebloid) | | [ranges::search](search "cpp/algorithm/ranges/search") (C++20) | searches for a range of elements (niebloid) | | [ranges::search\_n](search_n "cpp/algorithm/ranges/search n") (C++20) | searches for a number consecutive copies of an element in a range (niebloid) | | [find\_end](../find_end "cpp/algorithm/find end") | finds the last sequence of elements in a certain range (function template) | cpp std::ranges::sample std::ranges::sample =================== | Defined in header `[<algorithm>](../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | Call signature | | | | ``` template< std::input_iterator I, std::sentinel_for<I> S, std::weakly_incrementable O, class Gen > requires (std::forward_iterator<I> or std::random_access_iterator<O>) && std::indirectly_copyable<I, O> && std::uniform_random_bit_generator<std::remove_reference_t<Gen>> O sample( I first, S last, O out, std::iter_difference_t<I> n, Gen&& gen ); ``` | (1) | (since C++20) | | ``` template< ranges::input_range R, std::weakly_incrementable O, class Gen > requires (ranges::forward_range<R> || std::random_access_iterator<O>) && std::indirectly_copyable<ranges::iterator_t<R>, O> && std::uniform_random_bit_generator<std::remove_reference_t<Gen>> O sample( R&& r, O out, ranges::range_difference_t<R> n, Gen&& gen ); ``` | (2) | (since C++20) | 1) Selects `M = min(n, last - first)` elements from the sequence `[first, last)` (without replacement) such that each possible *sample* has equal probability of appearance, and writes those selected elements into the range beginning at `out`. The algorithm is *stable* (preserves the relative order of the selected elements) only if `I` models `[std::forward\_iterator](http://en.cppreference.com/w/cpp/iterator/forward_iterator)`. The behavior is undefined if `out` is in `[first, last)`. 2) Same as (1), but uses `r` as the source range, as if using `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r)` as `first`, and `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r)` as `last`. The function-like entities described on this page are *niebloids*, that is: * Explicit template argument lists cannot be specified when calling any of them. * None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl"). * When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited. In practice, they may be implemented as function objects, or with special compiler extensions. ### Parameters | | | | | --- | --- | --- | | first1, last1 | - | the range from which to make the sampling (*the population*) | | r | - | the range from which to make the sampling (*the population*) | | out | - | the output iterator where the samples are written | | n | - | number of samples to take | | gen | - | the random number generator used as the source of randomness | ### Return value An iterator equal to `out + M`, that is the end of the resulting sample range. ### Complexity *Linear*: 𝓞`(last - first)`. ### Notes This function may implement *selection sampling* or [reservoir sampling](https://en.wikipedia.org/wiki/Reservoir_sampling "enwiki:Reservoir sampling"). ### Possible implementation | | | --- | | ``` struct sample_fn { template<std::input_iterator I, std::sentinel_for<I> S, std::weakly_incrementable O, class Gen> requires (std::forward_iterator<I> or std::random_access_iterator<O>) && std::indirectly_copyable<I, O> && std::uniform_random_bit_generator<std::remove_reference_t<Gen>> O operator()( I first, S last, O out, std::iter_difference_t<I> n, Gen&& gen ) const { using diff_t = std::iter_difference_t<I>; using distrib_t = std::uniform_int_distribution<diff_t>; using param_t = typename distrib_t::param_type; distrib_t D{}; if constexpr (std::forward_iterator<I>) { // this branch preserves "stability" of the sample elements auto rest {ranges::distance(first, last)}; for (n = ranges::min(n, rest); n != 0; ++first) { if (D(gen, param_t(0, --rest)) < n) { *out++ = *first; --n; } } return out; } else { // O is a random_access_iterator diff_t sample_size{}; // copy [first, first + M) elements to "random access" output for (; first != last && sample_size != n; ++first) { out[sample_size++] = *first; } // overwrite some of the copied elements with randomly selected ones for (auto pop_size {sample_size}; first != last; ++first, ++pop_size) { const auto i {D(gen, param_t{0, pop_size})}; if (i < n) out[i] = *first; } return out + sample_size; } } template<ranges::input_range R, std::weakly_incrementable O, class Gen> requires (ranges::forward_range<R> or std::random_access_iterator<O>) && std::indirectly_copyable<ranges::iterator_t<R>, O> && std::uniform_random_bit_generator<std::remove_reference_t<Gen>> O operator()( R&& r, O out, ranges::range_difference_t<R> n, Gen&& gen ) const { return (*this)(ranges::begin(r), ranges::end(r), std::move(out), n, std::forward<Gen>(gen)); } }; inline constexpr sample_fn sample{}; ``` | ### Example ``` #include <algorithm> #include <iomanip> #include <iostream> #include <iterator> #include <random> #include <vector> void print(auto const& rem, auto const& v) { std::cout << rem << " = [" << std::size(v) << "] { "; for (auto const& e : v) { std::cout << e << ' '; } std::cout << "}\n"; } int main() { const auto in = {1, 2, 3, 4, 5, 6}; print("in", in); std::vector<int> out; const int max = in.size() + 2; auto gen = std::mt19937{std::random_device{}()}; for (int n{}; n != max; ++n) { out.clear(); std::ranges::sample(in, std::back_inserter(out), n, gen); std::cout << "n = " << n; print(", out", out); } } ``` Possible output: ``` in = [6] { 1 2 3 4 5 6 } n = 0, out = [0] { } n = 1, out = [1] { 5 } n = 2, out = [2] { 4 5 } n = 3, out = [3] { 2 3 5 } n = 4, out = [4] { 2 4 5 6 } n = 5, out = [5] { 1 2 3 5 6 } n = 6, out = [6] { 1 2 3 4 5 6 } n = 7, out = [6] { 1 2 3 4 5 6 } ``` ### See also | | | | --- | --- | | [ranges::shuffle](shuffle "cpp/algorithm/ranges/shuffle") (C++20) | randomly re-orders elements in a range (niebloid) | | [sample](../sample "cpp/algorithm/sample") (C++17) | selects n random elements from a sequence (function template) |
programming_docs
cpp std::ranges::partial_sort std::ranges::partial\_sort ========================== | Defined in header `[<algorithm>](../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | Call signature | | | | ``` template< std::random_access_iterator I, std::sentinel_for<I> S, class Comp = ranges::less, class Proj = std::identity > requires std::sortable<I, Comp, Proj> constexpr I partial_sort( I first, I middle, S last, Comp comp = {}, Proj proj = {} ); ``` | (1) | (since C++20) | | ``` template< ranges::random_access_range R, class Comp = ranges::less, class Proj = std::identity > requires std::sortable<ranges::iterator_t<R>, Comp, Proj> constexpr ranges::borrowed_iterator_t<R> partial_sort( R&& r, ranges::iterator_t<R> middle, Comp comp = {}, Proj proj = {} ); ``` | (2) | (since C++20) | 1) Rearranges elements such that the range `[first, middle)` contains the sorted `middle - first` smallest elements in the range `[first, last)`. The order of equal elements is *not* guaranteed to be preserved. The order of the remaining elements in the range `[middle, last)` is *unspecified*. The elements are compared using the given binary comparison function `comp` and projected using `proj` function object. 2) Same as (1), but uses `r` as the range, as if using `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r)` as `first` and `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r)` as `last`. The function-like entities described on this page are *niebloids*, that is: * Explicit template argument lists cannot be specified when calling any of them. * None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl"). * When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited. In practice, they may be implemented as function objects, or with special compiler extensions. ### Parameters | | | | | --- | --- | --- | | first, last | - | iterator-sentinel defining the range to sort | | r | - | the range to sort | | middle | - | the iterator defining the last element to be sorted | | comp | - | comparator to apply to the projected elements | | proj | - | projection to apply to the elements | ### Return value An iterator equal to `last`. ### Complexity \(\scriptsize \mathcal{O}(N\cdot\log{(M)})\)𝓞(N·log(M)) comparisons and twice as many projections, where \(\scriptsize N\)N is `[ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(first, last)`, \(\scriptsize M\)M is `[ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(first, middle)`. ### Possible implementation | | | --- | | ``` struct partial_sort_fn { template <std::random_access_iterator I, std::sentinel_for<I> S, class Comp = ranges::less, class Proj = std::identity> requires std::sortable<I, Comp, Proj> constexpr I operator()( I first, I middle, S last, Comp comp = {}, Proj proj = {} ) const { if (first == middle) return ranges::next(first, last); ranges::make_heap(first, middle, comp, proj); auto it {middle}; for (; it != last; ++it) { if (std::invoke(comp, std::invoke(proj, *it), std::invoke(proj, *first))) { ranges::pop_heap(first, middle, comp, proj); ranges::iter_swap(middle - 1, it); ranges::push_heap(first, middle, comp, proj); } } ranges::sort_heap(first, middle, comp, proj); return it; } template <ranges::random_access_range R, class Comp = ranges::less, class Proj = std::identity> requires std::sortable<ranges::iterator_t<R>, Comp, Proj> constexpr ranges::borrowed_iterator_t<R> operator()( R&& r, ranges::iterator_t<R> middle, Comp comp = {}, Proj proj = {} ) const { return (*this)(ranges::begin(r), std::move(middle), ranges::end(r), std::move(comp), std::move(proj)); } }; inline constexpr partial_sort_fn partial_sort{}; ``` | ### Example ``` #include <algorithm> #include <functional> #include <iostream> #include <string> #include <vector> void print(const auto& v) { for (const char e : v) { std::cout << e << ' '; } std::cout << '\n'; } void underscore(int n) { while (n-- > 0) { std::cout << "^ "; } std::cout << '\n'; } int main() { static_assert('A' < 'a'); std::vector<char> v{'x', 'P', 'y', 'C', 'z', 'w', 'P', 'o'}; print(v); std::ranges::partial_sort(v, v.begin() + 3); print(v); underscore(3); static_assert('1' < 'a'); std::string s{"3a1b41c5"}; print(s); std::ranges::partial_sort(s.begin(), s.begin() + 3, s.end(), std::greater{}); print(s); underscore(3); } ``` Output: ``` x P y C z w P o C P P y z x w o ^ ^ ^ 3 a 1 b 4 1 c 5 c b a 1 3 1 4 5 ^ ^ ^ ``` ### See also | | | | --- | --- | | [ranges::partial\_sort\_copy](partial_sort_copy "cpp/algorithm/ranges/partial sort copy") (C++20) | copies and partially sorts a range of elements (niebloid) | | [ranges::sort](sort "cpp/algorithm/ranges/sort") (C++20) | sorts a range into ascending order (niebloid) | | [ranges::stable\_sort](stable_sort "cpp/algorithm/ranges/stable sort") (C++20) | sorts a range of elements while preserving order between equal elements (niebloid) | | [ranges::nth\_element](nth_element "cpp/algorithm/ranges/nth element") (C++20) | partially sorts the given range making sure that it is partitioned by the given element (niebloid) | | [ranges::make\_heap](make_heap "cpp/algorithm/ranges/make heap") (C++20) | creates a max heap out of a range of elements (niebloid) | | [ranges::pop\_heap](pop_heap "cpp/algorithm/ranges/pop heap") (C++20) | removes the largest element from a max heap (niebloid) | | [ranges::push\_heap](push_heap "cpp/algorithm/ranges/push heap") (C++20) | adds an element to a max heap (niebloid) | | [ranges::sort\_heap](sort_heap "cpp/algorithm/ranges/sort heap") (C++20) | turns a max heap into a range of elements sorted in ascending order (niebloid) | | [partial\_sort](../partial_sort "cpp/algorithm/partial sort") | sorts the first N elements of a range (function template) | cpp std::ranges::reverse std::ranges::reverse ==================== | Defined in header `[<algorithm>](../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | Call signature | | | | ``` template< std::bidirectional_iterator I, std::sentinel_for<I> S > requires std::permutable<I> constexpr I reverse( I first, S last ); ``` | (1) | (since C++20) | | ``` template< ranges::bidirectional_range R > requires std::permutable<ranges::iterator_t<R>> constexpr ranges::borrowed_iterator_t<R> reverse( R&& r ); ``` | (2) | (since C++20) | 1) Reverses the order of the elements in the range `[first, last)`. Behaves as if applying `[ranges::iter\_swap](../../iterator/ranges/iter_swap "cpp/iterator/ranges/iter swap")` to every pair of iterators `first+i, last-i-1` for each integer `i`, where `0 ≤ i < (last-first)/2`. 2) Same as (1), but uses `r` as the range, as if using `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r)` as `first` and `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r)` as `last`. The function-like entities described on this page are *niebloids*, that is: * Explicit template argument lists cannot be specified when calling any of them. * None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl"). * When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited. In practice, they may be implemented as function objects, or with special compiler extensions. ### Parameters | | | | | --- | --- | --- | | first, last | - | the range of elements to reverse | | r | - | the range of elements to reverse | ### Return value An iterator equal to `last`. ### Complexity Exactly `(last - first)/2` swaps. ### Notes Implementations (e.g. [MSVC STL](https://github.com/microsoft/STL/blob/main/stl/src/vector_algorithms.cpp)) may enable vectorization when the iterator type models [`contiguous_iterator`](../../iterator/contiguous_iterator "cpp/iterator/contiguous iterator") and swapping its value type calls neither non-trivial special member function nor [ADL](../../language/adl "cpp/language/adl")-found `swap`. ### Possible implementation See also implementations in [libstdc++](https://github.com/gcc-mirror/gcc/blob/14d8a5ae472ca5743016f37da2dd4770d83dea21/libstdc%2B%2B-v3/include/bits/ranges_algo.h#L1278-L1325) and [MSVC STL](https://github.com/microsoft/STL/blob/472161105d596192194d4715ccad307c6c163b4a/stl/inc/algorithm#L4154-L4180). | | | --- | | ``` struct reverse_fn { template<std::bidirectional_iterator I, std::sentinel_for<I> S> requires std::permutable<I> constexpr I operator()( I first, S last ) const { auto last2{ ranges::next(first, last) }; for (auto tail{ last2 }; !(first == tail or first == --tail); ++first) { ranges::iter_swap(first, tail); } return last2; } template<ranges::bidirectional_range R> requires std::permutable<ranges::iterator_t<R>> constexpr ranges::borrowed_iterator_t<R> operator()( R&& r ) const { return (*this)(ranges::begin(r), ranges::end(r)); } }; inline constexpr reverse_fn reverse{}; ``` | ### Example ``` #include <algorithm> #include <array> #include <iostream> #include <string> int main() { std::string s{"ABCDEF"}; std::cout << s << " → "; std::ranges::reverse(s.begin(), s.end()); std::cout << s << " → "; std::ranges::reverse(s); std::cout << s << " │ "; std::array a{1, 2, 3, 4, 5}; for(auto e : a) { std::cout << e << ' '; } std::cout << "→ "; std::ranges::reverse(a); for(auto e : a) { std::cout << e << ' '; } std::cout << '\n'; } ``` Output: ``` ABCDEF → FEDCBA → ABCDEF │ 1 2 3 4 5 → 5 4 3 2 1 ``` ### See also | | | | --- | --- | | [ranges::reverse\_copy](reverse_copy "cpp/algorithm/ranges/reverse copy") (C++20) | creates a copy of a range that is reversed (niebloid) | | [ranges::reverse\_viewviews::reverse](../../ranges/reverse_view "cpp/ranges/reverse view") (C++20) | a [`view`](../../ranges/view "cpp/ranges/view") that iterates over the elements of another bidirectional view in reverse order (class template) (range adaptor object) | | [reverse](../reverse "cpp/algorithm/reverse") | reverses the order of elements in a range (function template) | cpp std::ranges::remove, std::ranges::remove_if std::ranges::remove, std::ranges::remove\_if ============================================ | Defined in header `[<algorithm>](../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | Call signature | | | | ``` template< std::permutable I, std::sentinel_for<I> S, class T, class Proj = std::identity > requires std::indirect_binary_predicate<ranges::equal_to, std::projected<I, Proj>, const T*> constexpr ranges::subrange<I> remove( I first, S last, const T& value, Proj proj = {} ); ``` | (1) | (since C++20) | | ``` template< ranges::forward_range R, class T, class Proj = std::identity > requires std::permutable<ranges::iterator_t<R>> && std::indirect_binary_predicate<ranges::equal_to, std::projected<ranges::iterator_t<R>, Proj>, const T*> constexpr ranges::borrowed_subrange_t<R> remove( R&& r, const T& value, Proj proj = {} ); ``` | (2) | (since C++20) | | ``` template< std::permutable I, std::sentinel_for<I> S, class Proj = std::identity, std::indirect_unary_predicate<std::projected<I, Proj>> Pred > constexpr ranges::subrange<I> remove_if( I first, S last, Pred pred, Proj proj = {} ); ``` | (3) | (since C++20) | | ``` template< ranges::forward_range R, class Proj = std::identity, std::indirect_unary_predicate< std::projected<ranges::iterator_t<R>, Proj>> Pred > requires std::permutable<ranges::iterator_t<R>> constexpr ranges::borrowed_subrange_t<R> remove_if( R&& r, Pred pred, Proj proj = {} ); ``` | (4) | (since C++20) | Removes all elements satisfying specific criteria from the range `[first, last)` and returns a subrange `[ret, last)`, where `ret` is a past-the-end iterator for the new end of the range. 1) Removes all elements that are equal to `value`, using `[std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(proj, \*i) == value` to compare. 3) Removes all elements for which `[std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(pred, [std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(proj, \*i))` returns `true`. 2,4) Same as (1,3), but uses `r` as the range, as if using `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r)` as `first` and `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r)` as `last`. Removing is done by shifting (by means of move assignment) the elements in the range in such a way that the elements that are not to be removed appear in the beginning of the range. Relative order of the elements that remain is preserved and the *physical* size of the container is unchanged. Iterators pointing to an element between the new *logical* end and the *physical* end of the range are still dereferenceable, but the elements themselves have unspecified values (as per [MoveAssignable](../../named_req/moveassignable "cpp/named req/MoveAssignable") post-condition). The function-like entities described on this page are *niebloids*, that is: * Explicit template argument lists cannot be specified when calling any of them. * None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl"). * When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited. In practice, they may be implemented as function objects, or with special compiler extensions. ### Parameters | | | | | --- | --- | --- | | first, last | - | the range of elements to process | | r | - | the range of elements to process | | value | - | the value of elements to remove | | pred | - | predicate to apply to the projected elements | | proj | - | projection to apply to the elements | ### Return value `{ret, last}`, where `[first, ret)` is the resulting subrange after removal, and the elements in subrange `[ret, last)` are all in valid but unspecified state. ### Complexity Exactly `N` applications of the corresponding predicate and any projection, where `N = [ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(first, last)`, and `N-1` move operations at worst. ### Notes A call to `ranges::remove` is typically followed by a call to a container's `erase` member function, which erases the unspecified values and reduces the *physical* size of the container to match its new *logical* size. These two invocations together constitute a so-called [*Erase–remove* idiom](https://en.wikipedia.org/wiki/Erase-remove_idiom "enwiki:Erase-remove idiom"), which can be achieved by the free function `[std::erase](../../container/vector/erase2 "cpp/container/vector/erase2")` that has overloads for all standard *sequence* containers, or `[std::erase\_if](../../container/vector/erase2 "cpp/container/vector/erase2")` that has overloads for *all* standard containers. The similarly-named container member functions [`list::remove`](../../container/list/remove "cpp/container/list/remove"), [`list::remove_if`](../../container/list/remove "cpp/container/list/remove"), [`forward_list::remove`](../../container/forward_list/remove "cpp/container/forward list/remove"), and [`forward_list::remove_if`](../../container/forward_list/remove "cpp/container/forward list/remove") erase the removed elements. These algorithms usually cannot be used with associative containers such as `[std::set](../../container/set "cpp/container/set")` and `[std::map](../../container/map "cpp/container/map")` because their iterator types do not dereference to [MoveAssignable](../../named_req/moveassignable "cpp/named req/MoveAssignable") types (the keys in these containers are not modifiable). Because `ranges::remove` takes `value` by reference, it can have unexpected behavior if it is a reference to an element of the range `[first, last)`. ### Possible implementation | First version | | --- | | ``` struct remove_fn { template<std::permutable I, std::sentinel_for<I> S, class T, class Proj = std::identity> requires std::indirect_binary_predicate< ranges::equal_to, std::projected<I, Proj>, const T*> constexpr ranges::subrange<I> operator()( I first, S last, const T& value, Proj proj = {} ) const { first = ranges::find(std::move(first), last, value, proj); if (first != last) { for (I i { std::next(first) }; i != last; ++i) { if (value != std::invoke(proj, *i)) { *first = ranges::iter_move(i); ++first; } } } return {first, last}; } template<ranges::forward_range R, class T, class Proj = std::identity> requires std::permutable<ranges::iterator_t<R>> && std::indirect_binary_predicate< ranges::equal_to, std::projected<ranges::iterator_t<R>, Proj>, const T*> constexpr ranges::borrowed_subrange_t<R> operator()( R&& r, const T& value, Proj proj = {} ) const { return (*this)(ranges::begin(r), ranges::end(r), value, std::move(proj)); } }; inline constexpr remove_fn remove{}; ``` | | Second version | | ``` struct remove_if_fn { template<std::permutable I, std::sentinel_for<I> S, class Proj = std::identity, std::indirect_unary_predicate<std::projected<I, Proj>> Pred> constexpr ranges::subrange<I> operator()( I first, S last, Pred pred, Proj proj = {} ) const { first = ranges::find_if(std::move(first), last, pred, proj); if (first != last) { for (I i { std::next(first) }; i != last; ++i) { if (!std::invoke(pred, std::invoke(proj, *i))) { *first = ranges::iter_move(i); ++first; } } } return {first, last}; } template<ranges::forward_range R, class Proj = std::identity, std::indirect_unary_predicate<std::projected<ranges::iterator_t<R>, Proj>> Pred> requires std::permutable<ranges::iterator_t<R>> constexpr ranges::borrowed_subrange_t<R> operator()( R&& r, Pred pred, Proj proj = {} ) const { return (*this)(ranges::begin(r), ranges::end(r), pred, std::move(proj)); } }; inline constexpr remove_if_fn remove_if{}; ``` | ### Example ``` #include <algorithm> #include <cctype> #include <iomanip> #include <iostream> #include <string> #include <string_view> int main() { std::string v1{"No - Diagnostic - Required"}; std::cout << std::quoted(v1) << " (v1, size: " << v1.size() << ")\n"; const auto ret = std::ranges::remove(v1, ' '); std::cout << std::quoted(v1) << " (v1 after `remove`, size: " << v1.size() << ")\n"; std::cout << ' ' << std::string(std::distance(v1.begin(), ret.begin()), '^') << '\n'; v1.erase(ret.begin(), ret.end()); std::cout << std::quoted(v1) << " (v1 after `erase`, size: " << v1.size() << ")\n\n"; // remove_if with custom unary predicate: auto rm = [](char c) { return !std::isupper(c); }; std::string v2{"Substitution Failure Is Not An Error"}; std::cout << std::quoted(v2) << " (v2, size: " << v2.size() << ")\n"; const auto [first, last] = std::ranges::remove_if(v2, rm); std::cout << std::quoted(v2) << " (v2 after `remove_if`, size: " << v2.size() << ")\n"; std::cout << ' ' << std::string(std::distance(v2.begin(), first), '^') << '\n'; v2.erase(first, last); std::cout << std::quoted(v2) << " (v2 after `erase`, size: " << v2.size() << ")\n\n"; // creating a view into a container that is modified by `remove_if`: for (std::string s: {"Small Object Optimization", "Non-Type Template Parameter"}) { std::cout << quoted(s) << " => " << std::string_view{begin(s), std::ranges::remove_if(s, rm).begin()} << '\n'; } } ``` Possible output: ``` "No _ Diagnostic _ Required" (v1, size: 26) "No_Diagnostic_Requiredired" (v1 after `remove`, size: 26) ^^^^^^^^^^^^^^^^^^^^^^ "No_Diagnostic_Required" (v1 after `erase`, size: 22) "Substitution Failure Is Not An Error" (v2, size: 36) "SFINAEtution Failure Is Not An Error" (v2 after `remove_if`, size: 36) ^^^^^^ "SFINAE" (v2 after `erase`, size: 6) "Small Object Optimization" => SOO "Non-Type Template Parameter" => NTTP ``` ### See also | | | | --- | --- | | [ranges::remove\_copyranges::remove\_copy\_if](remove_copy "cpp/algorithm/ranges/remove copy") (C++20)(C++20) | copies a range of elements omitting those that satisfy specific criteria (niebloid) | | [ranges::unique](unique "cpp/algorithm/ranges/unique") (C++20) | removes consecutive duplicate elements in a range (niebloid) | | [removeremove\_if](../remove "cpp/algorithm/remove") | removes elements satisfying specific criteria (function template) |
programming_docs
cpp std::ranges::count, std::ranges::count_if std::ranges::count, std::ranges::count\_if ========================================== | Defined in header `[<algorithm>](../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | Call signature | | | | ``` template< std::input_iterator I, std::sentinel_for<I> S, class T, class Proj = std::identity > requires std::indirect_binary_predicate<ranges::equal_to, std::projected<I, Proj>, const T*> constexpr std::iter_difference_t<I> count( I first, S last, const T& value, Proj proj = {} ); ``` | (1) | (since C++20) | | ``` template< ranges::input_range R, class T, class Proj = std::identity > requires std::indirect_binary_predicate<ranges::equal_to, std::projected<ranges::iterator_t<R>, Proj>, const T*> constexpr ranges::range_difference_t<R> count( R&& r, const T& value, Proj proj = {} ); ``` | (2) | (since C++20) | | ``` template< std::input_iterator I, std::sentinel_for<I> S, class Proj = std::identity, std::indirect_unary_predicate<std::projected<I, Proj>> Pred > constexpr std::iter_difference_t<I> count_if( I first, S last, Pred pred, Proj proj = {} ); ``` | (3) | (since C++20) | | ``` template< ranges::input_range R, class Proj = std::identity, std::indirect_unary_predicate<std::projected<ranges::iterator_t<R>, Proj>> Pred > constexpr ranges::range_difference_t<R> count_if( R&& r, Pred pred, Proj proj = {} ); ``` | (4) | (since C++20) | Returns the number of elements in the range `[first, last)` satisfying specific criteria. 1) counts the elements that are equal to `value`. 3) counts elements for which predicate `p` returns `true`. 2,4) Same as (1,3), but uses `r` as the source range, as if using `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r)` as `first` and `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r)` as `last`. The function-like entities described on this page are *niebloids*, that is: * Explicit template argument lists cannot be specified when calling any of them. * None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl"). * When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited. In practice, they may be implemented as function objects, or with special compiler extensions. ### Parameters | | | | | --- | --- | --- | | first, last | - | the range of elements to examine | | r | - | the range of the elements to examine | | value | - | the value to search for | | pred | - | predicate to apply to the projected elements | | proj | - | projection to apply to the elements | ### Return value Number of elements satisfying the condition. ### Complexity Exactly `last` - `first` comparisons and projection. ### Notes For the number of elements in the range without any additional criteria, see `std::ranges::distance`. ### Possible implementation | First version | | --- | | ``` struct count_fn { template< std::input_iterator I, std::sentinel_for<I> S, class T, class Proj = std::identity > requires std::indirect_binary_predicate<ranges::equal_to, std::projected<I, Proj>, const T*> constexpr std::iter_difference_t<I> operator()( I first, S last, const T& value, Proj proj = {} ) const { std::iter_difference_t<I> counter = 0; for (; first != last; ++first) { if (std::invoke(proj, *first) == value) { ++counter; } } return counter; } template< ranges::input_range R, class T, class Proj = std::identity > requires std::indirect_binary_predicate<ranges::equal_to, std::projected<ranges::iterator_t<R>, Proj>, const T*> constexpr ranges::range_difference_t<R> operator()( R&& r, const T& value, Proj proj = {} ) const { return (*this)(ranges::begin(r), ranges::end(r), value, std::ref(proj)); } }; inline constexpr count_fn count; ``` | | Second version | | ``` struct count_if_fn { template< std::input_iterator I, std::sentinel_for<I> S, class Proj = std::identity, std::indirect_unary_predicate<std::projected<I, Proj>> Pred > constexpr std::iter_difference_t<I> operator()( I first, S last, Pred pred, Proj proj = {} ) const { std::iter_difference_t<I> counter = 0; for (; first != last; ++first) { if (std::invoke(pred, std::invoke(proj, *first))) { ++counter; } } return counter; } template< ranges::input_range R, class Proj = std::identity, std::indirect_unary_predicate<std::projected<ranges::iterator_t<R>, Proj>> Pred > constexpr ranges::range_difference_t<R> operator()( R&& r, Pred pred, Proj proj = {} ) const { return (*this)(ranges::begin(r), ranges::end(r), std::ref(pred), std::ref(proj)); } }; inline constexpr count_if_fn count_if; ``` | ### Example ``` #include <algorithm> #include <iostream> #include <vector> int main() { std::vector<int> v{ 1, 2, 3, 4, 4, 3, 7, 8, 9, 10 }; namespace ranges = std::ranges; // determine how many integers in a std::vector match a target value. int target1 = 3; int target2 = 5; int num_items1 = ranges::count(v.begin(), v.end(), target1); int num_items2 = ranges::count(v, target2); std::cout << "number: " << target1 << " count: " << num_items1 << '\n'; std::cout << "number: " << target2 << " count: " << num_items2 << '\n'; // use a lambda expression to count elements divisible by 3. int num_items3 = ranges::count_if(v.begin(), v.end(), [](int i){return i % 3 == 0;}); std::cout << "number divisible by three: " << num_items3 << '\n'; // use a lambda expression to count elements divisible by 11. int num_items11 = ranges::count_if(v, [](int i){return i % 11 == 0;}); std::cout << "number divisible by eleven: " << num_items11 << '\n'; } ``` Output: ``` number: 3 count: 2 number: 5 count: 0 number divisible by three: 3 number divisible by eleven: 0 ``` ### See also | | | | --- | --- | | [ranges::distance](../../iterator/ranges/distance "cpp/iterator/ranges/distance") (C++20) | returns the distance between an iterator and a sentinel, or between the beginning and end of a range (niebloid) | | [views::counted](../../ranges/view_counted "cpp/ranges/view counted") (C++20) | creates a subrange from an iterator and a count (customization point object) | | [ranges::filter\_viewviews::filter](../../ranges/filter_view "cpp/ranges/filter view") (C++20) | a [`view`](../../ranges/view "cpp/ranges/view") that consists of the elements of a [`range`](../../ranges/range "cpp/ranges/range") that satisfies a predicate (class template) (range adaptor object) | | [countcount\_if](../count "cpp/algorithm/count") | returns the number of elements satisfying specific criteria (function template) | cpp std::ranges::prev_permutation, std::ranges::prev_permutation_result std::ranges::prev\_permutation, std::ranges::prev\_permutation\_result ====================================================================== | Defined in header `[<algorithm>](../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | Call signature | | | | ``` template< std::bidirectional_iterator I, std::sentinel_for<I> S, class Comp = ranges::less, class Proj = std::identity > requires std::sortable<I, Comp, Proj> constexpr prev_permutation_result<I> prev_permutation( I first, S last, Comp comp = {}, Proj proj = {} ); ``` | (1) | (since C++20) | | ``` template< ranges::bidirectional_range R, class Comp = ranges::less, class Proj = std::identity > requires std::sortable<ranges::iterator_t<R>, Comp, Proj> constexpr prev_permutation_result<ranges::borrowed_iterator_t<R>> prev_permutation( R&& r, Comp comp = {}, Proj proj = {} ); ``` | (2) | (since C++20) | | Helper type | | | | ``` template<class I> using prev_permutation_result = ranges::in_found_result<I>; ``` | (3) | (since C++20) | 1) Transforms the range `[first, last)` into the previous *permutation*, where the set of all permutations is ordered *lexicographically* with respect to binary comparison function object `comp` and projection function object `proj`. Returns `{last, true}` if such a *"previous permutation"* exists; otherwise transforms the range into the lexicographically *last* permutation (as if by `[ranges::sort](http://en.cppreference.com/w/cpp/ranges-algorithm-placeholder/sort)(first, last, comp, proj); [ranges::reverse](http://en.cppreference.com/w/cpp/algorithm/ranges/reverse)(first, last);`), and returns `{last, false}`. 2) Same as (1), but uses `r` as the source range, as if using `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r)` as `first`, and `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r)` as `last`. The function-like entities described on this page are *niebloids*, that is: * Explicit template argument lists cannot be specified when calling any of them. * None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl"). * When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited. In practice, they may be implemented as function objects, or with special compiler extensions. ### Parameters | | | | | --- | --- | --- | | first, last | - | the range of elements to *permute* | | r | - | the range of elements to *permute* | | comp | - | comparison function object which returns `true` if the first argument is *less* than the second | | proj | - | projection to apply to the elements | ### Return value 1) `ranges::prev_permutation_result<I>{last, true}` if the new permutation is lexicographically *less* than the old one. `ranges::prev_permutation_result<I>{last, false}` if the first permutation was reached and the range was reset to the last permutation. 2) same as (1) except that the return type is `ranges::prev\_permutation\_result<[ranges::borrowed\_iterator\_t](http://en.cppreference.com/w/cpp/ranges/borrowed_iterator_t)<R>>`. ### Exceptions Any exceptions thrown from iterator operations or the element swap. ### Complexity At most \(\scriptsize N/2\)N/2 swaps, where \(\scriptsize N\)N is `[ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(first, last)` in case (1) or `[ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(r)` in case (2). Averaged over the entire sequence of permutations, typical implementations use about 3 comparisons and 1.5 swaps per call. ### Notes Implementations (e.g. [MSVC STL](https://github.com/microsoft/STL/blob/main/stl/src/vector_algorithms.cpp)) may enable vectorization when the iterator type models [`contiguous_iterator`](../../iterator/contiguous_iterator "cpp/iterator/contiguous iterator") and swapping its value type calls neither non-trivial special member function nor [ADL](../../language/adl "cpp/language/adl")-found `swap`. ### Possible implementation | | | --- | | ``` struct prev_permutation_fn { template<std::bidirectional_iterator I, std::sentinel_for<I> S, class Comp = ranges::less, class Proj = std::identity> requires std::sortable<I, Comp, Proj> constexpr ranges::prev_permutation_result<I> operator()(I first, S last, Comp comp = {}, Proj proj = {}) const { // check that the sequence has at least two elements if (first == last) return {std::move(first), false}; auto i {first}; ++i; if (i == last) return {std::move(i), false}; auto i_last {ranges::next(first, last)}; i = i_last; --i; // main "permutating" loop for (;;) { auto i1 {i}; --i; if (std::invoke(comp, std::invoke(proj, *i), std::invoke(proj, *i1))) { auto j {i_last}; while (!std::invoke(comp, std::invoke(proj, *i), std::invoke(proj, *--j))) { } ranges::iter_swap(i, j); ranges::reverse(i1, last); return {std::move(i_last), true}; } // permutation "space" is exhausted if (i == first) { ranges::reverse(first, last); return {std::move(i_last), false}; } } } template<ranges::bidirectional_range R, class Comp = ranges::less, class Proj = std::identity> requires std::sortable<ranges::iterator_t<R>, Comp, Proj> constexpr ranges::prev_permutation_result<ranges::borrowed_iterator_t<R>> operator()(R&& r, Comp comp = {}, Proj proj = {}) const { return (*this)(ranges::begin(r), ranges::end(r), std::move(comp), std::move(proj)); } }; inline constexpr prev_permutation_fn prev_permutation{}; ``` | ### Example ``` #include <algorithm> #include <array> #include <compare> #include <functional> #include <iostream> #include <string> struct S { char c; int i; auto operator<=>(const S&) const = default; friend std::ostream& operator<< (std::ostream& os, const S& s) { return os << "{'" << s.c << "', " << s.i << "}"; } }; auto print = [](auto const& v, char term = ' ') { std::cout << "{ "; for (const auto& e: v) { std::cout << e << ' '; } std::cout << '}' << term; }; int main() { std::cout << "Generate all permutations (iterators case):\n"; std::string s{"cba"}; do { print(s); } while(std::ranges::prev_permutation(s.begin(), s.end()).found); std::cout << "\n" "Generate all permutations (range case):\n"; std::array a{'c', 'b', 'a'}; do { print(a); } while(std::ranges::prev_permutation(a).found); std::cout << "\n" "Generate all permutations using comparator:\n"; using namespace std::literals; std::array z{ "▁"s, "▄"s, "█"s }; do { print(z); } while(std::ranges::prev_permutation(z, std::greater()).found); std::cout << "\n" "Generate all permutations using projection:\n"; std::array<S, 3> r{ S{'C',1}, S{'B',2}, S{'A',3} }; do { print(r, '\n'); } while(std::ranges::prev_permutation(r, {}, &S::c).found); } ``` Output: ``` Generate all permutations (iterators case): { c b a } { c a b } { b c a } { b a c } { a c b } { a b c } Generate all permutations (range case): { c b a } { c a b } { b c a } { b a c } { a c b } { a b c } Generate all permutations using comparator: { ▁ ▄ █ } { ▁ █ ▄ } { ▄ ▁ █ } { ▄ █ ▁ } { █ ▁ ▄ } { █ ▄ ▁ } Generate all permutations using projection: { {'C', 1} {'B', 2} {'A', 3} } { {'C', 1} {'A', 3} {'B', 2} } { {'B', 2} {'C', 1} {'A', 3} } { {'B', 2} {'A', 3} {'C', 1} } { {'A', 3} {'C', 1} {'B', 2} } { {'A', 3} {'B', 2} {'C', 1} } ``` ### See also | | | | --- | --- | | [ranges::next\_permutation](next_permutation "cpp/algorithm/ranges/next permutation") (C++20) | generates the next greater lexicographic permutation of a range of elements (niebloid) | | [ranges::is\_permutation](is_permutation "cpp/algorithm/ranges/is permutation") (C++20) | determines if a sequence is a permutation of another sequence (niebloid) | | [next\_permutation](../next_permutation "cpp/algorithm/next permutation") | generates the next greater lexicographic permutation of a range of elements (function template) | | [prev\_permutation](../prev_permutation "cpp/algorithm/prev permutation") | generates the next smaller lexicographic permutation of a range of elements (function template) | | [is\_permutation](../is_permutation "cpp/algorithm/is permutation") (C++11) | determines if a sequence is a permutation of another sequence (function template) | cpp std::ranges::replace, std::ranges::replace_if std::ranges::replace, std::ranges::replace\_if ============================================== | Defined in header `[<algorithm>](../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | Call signature | | | | ``` template< std::input_iterator I, std::sentinel_for<I> S, class T1, class T2, class Proj = std::identity > requires std::indirectly_writable<I, const T2&> && std::indirect_binary_predicate<ranges::equal_to, std::projected<I, Proj>, const T1*> constexpr I replace( I first, S last, const T1& old_value, const T2& new_value, Proj proj = {} ); ``` | (1) | (since C++20) | | ``` template< ranges::input_range R, class T1, class T2, class Proj = std::identity > requires std::indirectly_writable<ranges::iterator_t<R>, const T2&> && std::indirect_binary_predicate<ranges::equal_to, std::projected<ranges::iterator_t<R>, Proj>, const T1*> constexpr ranges::borrowed_iterator_t<R> replace( R&& r, const T1& old_value, const T2& new_value, Proj proj = {} ); ``` | (2) | (since C++20) | | ``` template< std::input_iterator I, std::sentinel_for<I> S, class T, class Proj = std::identity, std::indirect_unary_predicate<std::projected<I, Proj>> Pred > requires std::indirectly_writable<I, const T&> constexpr I replace_if( I first, S last, Pred pred, const T& new_value, Proj proj = {} ); ``` | (3) | (since C++20) | | ``` template< ranges::input_range R, class T, class Proj = std::identity, std::indirect_unary_predicate< std::projected<ranges::iterator_t<R>, Proj>> Pred > requires std::indirectly_writable<ranges::iterator_t<R>, const T&> constexpr ranges::borrowed_iterator_t<R> replace_if( R&& r, Pred pred, const T& new_value, Proj proj = {} ); ``` | (4) | (since C++20) | Replaces all elements satisfying specific criteria with `new_value` in the range `[first, last)`. 1) Replaces all elements that are equal to `old_value`, using `[std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(proj, \*i) == old_value` to compare. 3) Replaces all elements for which the predicate `pred` evaluates to `true`, where evaluating expression is `[std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(pred, [std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(proj, \*i))`. 2,4) Same as (1,3), but uses `r` as the range, as if using `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r)` as `first` and `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r)` as `last`. The function-like entities described on this page are *niebloids*, that is: * Explicit template argument lists cannot be specified when calling any of them. * None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl"). * When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited. In practice, they may be implemented as function objects, or with special compiler extensions. ### Parameters | | | | | --- | --- | --- | | first, last | - | the range of elements to process | | r | - | the range of elements to process | | old\_value | - | the value of elements to replace | | new\_value | - | the value to use as a replacement | | pred | - | predicate to apply to the projected elements | | proj | - | projection to apply to the elements | ### Return value An iterator equal to `last`. ### Complexity Exactly `[ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(first, last)` applications of the corresponding predicate `comp` and any projection `proj`. ### Notes Because the algorithm takes `old_value` and `new_value` by reference, it may have unexpected behavior if either is a reference to an element of the range `[first, last)`. ### Possible implementation | First version | | --- | | ``` struct replace_fn { template <std::input_iterator I, std::sentinel_for<I> S, class T1, class T2, class Proj = std::identity> requires std::indirectly_writable<I, const T2&> && std::indirect_binary_predicate< ranges::equal_to, std::projected<I, Proj>, const T1*> constexpr I operator() ( I first, S last, const T1& old_value, const T2& new_value, Proj proj = {} ) const { for (; first != last; ++first) { if (old_value == std::invoke(proj, *first)) { *first = new_value; } } return first; } template <ranges::input_range R, class T1, class T2, class Proj = std::identity> requires std::indirectly_writable<ranges::iterator_t<R>, const T2&> && std::indirect_binary_predicate<ranges::equal_to, std::projected<ranges::iterator_t<R>, Proj>, const T1*> constexpr ranges::borrowed_iterator_t<R> operator() ( R&& r, const T1& old_value, const T2& new_value, Proj proj = {} ) const { return (*this)(ranges::begin(r), ranges::end(r), old_value, new_value, std::move(proj)); } }; inline constexpr replace_fn replace{}; ``` | | Second version | | ``` struct replace_if_fn { template <std::input_iterator I, std::sentinel_for<I> S, class T, class Proj = std::identity, std::indirect_unary_predicate< std::projected<I, Proj>> Pred> requires std::indirectly_writable<I, const T&> constexpr I operator() ( I first, S last, Pred pred, const T& new_value, Proj proj = {} ) const { for (; first != last; ++first) { if (!!std::invoke(pred, std::invoke(proj, *first))) { *first = new_value; } } return std::move(first); } template <ranges::input_range R, class T, class Proj = std::identity, std::indirect_unary_predicate<std::projected<ranges::iterator_t<R>, Proj>> Pred> requires std::indirectly_writable<ranges::iterator_t<R>, const T&> constexpr ranges::borrowed_iterator_t<R> operator() ( R&& r, Pred pred, const T& new_value, Proj proj = {} ) const { return (*this)(ranges::begin(r), ranges::end(r), std::move(pred), new_value, std::move(proj)); } }; inline constexpr replace_if_fn replace_if{}; ``` | ### Example ``` #include <algorithm> #include <array> #include <iostream> int main() { auto print = [](const auto& v) { for (const auto& e : v) { std::cout << e << ' '; } std::cout << '\n'; }; std::array p{1, 6, 1, 6, 1, 6}; print(p); std::ranges::replace(p, 6, 9); print(p); std::array q{1, 2, 3, 6, 7, 8, 4, 5}; print(q); std::ranges::replace_if(q, [](int x){ return 5 < x; }, 5); print(q); } ``` Output: ``` 1 6 1 6 1 6 1 9 1 9 1 9 1 2 3 6 7 8 4 5 1 2 3 5 5 5 4 5 ``` ### See also | | | | --- | --- | | [ranges::replace\_copyranges::replace\_copy\_if](replace_copy "cpp/algorithm/ranges/replace copy") (C++20)(C++20) | copies a range, replacing elements satisfying specific criteria with another value (niebloid) | | [replacereplace\_if](../replace "cpp/algorithm/replace") | replaces all values satisfying specific criteria with another value (function template) |
programming_docs
cpp std::ranges::remove_copy, std::ranges::remove_copy_if, std::ranges::remove_copy_result, std::ranges::remove_copy_if_result std::ranges::remove\_copy, std::ranges::remove\_copy\_if, std::ranges::remove\_copy\_result, std::ranges::remove\_copy\_if\_result ================================================================================================================================== | Defined in header `[<algorithm>](../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | Call signature | | | | ``` template< std::input_iterator I, std::sentinel_for<I> S, std::weakly_incrementable O, class T, class Proj = std::identity > requires std::indirectly_copyable<I, O> && std::indirect_binary_predicate<ranges::equal_to, std::projected<I, Proj>, const T*> constexpr remove_copy_result<I, O> remove_copy( I first, S last, O result, const T& value, Proj proj = {} ); ``` | (1) | (since C++20) | | ``` template< ranges::input_range R, std::weakly_incrementable O, class T, class Proj = std::identity > requires std::indirectly_copyable<ranges::iterator_t<R>, O> && std::indirect_binary_predicate<ranges::equal_to, std::projected<ranges::iterator_t<R>, Proj>, const T*> constexpr remove_copy_result<ranges::borrowed_iterator_t<R>, O> remove_copy( R&& r, O result, const T& value, Proj proj = {} ); ``` | (2) | (since C++20) | | ``` template< std::input_iterator I, std::sentinel_for<I> S, std::weakly_incrementable O, class Proj = std::identity, std::indirect_unary_predicate<std::projected<I, Proj>> Pred > requires std::indirectly_copyable<I, O> constexpr remove_copy_if_result<I, O> remove_copy_if( I first, S last, O result, Pred pred, Proj proj = {} ); ``` | (3) | (since C++20) | | ``` template< ranges::input_range R, std::weakly_incrementable O, class Proj = std::identity, std::indirect_unary_predicate< std::projected<ranges::iterator_t<R>, Proj>> Pred > requires std::indirectly_copyable<ranges::iterator_t<R>, O> constexpr remove_copy_if_result<ranges::borrowed_iterator_t<R>, O> remove_copy_if( R&& r, O result, Pred pred, Proj proj = {} ); ``` | (4) | (since C++20) | | Helper types | | | | ``` template<class I, class O> using remove_copy_result = ranges::in_out_result<I, O>; ``` | (5) | (since C++20) | | ``` template<class I, class O> using remove_copy_if_result = ranges::in_out_result<I, O>; ``` | (6) | (since C++20) | Copies elements from the source range `[first, last)`, to the destination range beginning at `result`, omitting the elements which (after being projected by `proj`) satisfy specific criteria. The behavior is undefined if the source and destination ranges overlap. 1) Ignores all elements that are equal to `value`. 3) Ignores all elements for which predicate `pred` returns `true`. 2,4) Same as (1,3), but uses `r` as the source range, as if using `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r)` as `first`, and `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r)` as `last`. The function-like entities described on this page are *niebloids*, that is: * Explicit template argument lists cannot be specified when calling any of them. * None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl"). * When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited. In practice, they may be implemented as function objects, or with special compiler extensions. ### Parameters | | | | | --- | --- | --- | | first, last | - | the source range of elements | | r | - | the source range of elements | | result | - | the beginning of the destination range | | value | - | the value of the elements *not* to copy | | comp | - | the binary predicate to compare the projected elements | | proj | - | the projection to apply to the elements | ### Return value `{last, result + N}`, where `N` is the number of elements copied. ### Complexity Exactly `[ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(first, last)` applications of the corresponding predicate `comp` and any projection `proj`. ### Notes The algorithm is *stable*, i.e. preserves the relative order of the copied elements. ### Possible implementation | First version | | --- | | ``` struct remove_copy_fn { template <std::input_iterator I, std::sentinel_for<I> S, std::weakly_incrementable O, class T, class Proj = std::identity> requires std::indirectly_copyable<I, O> && std::indirect_binary_predicate<ranges::equal_to, std::projected<I, Proj>, const T*> constexpr ranges::remove_copy_result<I, O> operator()( I first, S last, O result, const T& value, Proj proj = {} ) const { for (; !(first == last); ++first) { if (value != std::invoke(proj, *first)) { *result = *first; ++result; } } return {std::move(first), std::move(result)}; } template <ranges::input_range R, std::weakly_incrementable O, class T, class Proj = std::identity> requires std::indirectly_copyable<ranges::iterator_t<R>, O> && std::indirect_binary_predicate<ranges::equal_to, std::projected<ranges::iterator_t<R>, Proj>, const T*> constexpr ranges::remove_copy_result<ranges::borrowed_iterator_t<R>, O> operator()( R&& r, O result, const T& value, Proj proj = {} ) const { return (*this)(ranges::begin(r), ranges::end(r), std::move(result), value, std::move(proj)); } }; inline constexpr remove_copy_fn remove_copy{}; ``` | | Second version | | ``` struct remove_copy_if_fn { template <std::input_iterator I, std::sentinel_for<I> S, std::weakly_incrementable O, class Proj = std::identity, std::indirect_unary_predicate<std::projected<I, Proj>> Pred> requires std::indirectly_copyable<I, O> constexpr ranges::remove_copy_if_result<I, O> operator()( I first, S last, O result, Pred pred, Proj proj = {} ) const { for (; first != last; ++first) { if (false == std::invoke(pred, std::invoke(proj, *first))) { *result = *first; ++result; } } return {std::move(first), std::move(result)}; } template <ranges::input_range R, std::weakly_incrementable O, class Proj = std::identity, std::indirect_unary_predicate<std::projected<ranges::iterator_t<R>, Proj>> Pred> requires std::indirectly_copyable<ranges::iterator_t<R>, O> constexpr ranges::remove_copy_if_result<ranges::borrowed_iterator_t<R>, O> operator()( R&& r, O result, Pred pred, Proj proj = {} ) const { return (*this)(ranges::begin(r), ranges::end(r), std::move(result), std::move(pred), std::move(proj)); } }; inline constexpr remove_copy_if_fn remove_copy_if{}; ``` | ### Example ``` #include <algorithm> #include <array> #include <complex> #include <iomanip> #include <iostream> #include <iterator> #include <string_view> #include <vector> void print(const auto rem, const auto& v) { std::cout << rem << ' '; for (const auto& e : v) { std::cout << e << ' '; }; std::cout << '\n'; } int main() { // Filter out the hash symbol from the given string. const std::string_view str{ "#Small #Buffer #Optimization" }; std::cout << "before: " << std::quoted(str) << "\n"; std::cout << "after: \""; std::ranges::remove_copy(str.begin(), str.end(), std::ostream_iterator<char>(std::cout), '#'); std::cout << "\"\n"; // Copy only the complex numbers with positive imaginary part. using Ci = std::complex<int>; constexpr std::array<Ci, 5> source{ Ci{1,0}, Ci{0,1}, Ci{2,-1}, Ci{3,2}, Ci{4,-3} }; std::vector<std::complex<int>> target; std::ranges::remove_copy_if(source, std::back_inserter(target), [](int imag){ return imag <= 0; }, [](Ci z){ return z.imag(); } ); print("source:", source); print("target:", target); } ``` Output: ``` before: "#Small #Buffer #Optimization" after: "Small Buffer Optimization" source: (1,0) (0,1) (2,-1) (3,2) (4,-3) target: (0,1) (3,2) ``` ### See also | | | | --- | --- | | [ranges::removeranges::remove\_if](remove "cpp/algorithm/ranges/remove") (C++20)(C++20) | removes elements satisfying specific criteria (niebloid) | | [ranges::copyranges::copy\_if](copy "cpp/algorithm/ranges/copy") (C++20)(C++20) | copies a range of elements to a new location (niebloid) | | [ranges::copy\_n](copy_n "cpp/algorithm/ranges/copy n") (C++20) | copies a number of elements to a new location (niebloid) | | [ranges::copy\_backward](copy_backward "cpp/algorithm/ranges/copy backward") (C++20) | copies a range of elements in backwards order (niebloid) | | [ranges::replace\_copyranges::replace\_copy\_if](replace_copy "cpp/algorithm/ranges/replace copy") (C++20)(C++20) | copies a range, replacing elements satisfying specific criteria with another value (niebloid) | | [ranges::reverse\_copy](reverse_copy "cpp/algorithm/ranges/reverse copy") (C++20) | creates a copy of a range that is reversed (niebloid) | | [ranges::rotate\_copy](rotate_copy "cpp/algorithm/ranges/rotate copy") (C++20) | copies and rotate a range of elements (niebloid) | | [ranges::unique\_copy](unique_copy "cpp/algorithm/ranges/unique copy") (C++20) | creates a copy of some range of elements that contains no consecutive duplicates (niebloid) | | [remove\_copyremove\_copy\_if](../remove_copy "cpp/algorithm/remove copy") | copies a range of elements omitting those that satisfy specific criteria (function template) | cpp std::ranges::search_n std::ranges::search\_n ====================== | Defined in header `[<algorithm>](../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | Call signature | | | | ``` template< std::forward_iterator I, std::sentinel_for<I> S, class T, class Pred = ranges::equal_to, class Proj = std::identity > requires std::indirectly_comparable<I, const T*, Pred, Proj> constexpr ranges::subrange<I> search_n( I first, S last, std::iter_difference_t<I> count, const T& value, Pred pred = {}, Proj proj = {} ); ``` | (1) | (since C++20) | | ``` template< ranges::forward_range R, class T, class Pred = ranges::equal_to, class Proj = std::identity > requires std::indirectly_comparable<ranges::iterator_t<R>, const T*, Pred, Proj> constexpr ranges::borrowed_subrange_t<R> search_n( R&& r, ranges::range_difference_t<R> count, const T& value, Pred pred = {}, Proj proj = {} ); ``` | (2) | (since C++20) | 1) Searches the range `[first, last)` for the *first* sequence of `count` elements whose projected values are each equal to the given `value` according to the binary predicate `pred`. 2) Same as (1), but uses `r` as the source range, as if using `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r)` as `first` and `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r)` as `last`. The function-like entities described on this page are *niebloids*, that is: * Explicit template argument lists cannot be specified when calling any of them. * None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl"). * When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited. In practice, they may be implemented as function objects, or with special compiler extensions. ### Parameters | | | | | --- | --- | --- | | first, last | - | the range of elements to examine (aka *haystack*) | | r | - | the range of elements to examine (aka *haystack*) | | count | - | the length of the sequence to search for | | value | - | the value to search for (aka *needle*) | | pred | - | the binary predicate that compares the projected elements with `value` | | proj | - | the projection to apply to the elements of the range to examine | ### Return value 1) Returns `std::[ranges::subrange](http://en.cppreference.com/w/cpp/ranges/subrange)` object that contains a pair of iterators in the range `[first, last)` that designate the found subsequence. If no such subsequence is found, returns `std::[ranges::subrange](http://en.cppreference.com/w/cpp/ranges/subrange){last, last}`. If `count <= 0`, returns `std::[ranges::subrange](http://en.cppreference.com/w/cpp/ranges/subrange){first, first}`. 2) same as (1) but the return type is `[ranges::borrowed\_subrange\_t](http://en.cppreference.com/w/cpp/ranges/borrowed_iterator_t)<R>`. ### Complexity Linear: at most `[ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(first, last)` applications of the predicate and the projection. ### Notes An implementation can improve efficiency of the search *in average* if the iterators model `[std::random\_access\_iterator](http://en.cppreference.com/w/cpp/iterator/random_access_iterator)`. ### Possible implementation | | | --- | | ``` struct search_n_fn { template<std::forward_iterator I, std::sentinel_for<I> S, class T, class Pred = ranges::equal_to, class Proj = std::identity> requires std::indirectly_comparable<I, const T*, Pred, Proj> constexpr ranges::subrange<I> operator()(I first, S last, std::iter_difference_t<I> count, const T& value, Pred pred = {}, Proj proj = {}) const { if (count <= 0) return {first, first}; for (; first != last; ++first) { if (std::invoke(pred, std::invoke(proj, *first), value)) { I start = first; std::iter_difference_t<I> n{1}; for (;;) { if (n++ == count) return {start, std::next(first)}; // found if (++first == last) return {first, first}; // not found if (!std::invoke(pred, std::invoke(proj, *first), value)) break; // not equ to value } } } return {first, first}; } template<ranges::forward_range R, class T, class Pred = ranges::equal_to, class Proj = std::identity> requires std::indirectly_comparable<ranges::iterator_t<R>, const T*, Pred, Proj> constexpr ranges::borrowed_subrange_t<R> operator()(R&& r, ranges::range_difference_t<R> count, const T& value, Pred pred = {}, Proj proj = {}) const { return (*this)(ranges::begin(r), ranges::end(r), std::move(count), value, std::move(pred), std::move(proj)); } }; inline constexpr search_n_fn search_n{}; ``` | ### Example ``` #include <algorithm> #include <iomanip> #include <iostream> #include <string> int main() { static constexpr auto nums = {1, 2, 2, 3, 4, 1, 2, 2, 2, 1}; constexpr int count{ 3 }; constexpr int value{ 2 }; constexpr auto result1 = std::ranges::search_n( nums.begin(), nums.end(), count, value ); static_assert( // found result1.size() == count && std::distance(nums.begin(), result1.begin()) == 6 && std::distance(nums.begin(), result1.end()) == 9 ); constexpr auto result2 = std::ranges::search_n(nums, count, value); static_assert( // found result2.size() == count && std::distance(nums.begin(), result2.begin()) == 6 && std::distance(nums.begin(), result2.end()) == 9 ); constexpr auto result3 = std::ranges::search_n(nums, count, /* value */ 5); static_assert( // not found result3.size() == 0 && result3.begin() == result3.end() && result3.end() == nums.end() ); constexpr auto result4 = std::ranges::search_n(nums, /* count */ 0, /* value */ 1); static_assert( // not found result4.size() == 0 && result4.begin() == result4.end() && result4.end() == nums.begin() ); constexpr char symbol{'B'}; std::cout << std::boolalpha << "Find a sub-sequence: " << std::quoted(std::string(count, symbol)) << '\n'; auto result5 = std::ranges::search_n(nums, count, symbol, [](const char x, const char y) { // binary predicate const bool o{ x == y }; std::cout << "bin_op(" << x << ", " << y << ") == " << o << "\n"; return o; }, [](const int z) { return 'A' + z - 1; } // projects nums -> ASCII ); std::cout << "Found: " << !result5.empty() << '\n'; } ``` Output: ``` Find a sub-sequence: "BBB" bin_op(A, B) == false bin_op(B, B) == true bin_op(B, B) == true bin_op(C, B) == false bin_op(D, B) == false bin_op(A, B) == false bin_op(B, B) == true bin_op(B, B) == true bin_op(B, B) == true Found: true ``` ### See also | | | | --- | --- | | [ranges::adjacent\_find](adjacent_find "cpp/algorithm/ranges/adjacent find") (C++20) | finds the first two adjacent items that are equal (or satisfy a given predicate) (niebloid) | | [ranges::findranges::find\_ifranges::find\_if\_not](find "cpp/algorithm/ranges/find") (C++20)(C++20)(C++20) | finds the first element satisfying specific criteria (niebloid) | | [ranges::find\_end](find_end "cpp/algorithm/ranges/find end") (C++20) | finds the last sequence of elements in a certain range (niebloid) | | [ranges::find\_first\_of](find_first_of "cpp/algorithm/ranges/find first of") (C++20) | searches for any one of a set of elements (niebloid) | | [ranges::includes](includes "cpp/algorithm/ranges/includes") (C++20) | returns true if one sequence is a subsequence of another (niebloid) | | [ranges::mismatch](mismatch "cpp/algorithm/ranges/mismatch") (C++20) | finds the first position where two ranges differ (niebloid) | | [ranges::search](search "cpp/algorithm/ranges/search") (C++20) | searches for a range of elements (niebloid) | | [search\_n](../search_n "cpp/algorithm/search n") | searches a range for a number of consecutive copies of an element (function template) | cpp std::ranges::generate std::ranges::generate ===================== | Defined in header `[<algorithm>](../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | Call signature | | | | ``` template< std::input_or_output_iterator O, std::sentinel_for<O> S, std::copy_constructible F > requires std::invocable<F&> && std::indirectly_writable<O, std::invoke_result_t<F&>> constexpr O generate( O first, S last, F gen ); ``` | (1) | (since C++20) | | ``` template< class R, std::copy_constructible F > requires std::invocable<F&> && ranges::output_range<R, std::invoke_result_t<F&>> constexpr ranges::borrowed_iterator_t<R> generate( R&& r, F gen ); ``` | (2) | (since C++20) | 1) Assigns the result of *successive* invocations of the function object `gen` to each element in the range `[first, last)`. 2) Same as (1), but uses `r` as the range, as if using `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r)` as `first` and `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r)` as `last`. The function-like entities described on this page are *niebloids*, that is: * Explicit template argument lists cannot be specified when calling any of them. * None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl"). * When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited. In practice, they may be implemented as function objects, or with special compiler extensions. ### Parameters | | | | | --- | --- | --- | | first, last | - | the range of elements to modify | | r | - | the range of elements to modify | | gen | - | the generator function object | ### Return value An output iterator that compares equal to `last`. ### Complexity Exactly `[ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(first, last)` invocations of `gen()` and assignments. ### Possible implementation | | | --- | | ``` struct generate_fn { template<std::input_or_output_iterator O, std::sentinel_for<O> S, std::copy_constructible F> requires std::invocable<F&> && std::indirectly_writable<O, std::invoke_result_t<F&>> constexpr O operator()( O first, S last, F gen ) const { for (; first != last; *first = std::invoke(gen), ++first); return first; } template<class R, std::copy_constructible F> requires std::invocable<F&> && ranges::output_range<R, std::invoke_result_t<F&>> constexpr ranges::borrowed_iterator_t<R> operator()( R&& r, F gen ) const { return (*this)(ranges::begin(r), ranges::end(r), std::move(gen)); } }; inline constexpr generate_fn generate{}; ``` | ### Example ``` #include <algorithm> #include <array> #include <iostream> #include <random> #include <string_view> auto dice() { static std::uniform_int_distribution<int> distr{1, 6}; static std::random_device device; static std::mt19937 engine{device()}; return distr(engine); } void iota(auto& v, int n) { std::ranges::generate(v, [&n] () mutable { return n++; }); } void print(std::string_view comment, const auto& v) { for (std::cout << comment; int i : v) { std::cout << i << ' '; } std::cout << '\n'; } int main() { std::array<int, 8> v; std::ranges::generate(v.begin(), v.end(), dice); print("dice: ", v); std::ranges::generate(v, dice); print("dice: ", v); iota(v, 1); print("iota: ", v); } ``` Possible output: ``` dice: 4 3 1 6 6 4 5 5 dice: 4 2 5 3 6 2 6 2 iota: 1 2 3 4 5 6 7 8 ``` ### See also | | | | --- | --- | | [ranges::generate\_n](generate_n "cpp/algorithm/ranges/generate n") (C++20) | saves the result of N applications of a function (niebloid) | | [ranges::fill](fill "cpp/algorithm/ranges/fill") (C++20) | assigns a range of elements a certain value (niebloid) | | [ranges::fill\_n](fill_n "cpp/algorithm/ranges/fill n") (C++20) | assigns a value to a number of elements (niebloid) | | [ranges::transform](transform "cpp/algorithm/ranges/transform") (C++20) | applies a function to a range of elements (niebloid) | | [generate](../generate "cpp/algorithm/generate") | assigns the results of successive function calls to every element in a range (function template) |
programming_docs
cpp std::ranges::adjacent_find std::ranges::adjacent\_find =========================== | Defined in header `[<algorithm>](../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | Call signature | | | | ``` template< std::forward_iterator I, std::sentinel_for<I> S, class Proj = std::identity, std::indirect_binary_predicate< std::projected<I, Proj>, std::projected<I, Proj>> Pred = ranges::equal_to > constexpr I adjacent_find( I first, S last, Pred pred = {}, Proj proj = {} ); ``` | (1) | (since C++20) | | ``` template< ranges::forward_range R, class Proj = std::identity, std::indirect_binary_predicate< std::projected<ranges::iterator_t<R>, Proj>, std::projected<ranges::iterator_t<R>, Proj>> Pred = ranges::equal_to > constexpr ranges::borrowed_iterator_t<R> adjacent_find( R&& r, Pred pred = {}, Proj proj = {} ); ``` | (2) | (since C++20) | Searches the range `[first, last)` for two consecutive equal elements. 1) Elements are compared using `pred` (after projecting with the projection `proj`). 2) Same as (1), but uses `r` as the source range, as if using `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r)` as `first` and `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r)` as `last`. The function-like entities described on this page are *niebloids*, that is: * Explicit template argument lists cannot be specified when calling any of them. * None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl"). * When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited. In practice, they may be implemented as function objects, or with special compiler extensions. ### Parameters | | | | | --- | --- | --- | | first, last | - | the range of elements to examine | | r | - | the range of the elements to examine | | pred | - | predicate to apply to the projected elements | | proj | - | projection to apply to the elements | ### Return value An iterator to the first of the first pair of identical elements, that is, the first iterator `it` such that `bool([std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(pred, [std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(proj1, \*it), [std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(proj, \*(it + 1))))` is `true`. If no such elements are found, an iterator equal to `last` is returned. ### Complexity Exactly `min((result-first)+1, (last-first)-1)` applications of the predicate and projection where `result` is the return value. ### Possible implementation | | | --- | | ``` struct adjacent_find_fn { template< std::forward_iterator I, std::sentinel_for<I> S, class Proj = std::identity, std::indirect_binary_predicate< std::projected<I, Proj>, std::projected<I, Proj>> Pred = ranges::equal_to > constexpr I operator()( I first, S last, Pred pred = {}, Proj proj = {} ) const { if (first == last) { return first; } auto next = ranges::next(first); for (; next != last; ++next, ++first) { if (std::invoke(pred, std::invoke(proj, *first), std::invoke(proj, *next))) { return first; } } return next; } template< ranges::forward_range R, class Proj = std::identity, std::indirect_binary_predicate< std::projected<ranges::iterator_t<R>, Proj>, std::projected<ranges::iterator_t<R>, Proj>> Pred = ranges::equal_to > constexpr ranges::borrowed_iterator_t<R> operator()( R&& r, Pred pred = {}, Proj proj = {} ) const { return (*this)(ranges::begin(r), ranges::end(r), std::ref(pred), std::ref(proj)); } }; inline constexpr adjacent_find_fn adjacent_find; ``` | ### Example ``` #include <algorithm> #include <iostream> #include <vector> #include <functional> int main() { std::vector<int> v1{0, 1, 2, 3, 40, 40, 41, 41, 5}; // ^^ ^^ namespace ranges = std::ranges; auto i1 = ranges::adjacent_find(v1.begin(), v1.end()); if (i1 == v1.end()) { std::cout << "No matching adjacent elements\n"; } else { std::cout << "The first adjacent pair of equal elements is at [" << ranges::distance(v1.begin(), i1) << "] == " << *i1 << '\n'; } auto i2 = ranges::adjacent_find(v1, ranges::greater()); if (i2 == v1.end()) { std::cout << "The entire vector is sorted in ascending order\n"; } else { std::cout << "The last element in the non-decreasing subsequence is at [" << ranges::distance(v1.begin(), i2) << "] == " << *i2 << '\n'; } } ``` Output: ``` The first adjacent pair of equal elements is at [4] == 40 The last element in the non-decreasing subsequence is at [7] == 41 ``` ### See also | | | | --- | --- | | [ranges::unique](unique "cpp/algorithm/ranges/unique") (C++20) | removes consecutive duplicate elements in a range (niebloid) | | [adjacent\_find](../adjacent_find "cpp/algorithm/adjacent find") | finds the first two adjacent items that are equal (or satisfy a given predicate) (function template) | cpp std::ranges::set_difference, std::ranges::set_difference_result std::ranges::set\_difference, std::ranges::set\_difference\_result ================================================================== | Defined in header `[<algorithm>](../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | Call signature | | | | ``` template< std::input_iterator I1, std::sentinel_for<I1> S1, std::input_iterator I2, std::sentinel_for<I2> S2, std::weakly_incrementable O, class Comp = ranges::less, class Proj1 = std::identity, class Proj2 = std::identity > requires std::mergeable<I1, I2, O, Comp, Proj1, Proj2> constexpr set_difference_result<I1, O> set_difference( I1 first1, S1 last1, I2 first2, S2 last2, O result, Comp comp = {}, Proj1 proj1 = {}, Proj2 proj2 = {} ); ``` | (1) | (since C++20) | | ``` template< ranges::input_range R1, ranges::input_range R2, std::weakly_incrementable O, class Comp = ranges::less, class Proj1 = std::identity, class Proj2 = std::identity > requires std::mergeable<ranges::iterator_t<R1>, ranges::iterator_t<R2>, O, Comp, Proj1, Proj2> constexpr set_difference_result<ranges::borrowed_iterator_t<R1>, O> set_difference( R1&& r1, R2&& r2, O result, Comp comp = {}, Proj1 proj1 = {}, Proj2 proj2 = {} ); ``` | (2) | (since C++20) | | Helper types | | | | ``` template<class I, class O> using set_difference_result = ranges::in_out_result<I, O>; ``` | (3) | (since C++20) | Copies the elements from the sorted input range `[first1, last1)` which are not found in the sorted input range `[first2, last2)` to the output range beginning at `result`. The behavior is undefined if. * the input ranges are not sorted with respect to `comp` and `proj1` or `proj2`, respectively, or * the resulting range overlaps with either of the input ranges. 1) Elements are compared using the given binary comparison function `comp`. 2) Same as (1), but uses `r1` as the first range and `r2` as the second range, as if using `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r1)` as `first1`, `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r1)` as `last1`, `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r2)` as `first2`, and `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r2)` as `last2`. The function-like entities described on this page are *niebloids*, that is: * Explicit template argument lists cannot be specified when calling any of them. * None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl"). * When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited. In practice, they may be implemented as function objects, or with special compiler extensions. ### Parameters | | | | | --- | --- | --- | | first1, last1 | - | iterator-sentinel pair denoting the first sorted input range | | first2, last2 | - | iterator-sentinel pair denoting the second sorted input range | | r1 | - | the first sorted input range | | r2 | - | the second sorted input range | | result | - | the beginning of the output range | | comp | - | comparator to apply to the projected elements | | proj1 | - | projection to apply to the elements in the first range | | proj2 | - | projection to apply to the elements in the second range | ### Return value `{last1, result_last}`, where `result_last` is the end of the constructed range. ### Complexity At most \(\scriptsize 2\cdot(N\_1+N\_2)-1\)2·(N 1+N 2)-1 comparisons and applications of each projection, where \(\scriptsize N\_1\)N 1 and \(\scriptsize N\_2\)N 2 are `[ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(first1, last1)` and `[ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(first2, last2)`, respectively. ### Possible implementation | | | --- | | ``` struct set_difference_fn { template< std::input_iterator I1, std::sentinel_for<I1> S1, std::input_iterator I2, std::sentinel_for<I2> S2, std::weakly_incrementable O, class Comp = ranges::less, class Proj1 = std::identity, class Proj2 = std::identity > requires std::mergeable<I1, I2, O, Comp, Proj1, Proj2> constexpr ranges::set_difference_result<I1, O> operator()( I1 first1, S1 last1, I2 first2, S2 last2, O result, Comp comp = {}, Proj1 proj1 = {}, Proj2 proj2 = {} ) const { while (!(first1 == last1 or first2 == last2)) { if (std::invoke(comp, std::invoke(proj1, *first1), std::invoke(proj2, *first2))) { *result = *first1; ++first1; ++result; } else if (std::invoke(comp, std::invoke(proj2, *first2), std::invoke(proj1, *first1))) { ++first2; } else { ++first1; ++first2; } } return ranges::copy(std::move(first1), std::move(last1), std::move(result)); } template< ranges::input_range R1, ranges::input_range R2, std::weakly_incrementable O, class Comp = ranges::less, class Proj1 = std::identity, class Proj2 = std::identity > requires std::mergeable<ranges::iterator_t<R1>, ranges::iterator_t<R2>, O, Comp, Proj1, Proj2> constexpr ranges::set_difference_result< ranges::borrowed_iterator_t<R1>, O> operator()( R1&& r1, R2&& r2, O result, Comp comp = {}, Proj1 proj1 = {}, Proj2 proj2 = {} ) const { return (*this)(ranges::begin(r1), ranges::end(r1), ranges::begin(r2), ranges::end(r2), std::move(result), std::move(comp), std::move(proj1), std::move(proj2)); } }; inline constexpr set_difference_fn set_difference{}; ``` | ### Example ``` #include <algorithm> #include <cassert> #include <iostream> #include <iterator> #include <string_view> #include <vector> auto print = [](const auto& v, std::string_view end = "") { for (std::cout << "{ "; auto i : v) std::cout << i << ' '; std::cout << "} " << end; }; struct Order // a struct with some very interesting data { int order_id; friend std::ostream& operator<<(std::ostream& os, const Order& ord) { return os << "{" << ord.order_id << "},"; } }; int main() { const auto v1 = {1, 2, 5, 5, 5, 9}; const auto v2 = {2, 5, 7}; std::vector<int> diff; std::ranges::set_difference(v1, v2, std::back_inserter(diff)); print(v1, "∖ "); print(v2, "= "); print(diff, "\n"); // we want to know which orders "cut" between old and new states: const std::vector<Order> old_orders { {1}, {2}, {5}, {9}, }; const std::vector<Order> new_orders { {2}, {5}, {7}, }; std::vector<Order> cut_orders(old_orders.size() + new_orders.size()); auto [old_orders_end, cut_orders_last] = std::ranges::set_difference(old_orders, new_orders, cut_orders.begin(), {}, &Order::order_id, &Order::order_id); assert(old_orders_end == old_orders.end()); std::cout << "old orders = "; print(old_orders, "\n"); std::cout << "new orders = "; print(new_orders, "\n"); std::cout << "cut orders = "; print(cut_orders, "\n"); cut_orders.erase(cut_orders_last, end(cut_orders)); std::cout << "cut orders = "; print(cut_orders, "\n"); } ``` Output: ``` { 1 2 5 5 5 9 } ∖ { 2 5 7 } = { 1 5 5 9 } old orders = { {1}, {2}, {5}, {9}, } new orders = { {2}, {5}, {7}, } cut orders = { {1}, {9}, {0}, {0}, {0}, {0}, {0}, } cut orders = { {1}, {9}, } ``` ### See also | | | | --- | --- | | [ranges::set\_union](set_union "cpp/algorithm/ranges/set union") (C++20) | computes the union of two sets (niebloid) | | [ranges::set\_intersection](set_intersection "cpp/algorithm/ranges/set intersection") (C++20) | computes the intersection of two sets (niebloid) | | [ranges::set\_symmetric\_difference](set_symmetric_difference "cpp/algorithm/ranges/set symmetric difference") (C++20) | computes the symmetric difference between two sets (niebloid) | | [ranges::includes](includes "cpp/algorithm/ranges/includes") (C++20) | returns true if one sequence is a subsequence of another (niebloid) | | [set\_difference](../set_difference "cpp/algorithm/set difference") | computes the difference between two sets (function template) | cpp std::ranges::unique_copy, std::ranges::unique_copy_result std::ranges::unique\_copy, std::ranges::unique\_copy\_result ============================================================ | Defined in header `[<algorithm>](../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | Call signature | | | | ``` template< std::input_iterator I, std::sentinel_for<I> S, std::weakly_incrementable O, class Proj = std::identity, std::indirect_equivalence_relation<std::projected<I, Proj>> C = ranges::equal_to > requires std::indirectly_copyable<I, O> && (std::forward_iterator<I> || (std::input_iterator<O> && std::same_as<std::iter_value_t<I>, std::iter_value_t<O>>) || std::indirectly_copyable_storable<I, O>) constexpr unique_copy_result<I, O> unique_copy( I first, S last, O result, C comp = {}, Proj proj = {} ); ``` | (1) | (since C++20) | | ``` template< ranges::input_range R, std::weakly_incrementable O, class Proj = std::identity, std::indirect_equivalence_relation<std::projected<ranges::iterator_t<R>, Proj>> C = ranges::equal_to > requires std::indirectly_copyable<ranges::iterator_t<R>, O> && (std::forward_iterator<ranges::iterator_t<R>> || (std::input_iterator<O> && std::same_as<ranges::range_value_t<R>, std::iter_value_t<O>>) || std::indirectly_copyable_storable<ranges::iterator_t<R>, O>) constexpr unique_copy_result<ranges::borrowed_iterator_t<R>, O> unique_copy( R&& r, O result, C comp = {}, Proj proj = {} ); ``` | (2) | (since C++20) | | Helper types | | | | ``` template<class I, class O> using unique_copy_result = ranges::in_out_result<I, O>; ``` | (3) | (since C++20) | 1) Copies the elements from the source range `[first, last)`, to the destination range beginning at `result` in such a way that there are no consecutive equal elements. Only the first element of each group of equal elements is copied. The ranges `[first, last)` and `[result, result + N)` must not overlap. `N = [ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(first, last)`. Two consecutive elements `*(i - 1)` and `*i` are considered equivalent if `[std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(comp, [std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(proj, \*(i - 1)), [std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(proj, \*i)) == true`, where `i` is an iterator in the range `[first + 1, last)`. 2) Same as (1), but uses `r` as the range, as if using `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r)` as `first`, and `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r)` as `last`. The function-like entities described on this page are *niebloids*, that is: * Explicit template argument lists cannot be specified when calling any of them. * None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl"). * When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited. In practice, they may be implemented as function objects, or with special compiler extensions. ### Parameters | | | | | --- | --- | --- | | first, last | - | the source range of elements | | r | - | the source range of elements | | result | - | the destination range of elements | | comp | - | the binary predicate to compare the projected elements | | proj | - | the projection to apply to the elements | ### Return value `{last, result + N}`. ### Complexity Exactly `N - 1` applications of the corresponding predicate `comp` and no more than twice as many applications of any projection `proj`. ### Possible implementation See also the implementations in [libstdc++](https://github.com/gcc-mirror/gcc/blob/master/libstdc%2B%2B-v3/include/bits/ranges_algo.h#L1198-L1276) and [MSVC STL](https://github.com/microsoft/STL/blob/472161105d596192194d4715ccad307c6c163b4a/stl/inc/algorithm#L4022-L4113) (and third-party libraries: [cmcstl2](https://github.com/CaseyCarter/cmcstl2/blob/master/include/stl2/detail/algorithm/unique_copy.hpp), [NanoRange](https://github.com/tcbrindle/NanoRange/blob/master/include/nanorange/algorithm/unique_copy.hpp), and [range-v3](https://github.com/ericniebler/range-v3/blob/master/include/range/v3/algorithm/unique_copy.hpp)). | | | --- | | ``` struct unique_copy_fn { template<std::input_iterator I, std::sentinel_for<I> S, std::weakly_incrementable O, class Proj = std::identity, std::indirect_equivalence_relation<std::projected<I, Proj>> C = ranges::equal_to> requires std::indirectly_copyable<I, O> && (std::forward_iterator<I> or (std::input_iterator<O> && std::same_as<std::iter_value_t<I>, std::iter_value_t<O>>) or std::indirectly_copyable_storable<I, O>) constexpr ranges::unique_copy_result<I, O> operator() ( I first, S last, O result, C comp = {}, Proj proj = {} ) const { if (!(first == last)) { std::iter_value_t<I> value = *first; *result = value; ++result; while (!(++first == last)) { auto&& value2 = *first; if (!std::invoke(comp, std::invoke(proj, value2), std::invoke(proj, value))) { value = std::forward<decltype(value2)>(value2); *result = value; ++result; } } } return {std::move(first), std::move(result)}; } template<ranges::input_range R, std::weakly_incrementable O, class Proj = std::identity, std::indirect_equivalence_relation<std::projected<ranges::iterator_t<R>, Proj>> C = ranges::equal_to> requires std::indirectly_copyable<ranges::iterator_t<R>, O> && (std::forward_iterator<ranges::iterator_t<R>> or (std::input_iterator<O> && std::same_as<ranges::range_value_t<R>, std::iter_value_t<O>>) || std::indirectly_copyable_storable<ranges::iterator_t<R>, O>) constexpr ranges::unique_copy_result<ranges::borrowed_iterator_t<R>, O> operator() ( R&& r, O result, C comp = {}, Proj proj = {} ) const { return (*this)(ranges::begin(r), ranges::end(r), std::move(result), std::move(comp), std::move(proj)); } }; inline constexpr unique_copy_fn unique_copy{}; ``` | ### Example ``` #include <algorithm> #include <cmath> #include <iostream> #include <iterator> #include <list> #include <string> #include <type_traits> void print(const auto& rem, const auto& v) { using V = std::remove_cvref_t<decltype(v)>; constexpr bool sep {std::is_same_v<typename V::value_type, int>}; std::cout << rem << std::showpos; for (const auto& e : v) std::cout << e << (sep ? " " : ""); std::cout << '\n'; } int main() { std::string s1 {"The string with many spaces!"}; print("s1: ", s1); std::string s2; std::ranges::unique_copy( s1.begin(), s1.end(), std::back_inserter(s2), [](char c1, char c2){ return c1 == ' ' && c2 == ' '; } ); print("s2: ", s2); const auto v1 = { -1, +1, +2, -2, -3, +3, -3, }; print("v1: ", v1); std::list<int> v2; std::ranges::unique_copy( v1, std::back_inserter(v2), {}, // default comparator std::ranges::equal_to [](int x) { return std::abs(x); } // projection ); print("v2: ", v2); } ``` Output: ``` s1: The string with many spaces! s2: The string with many spaces! v1: -1 +1 +2 -2 -3 +3 -3 v2: -1 +2 -3 ``` ### See also | | | | --- | --- | | [ranges::unique](unique "cpp/algorithm/ranges/unique") (C++20) | removes consecutive duplicate elements in a range (niebloid) | | [ranges::copyranges::copy\_if](copy "cpp/algorithm/ranges/copy") (C++20)(C++20) | copies a range of elements to a new location (niebloid) | | [ranges::adjacent\_find](adjacent_find "cpp/algorithm/ranges/adjacent find") (C++20) | finds the first two adjacent items that are equal (or satisfy a given predicate) (niebloid) | | [unique\_copy](../unique_copy "cpp/algorithm/unique copy") | creates a copy of some range of elements that contains no consecutive duplicates (function template) |
programming_docs
cpp std::ranges::find, std::ranges::find_if, std::ranges::find_if_not std::ranges::find, std::ranges::find\_if, std::ranges::find\_if\_not ==================================================================== | Defined in header `[<algorithm>](../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | Call signature | | | | ``` template< std::input_iterator I, std::sentinel_for<I> S, class T, class Proj = std::identity > requires std::indirect_binary_predicate<ranges::equal_to, std::projected<I, Proj>, const T*> constexpr I find( I first, S last, const T& value, Proj proj = {} ); ``` | (1) | (since C++20) | | ``` template< ranges::input_range R, class T, class Proj = std::identity > requires std::indirect_binary_predicate<ranges::equal_to, std::projected<ranges::iterator_t<R>, Proj>, const T*> constexpr ranges::borrowed_iterator_t<R> find( R&& r, const T& value, Proj proj = {} ); ``` | (2) | (since C++20) | | ``` template< std::input_iterator I, std::sentinel_for<I> S, class Proj = std::identity, std::indirect_unary_predicate<std::projected<I, Proj>> Pred > constexpr I find_if( I first, S last, Pred pred, Proj proj = {} ); ``` | (3) | (since C++20) | | ``` template< ranges::input_range R, class Proj = std::identity, std::indirect_unary_predicate<std::projected<ranges::iterator_t<R>, Proj>> Pred > constexpr ranges::borrowed_iterator_t<R> find_if( R&& r, Pred pred, Proj proj = {} ); ``` | (4) | (since C++20) | | ``` template< std::input_iterator I, std::sentinel_for<I> S, class Proj = std::identity, std::indirect_unary_predicate<std::projected<I, Proj>> Pred > constexpr I find_if_not( I first, S last, Pred pred, Proj proj = {} ); ``` | (5) | (since C++20) | | ``` template< ranges::input_range R, class Proj = std::identity, std::indirect_unary_predicate<std::projected<ranges::iterator_t<R>, Proj>> Pred > constexpr ranges::borrowed_iterator_t<R> find_if_not( R&& r, Pred pred, Proj proj = {} ); ``` | (6) | (since C++20) | Returns the first element in the range `[first, last)` that satisfies specific criteria: 1) `find` searches for an element equal to `value` 3) `find_if` searches for an element for which predicate `pred` returns `true` 5) `find_if_not` searches for an element for which predicate `pred` returns `false` 2,4,6) Same as (1,3,5), but uses `r` as the source range, as if using `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r)` as `first` and `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r)` as `last`. The function-like entities described on this page are *niebloids*, that is: * Explicit template argument lists cannot be specified when calling any of them. * None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl"). * When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited. In practice, they may be implemented as function objects, or with special compiler extensions. ### Parameters | | | | | --- | --- | --- | | first, last | - | the range of elements to examine | | r | - | the range of the elements to examine | | value | - | value to compare the elements to | | pred | - | predicate to apply to the projected elements | | proj | - | projection to apply to the elements | ### Return value Iterator to the first element satisfying the condition or iterator equal to `last` if no such element is found. ### Complexity At most `last` - `first` applications of the predicate and projection. ### Possible implementation | First version | | --- | | ``` struct find_fn { template< std::input_iterator I, std::sentinel_for<I> S, class T, class Proj = std::identity > requires std::indirect_binary_predicate<ranges::equal_to, std::projected<I, Proj>, const T*> constexpr I operator()( I first, S last, const T& value, Proj proj = {} ) const { for (; first != last; ++first) { if (std::invoke(proj, *first) == value) { return first; } } return first; } template< ranges::input_range R, class T, class Proj = std::identity > requires std::indirect_binary_predicate<ranges::equal_to, std::projected<ranges::iterator_t<R>, Proj>, const T*> constexpr ranges::borrowed_iterator_t<R> operator()( R&& r, const T& value, Proj proj = {} ) const { return (*this)(ranges::begin(r), ranges::end(r), value, std::ref(proj)); } }; inline constexpr find_fn find; ``` | | Second version | | ``` struct find_if_fn { template< std::input_iterator I, std::sentinel_for<I> S, class Proj = std::identity, std::indirect_unary_predicate<std::projected<I, Proj>> Pred > constexpr I operator()( I first, S last, Pred pred, Proj proj = {} ) const { for (; first != last; ++first) { if (std::invoke(pred, std::invoke(proj, *first))) { return first; } } return first; } template< ranges::input_range R, class Proj = std::identity, std::indirect_unary_predicate<std::projected<ranges::iterator_t<R>, Proj>> Pred > constexpr ranges::borrowed_iterator_t<R> operator()( R&& r, Pred pred, Proj proj = {} ) const { return (*this)(ranges::begin(r), ranges::end(r), std::ref(pred), std::ref(proj)); } }; inline constexpr find_if_fn find_if; ``` | | Third version | | ``` struct find_if_not_fn { template< std::input_iterator I, std::sentinel_for<I> S, class Proj = std::identity, std::indirect_unary_predicate<std::projected<I, Proj>> Pred > constexpr I operator()( I first, S last, Pred pred, Proj proj = {} ) const { for (; first != last; ++first) { if (!std::invoke(pred, std::invoke(proj, *first))) { return first; } } return first; } template< ranges::input_range R, class Proj = std::identity, std::indirect_unary_predicate<std::projected<ranges::iterator_t<R>, Proj>> Pred > constexpr ranges::borrowed_iterator_t<R> operator()( R&& r, Pred pred, Proj proj = {} ) const { return (*this)(ranges::begin(r), ranges::end(r), std::ref(pred), std::ref(proj)); } }; inline constexpr find_if_not_fn find_if_not; ``` | ### Example ``` #include <algorithm> #include <iostream> #include <iterator> int main() { namespace ranges = std::ranges; const int n1 = 3; const int n2 = 5; const auto v = {4, 1, 3, 2}; if (ranges::find(v, n1) != v.end()) { std::cout << "v contains: " << n1 << '\n'; } else { std::cout << "v does not contain: " << n1 << '\n'; } if (ranges::find(v.begin(), v.end(), n2) != v.end()) { std::cout << "v contains: " << n2 << '\n'; } else { std::cout << "v does not contain: " << n2 << '\n'; } auto is_even = [](int x) { return x % 2 == 0; }; if (auto result = ranges::find_if(v.begin(), v.end(), is_even); result != v.end()) { std::cout << "First even element in v: " << *result << '\n'; } else { std::cout << "No even elements in v\n"; } if (auto result = ranges::find_if_not(v, is_even); result != v.end()) { std::cout << "First odd element in v: " << *result << '\n'; } else { std::cout << "No odd elements in v\n"; } auto divides_13 = [](int x) { return x % 13 == 0; }; if (auto result = ranges::find_if(v, divides_13); result != v.end()) { std::cout << "First element divisible by 13 in v: " << *result << '\n'; } else { std::cout << "No elements in v are divisible by 13\n"; } if (auto result = ranges::find_if_not(v.begin(), v.end(), divides_13); result != v.end()) { std::cout << "First element indivisible by 13 in v: " << *result << '\n'; } else { std::cout << "All elements in v are divisible by 13\n"; } } ``` Output: ``` v contains: 3 v does not contain: 5 First even element in v: 4 First odd element in v: 1 No elements in v are divisible by 13 First element indivisible by 13 in v: 4 ``` ### See also | | | | --- | --- | | [ranges::adjacent\_find](adjacent_find "cpp/algorithm/ranges/adjacent find") (C++20) | finds the first two adjacent items that are equal (or satisfy a given predicate) (niebloid) | | [ranges::find\_end](find_end "cpp/algorithm/ranges/find end") (C++20) | finds the last sequence of elements in a certain range (niebloid) | | [ranges::find\_first\_of](find_first_of "cpp/algorithm/ranges/find first of") (C++20) | searches for any one of a set of elements (niebloid) | | [ranges::mismatch](mismatch "cpp/algorithm/ranges/mismatch") (C++20) | finds the first position where two ranges differ (niebloid) | | [ranges::search](search "cpp/algorithm/ranges/search") (C++20) | searches for a range of elements (niebloid) | | [findfind\_iffind\_if\_not](../find "cpp/algorithm/find") (C++11) | finds the first element satisfying specific criteria (function template) | cpp std::ranges::stable_partition std::ranges::stable\_partition ============================== | Defined in header `[<algorithm>](../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | Call signature | | | | ``` template<std::bidirectional_iterator I, std::sentinel_for<I> S, class Proj = std::identity, std::indirect_unary_predicate<std::projected<I, Proj>> Pred> requires std::permutable<I> ranges::subrange<I> stable_partition( I first, S last, Pred pred, Proj proj = {} ); ``` | (1) | (since C++20) | | ``` template<ranges::bidirectional_range R, class Proj = std::identity, std::indirect_unary_predicate<std::projected<ranges::iterator_t<R>, Proj>> Pred> requires std::permutable<ranges::iterator_t<R>> ranges::borrowed_subrange_t<R> stable_partition( R&& r, Pred pred, Proj proj = {} ); ``` | (2) | (since C++20) | 1) Reorders the elements in the range `[first, last)` in such a way that the projection `proj` of all elements for which the predicate `pred` returns `true` precede the projection `proj` of elements for which predicate `pred` returns `false`. The algorithms is *stable*, i.e. the relative order of elements is *preserved*. 2) Same as (1), but uses `r` as the range, as if using `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r)` as `first` and `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r)` as `last`. The function-like entities described on this page are *niebloids*, that is: * Explicit template argument lists cannot be specified when calling any of them. * None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl"). * When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited. In practice, they may be implemented as function objects, or with special compiler extensions. ### Parameters | | | | | --- | --- | --- | | first, last | - | the range of elements to reorder | | r | - | the range of elements to reorder | | pred | - | predicate to apply to the projected elements | | proj | - | projection to apply to the elements. | ### Return value 1) An object equal to `{pivot, last}`, where `pivot` is an iterator to the first element of the second group. 2) Same as (1) if `r` is an lvalue or of a [`borrowed_range`](../../ranges/borrowed_range "cpp/ranges/borrowed range") type. Otherwise returns `[std::ranges::dangling](../../ranges/dangling "cpp/ranges/dangling")`. ### Complexity Given `N = [ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(first, last)`, the complexity is at worst \(\scriptsize N\cdot\log{(N)}\)N·log(N) swaps, and only \(\scriptsize \mathcal{O}(N)\)𝓞(N) swaps in case an extra memory buffer is used. Exactly \(\scriptsize N\)N applications of the predicate `pred` and projection `proj`. ### Notes This function attempts to allocate a temporary buffer. If the allocation fails, the less efficient algorithm is chosen. ### Possible implementation This implementation does not use extra memory buffer and as such can be less efficient. See also the implementation in [MSVC STL](https://github.com/microsoft/STL/blob/e745bad3b1d05b5b19ec652d68abb37865ffa454/stl/inc/algorithm#L5358-L5555) and [libstdc++](https://github.com/gcc-mirror/gcc/blob/master/libstdc%2B%2B-v3/include/bits/ranges_algo.h#L2365-L2394). | | | --- | | ``` struct stable_partition_fn { template<std::bidirectional_iterator I, std::sentinel_for<I> S, class Proj = std::identity, std::indirect_unary_predicate<std::projected<I, Proj>> Pred> requires std::permutable<I> ranges::subrange<I> operator()( I first, S last, Pred pred, Proj proj = {} ) const { first = ranges::find_if_not(first, last, pred, proj); I mid = first; while (mid != last) { mid = ranges::find_if(mid, last, pred, proj); if (mid == last) break; I last2 = ranges::find_if_not(mid, last, pred, proj); ranges::rotate(first, mid, last2); first = ranges::next(first, ranges::distance(mid, last2)); mid = last2; } return {std::move(first), std::move(mid)}; } template<ranges::bidirectional_range R, class Proj = std::identity, std::indirect_unary_predicate<std::projected<ranges::iterator_t<R>, Proj>> Pred> requires std::permutable<ranges::iterator_t<R>> ranges::borrowed_subrange_t<R> operator()( R&& r, Pred pred, Proj proj = {} ) const { return (*this)(ranges::begin(r), ranges::end(r), std::move(pred), std::move(proj)); } }; inline constexpr stable_partition_fn stable_partition{}; ``` | ### Example ``` #include <algorithm> #include <iostream> #include <iterator> #include <vector> namespace rng = std::ranges; template <std::permutable I, std::sentinel_for<I> S> constexpr void stable_sort(I first, S last) { if (first == last) return; auto pivot = *rng::next(first, rng::distance(first, last) / 2, last); auto left = [pivot](const auto& em) { return em < pivot; }; auto tail1 = rng::stable_partition(first, last, left); auto right = [pivot](const auto& em) { return !(pivot < em); }; auto tail2 = rng::stable_partition(tail1, right); stable_sort(first, tail1.begin()); stable_sort(tail2.begin(), tail2.end()); } void print(const auto rem, auto first, auto last, bool end = true) { std::cout << rem; for (; first != last; ++first) { std::cout << *first << ' '; } std::cout << (end ? "\n" : ""); } int main() { const auto original = { 9, 6, 5, 2, 3, 1, 7, 8 }; std::vector<int> vi; auto even = [](int x) { return 0 == (x % 2); }; print("Original vector:\t", original.begin(), original.end(), "\n"); vi = original; const auto ret1 = rng::stable_partition(vi, even); print("Stable partitioned:\t", vi.begin(), ret1.begin(), 0); print("│ ", ret1.begin(), ret1.end()); vi = original; const auto ret2 = rng::partition(vi, even); print("Partitioned:\t\t", vi.begin(), ret2.begin(), 0); print("│ ", ret2.begin(), ret2.end()); vi = {16, 30, 44, 30, 15, 24, 10, 18, 12, 35}; print("Unsorted vector: ", vi.begin(), vi.end()); stable_sort(rng::begin(vi), rng::end(vi)); print("Sorted vector: ", vi.begin(), vi.end()); } ``` Possible output: ``` Original vector: 9 6 5 2 3 1 7 8 Stable partitioned: 6 2 8 │ 9 5 3 1 7 Partitioned: 8 6 2 │ 5 3 1 7 9 Unsorted vector: 16 30 44 30 15 24 10 18 12 35 Sorted vector: 10 12 15 16 18 24 30 30 35 44 ``` ### See also | | | | --- | --- | | [ranges::partition](partition "cpp/algorithm/ranges/partition") (C++20) | divides a range of elements into two groups (niebloid) | | [ranges::partition\_copy](partition_copy "cpp/algorithm/ranges/partition copy") (C++20) | copies a range dividing the elements into two groups (niebloid) | | [ranges::is\_partitioned](is_partitioned "cpp/algorithm/ranges/is partitioned") (C++20) | determines if the range is partitioned by the given predicate (niebloid) | | [stable\_partition](../stable_partition "cpp/algorithm/stable partition") | divides elements into two groups while preserving their relative order (function template) | cpp std::ranges::equal_range std::ranges::equal\_range ========================= | Defined in header `[<algorithm>](../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | Call signature | | | | ``` template< std::forward_iterator I, std::sentinel_for<I> S, class T, class Proj = std::identity, std::indirect_strict_weak_order< const T*, std::projected<I, Proj>> Comp = ranges::less > constexpr ranges::subrange<I> equal_range(I first, S last, const T& value, Comp comp = {}, Proj proj = {}); ``` | (1) | (since C++20) | | ``` template< ranges::forward_range R, class T, class Proj = std::identity, std::indirect_strict_weak_order< const T*, std::projected<ranges::iterator_t<R>, Proj>> Comp = ranges::less > constexpr ranges::borrowed_subrange_t<R> equal_range(R&& r, const T& value, Comp comp = {}, Proj proj = {}); ``` | (2) | (since C++20) | 1) Returns a view containing all elements equivalent to `value` in the range `[first, last)`. The range `[first, last)` must be at least partially ordered with respect to `value`, i.e. it must satisfy all of the following requirements: * partitioned with respect to `element < value` or `comp(element, value)` (that is, all elements for which the expression is `true` precedes all elements for which the expression is `false`) * partitioned with respect to `!(value < element)` or `!comp(value, element)` * for all elements, if `element < value` or `comp(element, value)` is `true` then `!(value < element)` or `!comp(value, element)` is also `true` A fully-sorted range meets these criteria. The returned view is constructed from two iterators, one pointing to the first element that is *not less* than `value` and another pointing to the first element *greater* than `value`. The first iterator may be alternatively obtained with `std::ranges::lower_bound()`, the second - with `std::ranges::upper_bound()`. 2) Same as (1), but uses `r` as the source range, as if using the range `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r)` as `first` and `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r)` as `last`. The function-like entities described on this page are *niebloids*, that is: * Explicit template argument lists cannot be specified when calling any of them. * None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl"). * When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited. In practice, they may be implemented as function objects, or with special compiler extensions. ### Parameters | | | | | --- | --- | --- | | first, last | - | the range of elements to examine | | r | - | the range of the elements to examine | | value | - | value to compare the elements to | | comp | - | if the first argument is *less* than (i.e. is ordered before) the second | | proj | - | projection to apply to the elements | ### Return value `[std::ranges::subrange](../../ranges/subrange "cpp/ranges/subrange")` containing a pair of iterators defining the wanted range, the first pointing to the first element that is *not less* than `value` and the second pointing to the first element *greater* than `value`. If there are no elements *not less* than `value`, the last iterator (iterator that is equal to `last` or `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r)`) is returned as the first element. Similarly if there are no elements *greater* than `value`, the last iterator is returned as the second element. ### Complexity The number of comparisons performed is logarithmic in the distance between `first` and `last` (At most 2 \* log 2(last - first) + O(1) comparisons). However, for an iterator that does not model [`random_access_iterator`](../../iterator/random_access_iterator "cpp/iterator/random access iterator"), the number of iterator increments is linear. ### Possible implementation | | | --- | | ``` struct equal_range_fn { template< std::forward_iterator I, std::sentinel_for<I> S, class T, class Proj = std::identity, std::indirect_strict_weak_order< const T*, std::projected<I, Proj>> Comp = ranges::less > constexpr ranges::subrange<I> operator()(I first, S last, const T& value, Comp comp = {}, Proj proj = {}) const { return ranges::subrange( ranges::lower_bound(first, last, value, std::ref(comp), std::ref(proj)), ranges::upper_bound(first, last, value, std::ref(comp), std::ref(proj))); } template< ranges::forward_range R, class T, class Proj = std::identity, std::indirect_strict_weak_order< const T*, std::projected<std::ranges::iterator_t<R>, Proj>> Comp = ranges::less > constexpr ranges::borrowed_subrange_t<R> operator()(R&& r, const T& value, Comp comp = {}, Proj proj = {}) const { return (*this)(ranges::begin(r), ranges::end(r), value, std::ref(comp), std::ref(proj)); } }; inline constexpr equal_range_fn equal_range; ``` | ### Example ``` #include <algorithm> #include <compare> #include <vector> #include <iostream> struct S { int number; char name; // note: name is ignored by these comparison operators friend bool operator== ( const S s1, const S s2 ) { return s1.number == s2.number; } friend auto operator<=> ( const S s1, const S s2 ) { return s1.number <=> s2.number; } }; int main() { // note: not ordered, only partitioned w.r.t. S defined below std::vector<S> vec = { {1,'A'}, {2,'B'}, {2,'C'}, {2,'D'}, {4, 'D'}, {4,'G'}, {3,'F'} }; const S value = {2, '?'}; namespace ranges = std::ranges; { auto p = ranges::equal_range(vec, value); std::cout << "1. "; for ( auto i : p ) std::cout << i.name << ' '; } { auto p = ranges::equal_range(vec.begin(), vec.end(), value); std::cout << "\n2. "; for ( auto i = p.begin(); i != p.end(); ++i ) std::cout << i->name << ' '; } { auto p = ranges::equal_range(vec, 'D', ranges::less{}, &S::name); std::cout << "\n3. "; for ( auto i : p ) std::cout << i.name << ' '; } { auto p = ranges::equal_range(vec.begin(), vec.end(), 'D', ranges::less{}, &S::name); std::cout << "\n4. "; for ( auto i = p.begin(); i != p.end(); ++i ) std::cout << i->name << ' '; } } ``` Output: ``` 1. B C D 2. B C D 3. D D 4. D D ``` ### See also | | | | --- | --- | | [ranges::lower\_bound](lower_bound "cpp/algorithm/ranges/lower bound") (C++20) | returns an iterator to the first element *not less* than the given value (niebloid) | | [ranges::upper\_bound](upper_bound "cpp/algorithm/ranges/upper bound") (C++20) | returns an iterator to the first element *greater* than a certain value (niebloid) | | [ranges::binary\_search](binary_search "cpp/algorithm/ranges/binary search") (C++20) | determines if an element exists in a partially-ordered range (niebloid) | | [ranges::partition](partition "cpp/algorithm/ranges/partition") (C++20) | divides a range of elements into two groups (niebloid) | | [ranges::equal](equal "cpp/algorithm/ranges/equal") (C++20) | determines if two sets of elements are the same (niebloid) | | [equal\_range](../equal_range "cpp/algorithm/equal range") | returns range of elements matching a specific key (function template) |
programming_docs
cpp std::ranges::rotate_copy, std::ranges::rotate_copy_result std::ranges::rotate\_copy, std::ranges::rotate\_copy\_result ============================================================ | Defined in header `[<algorithm>](../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | Call signature | | | | ``` template< std::forward_iterator I, std::sentinel_for<I> S, std::weakly_incrementable O > requires std::indirectly_copyable<I, O> constexpr rotate_copy_result<I, O> rotate_copy( I first, I middle, S last, O result ); ``` | (1) | (since C++20) | | ``` template< ranges::forward_range R, std::weakly_incrementable O > requires std::indirectly_copyable<ranges::iterator_t<R>, O> constexpr rotate_copy_result<ranges::borrowed_iterator_t<R>, O> rotate_copy( R&& r, ranges::iterator_t<R> middle, O result ); ``` | (2) | (since C++20) | | Helper types | | | | ``` template< class I, class O > using rotate_copy_result = in_out_result<I, O>; ``` | (3) | (since C++20) | 1) Copies the elements from the source range `[first, last)`, to the destination range beginning at `result` in such a way, that the element `*middle` becomes the first element of the destination range and `*(middle - 1)` becomes the last element. The result is that the destination range contains a *left rotated* copy of the source range. The behavior is undefined if either `[first, middle)` or `[middle, last)` is not a valid range, or the source and destination ranges overlap. 2) Same as (1), but uses `r` as the source range, as if using `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r)` as `first` and `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r)` as `last`. The function-like entities described on this page are *niebloids*, that is: * Explicit template argument lists cannot be specified when calling any of them. * None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl"). * When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited. In practice, they may be implemented as function objects, or with special compiler extensions. ### Parameters | | | | | --- | --- | --- | | first, last | - | the source range of elements to copy from | | r | - | the source range of elements to copy from | | middle | - | the iterator to the element that should appear at the beginning of the destination range | | result | - | beginning of the destination range | ### Return value `{last, result + N}`, where `N = [ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(first, last)`. ### Complexity *Linear*: exactly `N` assignments. ### Notes If the value type is [TriviallyCopyable](../../named_req/triviallycopyable "cpp/named req/TriviallyCopyable") and the iterator types satisfy [`contiguous_iterator`](../../iterator/contiguous_iterator "cpp/iterator/contiguous iterator"), implementations of `ranges::rotate_copy` usually avoid multiple assignments by using a "bulk copy" function such as `[std::memmove](../../string/byte/memmove "cpp/string/byte/memmove")`. ### Possible implementation See also the implementations in [libstdc++](https://github.com/gcc-mirror/gcc/blob/14d8a5ae472ca5743016f37da2dd4770d83dea21/libstdc%2B%2B-v3/include/bits/ranges_algo.h#L1511-L1539) and [MSVC STL](https://github.com/microsoft/STL/blob/472161105d596192194d4715ccad307c6c163b4a/stl/inc/algorithm#L4466-L4514). | | | --- | | ``` struct rotate_copy_fn { template<std::forward_iterator I, std::sentinel_for<I> S, std::weakly_incrementable O> requires std::indirectly_copyable<I, O> constexpr ranges::rotate_copy_result<I, O> operator() ( I first, I middle, S last, O result ) const { auto c1{ ranges::copy(middle, std::move(last), std::move(result)) }; auto c2{ ranges::copy(std::move(first), std::move(middle), std::move(c1.out)) }; return { std::move(c1.in), std::move(c2.out) }; } template<ranges::forward_range R, std::weakly_incrementable O> requires std::indirectly_copyable<ranges::iterator_t<R>, O> constexpr ranges::rotate_copy_result<ranges::borrowed_iterator_t<R>, O> operator() ( R&& r, ranges::iterator_t<R> middle, O result ) const { return (*this)(ranges::begin(r), std::move(middle), ranges::end(r), std::move(result)); } }; inline constexpr rotate_copy_fn rotate_copy{}; ``` | ### Example ``` #include <algorithm> #include <iostream> #include <iterator> #include <vector> int main() { std::vector<int> src {1, 2, 3, 4, 5}; std::vector<int> dest(src.size()); auto pivot = std::ranges::find(src, 3); std::ranges::rotate_copy(src, pivot, dest.begin()); for (int i : dest) { std::cout << i << ' '; } std::cout << '\n'; // copy the rotation result directly to the std::cout pivot = std::ranges::find(dest, 1); std::ranges::rotate_copy(dest, pivot, std::ostream_iterator<int>(std::cout, " ")); std::cout << '\n'; } ``` Output: ``` 3 4 5 1 2 1 2 3 4 5 ``` ### See also | | | | --- | --- | | [ranges::rotate](rotate "cpp/algorithm/ranges/rotate") (C++20) | rotates the order of elements in a range (niebloid) | | [ranges::copyranges::copy\_if](copy "cpp/algorithm/ranges/copy") (C++20)(C++20) | copies a range of elements to a new location (niebloid) | | [rotate\_copy](../rotate_copy "cpp/algorithm/rotate copy") | copies and rotate a range of elements (function template) | cpp std::ranges::partial_sort_copy, std::ranges::partial_sort_copy_result std::ranges::partial\_sort\_copy, std::ranges::partial\_sort\_copy\_result ========================================================================== | Defined in header `[<algorithm>](../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | Call signature | | | | ``` template< std::input_iterator I1, std::sentinel_for<I1> S1, std::random_access_iterator I2, std::sentinel_for<I2> S2, class Comp = ranges::less, class Proj1 = std::identity, class Proj2 = std::identity > requires std::indirectly_copyable<I1, I2> && std::sortable<I2, Comp, Proj2> && std::indirect_strict_weak_order<Comp, std::projected<I1, Proj1>, std::projected<I2, Proj2>> constexpr partial_sort_copy_result<I1, I2> partial_sort_copy( I1 first, S1 last, I2 result_first, S2 result_last, Comp comp = {}, Proj1 proj1 = {}, Proj2 proj2 = {} ); ``` | (1) | (since C++20) | | ``` template< ranges::input_range R1, ranges::random_access_range R2, class Comp = ranges::less, class Proj1 = std::identity, class Proj2 = std::identity > requires std::indirectly_copyable<ranges::iterator_t<R1>, ranges::iterator_t<R2>> && std::sortable<ranges::iterator_t<R2>, Comp, Proj2> && std::indirect_strict_weak_order<Comp, std::projected<ranges::iterator_t<R1>, Proj1>, std::projected<ranges::iterator_t<R2>, Proj2>> constexpr partial_sort_copy_result<ranges::borrowed_iterator_t<R1>, ranges::borrowed_iterator_t<R2>> partial_sort_copy( R1&& r, R2&& result_r, Comp comp = {}, Proj1 proj1 = {}, Proj2 proj2 = {} ); ``` | (2) | (since C++20) | | Helper types | | | | ``` template<class I, class O> using partial_sort_copy_result = ranges::in_out_result<I, O>; ``` | (3) | (since C++20) | Copies the first `N` elements from the source range `[first, last)`, as if it was partially sorted with respect to `comp` and `proj1`, into the destination range `[result_first, result_first + N)`, where \(\scriptsize N = \min{(L\_1, L\_2)}\)N = min(L₁, L₂), \(\scriptsize L\_1\)L₁ is equal to `[ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(first, last)`, and \(\scriptsize L\_2\)L₂ is equal to `[ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(result_first, result_last)`. The order of equal elements is *not* guaranteed to be preserved. 1) The source range elements are projected using the function object `proj1`, and the destination elements are projected using the function object `proj2`. 2) Same as (1), but uses `r` as the source range and `result_r` as the destination range, as if using `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r)` as `first`, `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r)` as `last`, `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(result_r)` as `result_first`, and `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(result_r)` as `result_last`. The function-like entities described on this page are *niebloids*, that is: * Explicit template argument lists cannot be specified when calling any of them. * None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl"). * When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited. In practice, they may be implemented as function objects, or with special compiler extensions. ### Parameters | | | | | --- | --- | --- | | first, last | - | iterator-sentinel defining the source range to copy from | | r | - | the source range to copy from | | result\_first, result\_last | - | iterator-sentinel defining the destination range | | result\_r | - | the destination range | | comp | - | comparison to apply to the projected elements | | proj1 | - | projection to apply to the elements of source range | | proj2 | - | projection to apply to the elements of destination range | ### Return value An object equal to `{last, result_first + N}`. ### Complexity At most \(\scriptsize L\_1 \cdot \log{(N)}\)L₁•log(N) comparisons and \(\scriptsize 2 \cdot L\_1 \cdot \log{(N)}\)2•L₁•log(N) projections. ### Possible implementation | | | --- | | ``` struct partial_sort_copy_fn { template< std::input_iterator I1, std::sentinel_for<I1> S1, std::random_access_iterator I2, std::sentinel_for<I2> S2, class Comp = ranges::less, class Proj1 = std::identity, class Proj2 = std::identity > requires std::indirectly_copyable<I1, I2> && std::sortable<I2, Comp, Proj2> && std::indirect_strict_weak_order<Comp, std::projected<I1, Proj1>, std::projected<I2, Proj2>> constexpr ranges::partial_sort_copy_result<I1, I2> operator()( I1 first, S1 last, I2 result_first, S2 result_last, Comp comp = {}, Proj1 proj1 = {}, Proj2 proj2 = {} ) const { if (result_first == result_last) { return {std::move(ranges::next(std::move(first), std::move(last))), std::move(result_first)}; } auto out_last {result_first}; // copy first N elements for (; !(first == last or out_last == result_last); ++out_last, ++first) { *out_last = *first; } // convert N copied elements into a max-heap ranges::make_heap(result_first, out_last, comp, proj2); // process the rest of the input range (if any), preserving the heap property for (; first != last; ++first) { if (std::invoke(comp, std::invoke(proj1, *first), std::invoke(proj2, *result_first))) { // pop out the biggest item and push in a newly found smaller one ranges::pop_heap(result_first, out_last, comp, proj2); *(out_last - 1) = *first; ranges::push_heap(result_first, out_last, comp, proj2); } } // first N elements in the output range is still a heap - convert it into a sorted range ranges::sort_heap(result_first, out_last, comp, proj2); return {std::move(first), std::move(out_last)}; } template< ranges::input_range R1, ranges::random_access_range R2, class Comp = ranges::less, class Proj1 = std::identity, class Proj2 = std::identity > requires std::indirectly_copyable<ranges::iterator_t<R1>, ranges::iterator_t<R2>> && std::sortable<ranges::iterator_t<R2>, Comp, Proj2> && std::indirect_strict_weak_order<Comp, std::projected<ranges::iterator_t<R1>, Proj1>, std::projected<ranges::iterator_t<R2>, Proj2>> constexpr ranges::partial_sort_copy_result<ranges::borrowed_iterator_t<R1>, ranges::borrowed_iterator_t<R2>> operator()( R1&& r, R2&& result_r, Comp comp = {}, Proj1 proj1 = {}, Proj2 proj2 = {} ) const { return (*this)(ranges::begin(r), ranges::end(r), ranges::begin(result_r), ranges::end(result_r), std::move(comp), std::move(proj1), std::move(proj2)); } }; inline constexpr partial_sort_copy_fn partial_sort_copy{}; ``` | ### Example ``` #include <algorithm> #include <forward_list> #include <functional> #include <iostream> #include <ranges> #include <string_view> #include <vector> void print(std::string_view rem, std::ranges::input_range auto const& v) { for (std::cout << rem; const auto& e : v) std::cout << e << ' '; std::cout << '\n'; } int main() { const std::forward_list source{4, 2, 5, 1, 3}; print("Write to the smaller vector in ascending order: ", ""); std::vector dest1{10, 11, 12}; print("const source list: ", source); print("destination range: ", dest1); std::ranges::partial_sort_copy(source, dest1); print("partial_sort_copy: ", dest1); print("Write to the larger vector in descending order:", ""); std::vector dest2{10, 11, 12, 13, 14, 15, 16}; print("const source list: ", source); print("destination range: ", dest2); std::ranges::partial_sort_copy(source, dest2, std::greater{}); print("partial_sort_copy: ", dest2); } ``` Output: ``` Write to the smaller vector in ascending order: const source list: 4 2 5 1 3 destination range: 10 11 12 partial_sort_copy: 1 2 3 Write to the larger vector in descending order: const source list: 4 2 5 1 3 destination range: 10 11 12 13 14 15 16 partial_sort_copy: 5 4 3 2 1 15 16 ``` ### See also | | | | --- | --- | | [ranges::partial\_sort](partial_sort "cpp/algorithm/ranges/partial sort") (C++20) | sorts the first N elements of a range (niebloid) | | [ranges::sort](sort "cpp/algorithm/ranges/sort") (C++20) | sorts a range into ascending order (niebloid) | | [ranges::stable\_sort](stable_sort "cpp/algorithm/ranges/stable sort") (C++20) | sorts a range of elements while preserving order between equal elements (niebloid) | | [ranges::sort\_heap](sort_heap "cpp/algorithm/ranges/sort heap") (C++20) | turns a max heap into a range of elements sorted in ascending order (niebloid) | | [ranges::make\_heap](make_heap "cpp/algorithm/ranges/make heap") (C++20) | creates a max heap out of a range of elements (niebloid) | | [ranges::push\_heap](push_heap "cpp/algorithm/ranges/push heap") (C++20) | adds an element to a max heap (niebloid) | | [ranges::pop\_heap](pop_heap "cpp/algorithm/ranges/pop heap") (C++20) | removes the largest element from a max heap (niebloid) | | [partial\_sort\_copy](../partial_sort_copy "cpp/algorithm/partial sort copy") | copies and partially sorts a range of elements (function template) | cpp std::ranges::set_intersection, std::ranges::set_intersection_result std::ranges::set\_intersection, std::ranges::set\_intersection\_result ====================================================================== | Defined in header `[<algorithm>](../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | Call signature | | | | ``` template< std::input_iterator I1, std::sentinel_for<I1> S1, std::input_iterator I2, std::sentinel_for<I2> S2, std::weakly_incrementable O, class Comp = ranges::less, class Proj1 = std::identity, class Proj2 = std::identity > requires std::mergeable<I1, I2, O, Comp, Proj1, Proj2> constexpr set_intersection_result<I1, I2, O> set_intersection( I1 first1, S1 last1, I2 first2, S2 last2, O result, Comp comp = {}, Proj1 proj1 = {}, Proj2 proj2 = {} ); ``` | (1) | (since C++20) | | ``` template< ranges::input_range R1, ranges::input_range R2, std::weakly_incrementable O, class Comp = ranges::less, class Proj1 = std::identity, class Proj2 = std::identity > requires std::mergeable<ranges::iterator_t<R1>, ranges::iterator_t<R2>, O, Comp, Proj1, Proj2> constexpr set_intersection_result<ranges::borrowed_iterator_t<R1>, ranges::borrowed_iterator_t<R2>, O> set_intersection( R1&& r1, R2&& r2, O result, Comp comp = {}, Proj1 proj1 = {}, Proj2 proj2 = {} ); ``` | (2) | (since C++20) | | Helper types | | | | ``` template< class I1, class I2, class O > using set_intersection_result = ranges::in_in_out_result<I1, I2, O>; ``` | (3) | (since C++20) | Constructs a sorted range beginning at `result` consisting of elements that are found in both sorted input ranges `[first1, last1)` and `[first2, last2)`. If some element is found `m` times in `[first1, last1)` and `n` times in `[first2, last2)`, the first `min(m, n)` elements will be copied from the first range to `result`. The order of equivalent elements is preserved. The behavior is undefined if. * the input ranges are not sorted with respect to `comp` and `proj1` or `proj2`, respectively, or * the resulting range overlaps with either of the input ranges. 1) Elements are compared using the given binary comparison function `comp`. 2) Same as (1), but uses `r1` as the first range and `r2` as the second range, as if using `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r1)` as `first1`, `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r1)` as `last1`, `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r2)` as `first2`, and `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r2)` as `last2`. The function-like entities described on this page are *niebloids*, that is: * Explicit template argument lists cannot be specified when calling any of them. * None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl"). * When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited. In practice, they may be implemented as function objects, or with special compiler extensions. ### Parameters | | | | | --- | --- | --- | | first1, last1 | - | iterator-sentinel pair denoting the first input sorted range | | first2, last2 | - | iterator-sentinel pair denoting the second input sorted range | | r1 | - | the first sorted input range | | r2 | - | the second sorted input range | | result | - | the beginning of the output range | | comp | - | comparison to apply to the projected elements | | proj1 | - | projection to apply to the elements in the first range | | proj2 | - | projection to apply to the elements in the second range | ### Return value `{last1, last2, result_last}`, where `result_last` is the end of the constructed range. ### Complexity At most \(\scriptsize 2\cdot(N\_1+N\_2)-1\)2·(N 1+N 2)-1 comparisons and applications of each projection, where \(\scriptsize N\_1\)N 1 and \(\scriptsize N\_2\)N 2 are `[ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(first1, last1)` and `[ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(first2, last2)`, respectively. ### Possible implementation | | | --- | | ``` struct set_intersection_fn { template< std::input_iterator I1, std::sentinel_for<I1> S1, std::input_iterator I2, std::sentinel_for<I2> S2, std::weakly_incrementable O, class Comp = ranges::less, class Proj1 = std::identity, class Proj2 = std::identity > requires std::mergeable<I1, I2, O, Comp, Proj1, Proj2> constexpr ranges::set_union_result<I1, I2, O> operator()( I1 first1, S1 last1, I2 first2, S2 last2, O result, Comp comp = {}, Proj1 proj1 = {}, Proj2 proj2 = {} ) const { while (!(first1 == last1 or first2 == last2)) { if (std::invoke(comp, std::invoke(proj1, *first1), std::invoke(proj2, *first2))) ++first1; else if (std::invoke(comp, std::invoke(proj2, *first2), std::invoke(proj1, *first1))) ++first2; else *result = *first1, ++first1, ++first2, ++result; } return {ranges::next(std::move(first1), std::move(last1)), ranges::next(std::move(first2), std::move(last2)), std::move(result)}; } template< ranges::input_range R1, ranges::input_range R2, std::weakly_incrementable O, class Comp = ranges::less, class Proj1 = std::identity, class Proj2 = std::identity > requires std::mergeable<ranges::iterator_t<R1>, ranges::iterator_t<R2>, O, Comp, Proj1, Proj2> constexpr ranges::set_intersection_result<ranges::borrowed_iterator_t<R1>, ranges::borrowed_iterator_t<R2>, O> operator()( R1&& r1, R2&& r2, O result, Comp comp = {}, Proj1 proj1 = {}, Proj2 proj2 = {} ) const { return (*this)(ranges::begin(r1), ranges::end(r1), ranges::begin(r2), ranges::end(r2), std::move(result), std::move(comp), std::move(proj1), std::move(proj2)); } }; inline constexpr set_intersection_fn set_intersection{}; ``` | ### Example ``` #include <algorithm> #include <iostream> #include <iterator> #include <vector> void print(const auto& v, const auto& rem) { std::cout << "{ "; for (const auto& e : v) std::cout << e << ' '; std::cout << "}" << rem; } int main() { const auto in1 = {1, 2, 2, 3, 4, 5, 6 }; const auto in2 = {2, 2, 3, 3, 5, 7}; std::vector<int> out; std::ranges::set_intersection(in1, in2, std::back_inserter(out)); print(in1, " ∩ "), print(in2, " = "), print(out, "\n"); } ``` Output: ``` { 1 2 2 3 4 5 6 } ∩ { 2 2 3 3 5 7 } = { 2 2 3 5 } ``` ### See also | | | | --- | --- | | [ranges::set\_union](set_union "cpp/algorithm/ranges/set union") (C++20) | computes the union of two sets (niebloid) | | [ranges::set\_difference](set_difference "cpp/algorithm/ranges/set difference") (C++20) | computes the difference between two sets (niebloid) | | [ranges::set\_symmetric\_difference](set_symmetric_difference "cpp/algorithm/ranges/set symmetric difference") (C++20) | computes the symmetric difference between two sets (niebloid) | | [ranges::includes](includes "cpp/algorithm/ranges/includes") (C++20) | returns true if one sequence is a subsequence of another (niebloid) | | [set\_intersection](../set_intersection "cpp/algorithm/set intersection") | computes the intersection of two sets (function template) |
programming_docs
cpp std::ranges::rotate std::ranges::rotate =================== | Defined in header `[<algorithm>](../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | Call signature | | | | ``` template< std::permutable I, std::sentinel_for<I> S > constexpr ranges::subrange<I> rotate( I first, I middle, S last ); ``` | (1) | (since C++20) | | ``` template< ranges::forward_range R > requires std::permutable<ranges::iterator_t<R>> constexpr ranges::borrowed_subrange_t<R> rotate( R&& r, ranges::iterator_t<R> middle ); ``` | (2) | (since C++20) | 1) Performs a *left rotation* on a range of elements. Specifically, `ranges::rotate` swaps the elements in the range `[first, last)` in such a way that the element `*middle` becomes the first element of the new range and `*(middle - 1)` becomes the last element. The behavior is undefined if `[first, last)` is not a valid range or `middle` is not in `[first, last)`. 2) Same as (1), but uses `r` as the range, as if using `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r)` as `first` and `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r)` as `last`. The function-like entities described on this page are *niebloids*, that is: * Explicit template argument lists cannot be specified when calling any of them. * None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl"). * When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited. In practice, they may be implemented as function objects, or with special compiler extensions. ### Parameters | | | | | --- | --- | --- | | first, last | - | the range of elements to rotate | | r | - | the range of elements to rotate | | middle | - | the iterator to the element that should appear at the beginning of the rotated range | ### Return value `{new_first, last}`, where `*new\_first*` compares equal to `[ranges::next](http://en.cppreference.com/w/cpp/iterator/ranges/next)(first, [ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(middle, last))` and designates a new location of the element pointed by `first`. ### Complexity *Linear* at worst: `[ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(first, last)` swaps. ### Notes `ranges::rotate` has better efficiency on common implementations if `I` models [`bidirectional_iterator`](../../iterator/bidirectional_iterator "cpp/iterator/bidirectional iterator") or (better) [`random_access_iterator`](../../iterator/random_access_iterator "cpp/iterator/random access iterator"). Implementations (e.g. [MSVC STL](https://github.com/microsoft/STL/blob/main/stl/src/vector_algorithms.cpp)) may enable vectorization when the iterator type models [`contiguous_iterator`](../../iterator/contiguous_iterator "cpp/iterator/contiguous iterator") and swapping its value type calls neither non-trivial special member function nor [ADL](../../language/adl "cpp/language/adl")-found `swap`. ### Possible implementation See also the implementations in [libstdc++](https://github.com/gcc-mirror/gcc/blob/14d8a5ae472ca5743016f37da2dd4770d83dea21/libstdc%2B%2B-v3/include/bits/ranges_algo.h#L1361-L1506) and [MSVC STL](https://github.com/microsoft/STL/blob/472161105d596192194d4715ccad307c6c163b4a/stl/inc/algorithm#L4407-L4434). | | | --- | | ``` struct rotate_fn { template<std::permutable I, std::sentinel_for<I> S> constexpr ranges::subrange<I> operator() ( I first, I middle, S last ) const { if (first == middle) { auto last_it{ranges::next(first, last)}; return {last_it, last_it}; } if (middle == last) return {std::move(first), std::move(middle)}; if constexpr (std::bidirectional_iterator<I>) { ranges::reverse(first, middle); auto last_it{ranges::next(first, last)}; ranges::reverse(middle, last_it); if constexpr (std::random_access_iterator<I>) { ranges::reverse(first, last_it); return {first + (last_it - middle), std::move(last_it)}; } else { auto mid_last{last_it}; do { ranges::iter_swap(first, --mid_last); ++first; } while (first != middle && mid_last != middle); ranges::reverse(first, mid_last); if (first == middle) return {std::move(mid_last), std::move(last_it)}; else return {std::move(first), std::move(last_it)}; } } else { // I is merely a forward_iterator auto next_it{middle}; do { // rotate the first cycle ranges::iter_swap(first, next_it); ++first; ++next_it; if (first == middle) middle = next_it; } while (next_it != last); auto new_first{first}; while (middle != last) { // rotate subsequent cycles next_it = middle; do { ranges::iter_swap(first, next_it); ++first; ++next_it; if (first == middle) middle = next_it; } while (next_it != last); } return {std::move(new_first), std::move(middle)}; } } template<ranges::forward_range R> requires std::permutable<ranges::iterator_t<R>> constexpr ranges::borrowed_subrange_t<R> operator() ( R&& r, ranges::iterator_t<R> middle ) const { return (*this)(ranges::begin(r), std::move(middle), ranges::end(r)); } }; inline constexpr rotate_fn rotate{}; ``` | ### Example The *`rotate`* algorithm can be used as a common building block in many other algorithms, e.g. *insertion sort*: ``` #include <algorithm> #include <iostream> #include <numeric> #include <string> #include <vector> int main() { std::string s(16, ' '); for (int k{}; k != 5; ++k) { std::iota(s.begin(), s.end(), 'A'); std::ranges::rotate(s, s.begin() + k); std::cout << "Rotate left (" << k << "): " << s << '\n'; } std::cout << '\n'; for (int k{}; k != 5; ++k) { std::iota(s.begin(), s.end(), 'A'); std::ranges::rotate(s, s.end() - k); std::cout << "Rotate right (" << k << "): " << s << '\n'; } std::cout << "\n" "Insertion sort using `rotate`, step-by-step:\n"; s = {'2', '4', '2', '0', '5', '9', '7', '3', '7', '1'}; for (auto i = s.begin(); i != s.end(); ++i) { std::cout << "i = " << std::ranges::distance(s.begin(), i) << ": "; std::ranges::rotate(std::ranges::upper_bound(s.begin(), i, *i), i, i + 1); std::cout << s << '\n'; } std::cout << (std::ranges::is_sorted(s) ? "Sorted!" : "Not sorted.") << '\n'; } ``` Output: ``` Rotate left (0): ABCDEFGHIJKLMNOP Rotate left (1): BCDEFGHIJKLMNOPA Rotate left (2): CDEFGHIJKLMNOPAB Rotate left (3): DEFGHIJKLMNOPABC Rotate left (4): EFGHIJKLMNOPABCD Rotate right (0): ABCDEFGHIJKLMNOP Rotate right (1): PABCDEFGHIJKLMNO Rotate right (2): OPABCDEFGHIJKLMN Rotate right (3): NOPABCDEFGHIJKLM Rotate right (4): MNOPABCDEFGHIJKL Insertion sort using `rotate`, step-by-step: i = 0: 2420597371 i = 1: 2420597371 i = 2: 2240597371 i = 3: 0224597371 i = 4: 0224597371 i = 5: 0224597371 i = 6: 0224579371 i = 7: 0223457971 i = 8: 0223457791 i = 9: 0122345779 Sorted! ``` ### See also | | | | --- | --- | | [ranges::rotate\_copy](rotate_copy "cpp/algorithm/ranges/rotate copy") (C++20) | copies and rotate a range of elements (niebloid) | | [ranges::reverse](reverse "cpp/algorithm/ranges/reverse") (C++20) | reverses the order of elements in a range (niebloid) | | [rotate](../rotate "cpp/algorithm/rotate") | rotates the order of elements in a range (function template) | cpp std::ranges::replace_copy, std::ranges::replace_copy_if, std::ranges::replace_copy_result, std::ranges::replace_copy_if_result std::ranges::replace\_copy, std::ranges::replace\_copy\_if, std::ranges::replace\_copy\_result, std::ranges::replace\_copy\_if\_result ====================================================================================================================================== | Defined in header `[<algorithm>](../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | Call signature | | | | ``` template< std::input_iterator I, std::sentinel_for<I> S, class T1, class T2, std::output_iterator<const T2&> O, class Proj = std::identity > requires std::indirectly_copyable<I, O> && std::indirect_binary_predicate<ranges::equal_to, std::projected<I, Proj>, const T1*> constexpr replace_copy_result<I, O> replace_copy( I first, S last, O result, const T1& old_value, const T2& new_value, Proj proj = {} ); ``` | (1) | (since C++20) | | ``` template< ranges::input_range R, class T1, class T2, std::output_iterator<const T2&> O, class Proj = std::identity > requires std::indirectly_copyable<ranges::iterator_t<R>, O> && std::indirect_binary_predicate<ranges::equal_to, std::projected<ranges::iterator_t<R>, Proj>, const T1*> constexpr replace_copy_result<ranges::borrowed_iterator_t<R>, O> replace_copy( R&& r, O result, const T1& old_value, const T2& new_value, Proj proj = {} ); ``` | (2) | (since C++20) | | ``` template< std::input_iterator I, std::sentinel_for<I> S, class T, std::output_iterator<const T&> O, class Proj = std::identity, std::indirect_unary_predicate<std::projected<I, Proj>> Pred > requires std::indirectly_copyable<I, O> constexpr replace_copy_if_result<I, O> replace_copy_if( I first, S last, O result, Pred pred, const T& new_value, Proj proj = {} ); ``` | (3) | (since C++20) | | ``` template< ranges::input_range R, class T, std::output_iterator<const T&> O, class Proj = std::identity, std::indirect_unary_predicate<std::projected<ranges::iterator_t<R>, Proj>> Pred > requires std::indirectly_copyable<ranges::iterator_t<R>, O> constexpr replace_copy_if_result<ranges::borrowed_iterator_t<R>, O> replace_copy_if( R&& r, O result, Pred pred, const T& new_value, Proj proj = {} ); ``` | (4) | (since C++20) | | Helper types | | | | ``` template< class I, class O > using replace_copy_result = ranges::in_out_result<I, O>; ``` | (5) | (since C++20) | | ``` template< class I, class O > using replace_copy_if_result = ranges::in_out_result<I, O>; ``` | (6) | (since C++20) | Copies the elements from the source range `[first, last)` to the destination range beginning at `result`, replacing all elements satisfying specific criteria with `new_value`. The behavior is undefined if the source and destination ranges overlap. 1) Replaces all elements that are equal to `old_value`, using `[std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(proj, \*(first + (i - result))) == old_value` to compare. 3) Replaces all elements for which the predicate `pred` evaluates to `true`, where the evaluating expression is `[std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(pred, [std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(proj, \*(first + (i - result))))`. 2,4) Same as (1,3), but uses `r` as the soruce range, as if using `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r)` as `first`, and `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r)` as `last`. The function-like entities described on this page are *niebloids*, that is: * Explicit template argument lists cannot be specified when calling any of them. * None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl"). * When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited. In practice, they may be implemented as function objects, or with special compiler extensions. ### Parameters | | | | | --- | --- | --- | | first, last | - | the range of elements to copy | | r | - | the range of elements to copy | | result | - | the beginning of the destination range | | old\_value | - | the value of elements to replace | | new\_value | - | the value to use as a replacement | | pred | - | predicate to apply to the projected elements | | proj | - | projection to apply to the elements. | ### Return value `{last, result + N}`, where. 1,3) `N = [ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(first, last)`; 2,4) `N = [ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(r)`. ### Complexity Exactly `N` applications of the corresponding predicate `comp` and any projection `proj`. ### Possible implementation | First version | | --- | | ``` struct replace_copy_fn { template <std::input_iterator I, std::sentinel_for<I> S, class T1, class T2, std::output_iterator<const T2&> O, class Proj = std::identity> requires std::indirectly_copyable<I, O> && std::indirect_binary_predicate<ranges::equal_to, std::projected<I, Proj>, const T1*> constexpr ranges::replace_copy_result<I, O> operator()( I first, S last, O result, const T1& old_value, const T2& new_value, Proj proj = {} ) const { for (; first != last; ++first, ++result) { *result = (std::invoke(proj, *first) == old_value) ? new_value : *first; } return {std::move(first), std::move(result)}; } template <ranges::input_range R, class T1, class T2, std::output_iterator<const T2&> O, class Proj = std::identity> requires std::indirectly_copyable<ranges::iterator_t<R>, O> && std::indirect_binary_predicate<ranges::equal_to, std::projected<ranges::iterator_t<R>, Proj>, const T1*> constexpr ranges::replace_copy_result<ranges::borrowed_iterator_t<R>, O> operator()( R&& r, O result, const T1& old_value, const T2& new_value, Proj proj = {} ) const { return (*this)(ranges::begin(r), ranges::end(r), std::move(result), old_value, new_value, std::move(proj)); } }; inline constexpr replace_copy_fn replace_copy{}; ``` | | Second version | | ``` struct replace_copy_if_fn { template <std::input_iterator I, std::sentinel_for<I> S, class T, std::output_iterator<const T&> O, class Proj = std::identity, std::indirect_unary_predicate< std::projected<I, Proj>> Pred> requires std::indirectly_copyable<I, O> constexpr ranges::replace_copy_if_result<I, O> operator()( I first, S last, O result, Pred pred, const T& new_value, Proj proj = {} ) const { for (; first != last; ++first, ++result) { *result = std::invoke(pred, std::invoke(proj, *first)) ? new_value : *first; } return {std::move(first), std::move(result)}; } template <ranges::input_range R, class T, std::output_iterator<const T&> O, class Proj = std::identity, std::indirect_unary_predicate<std::projected<ranges::iterator_t<R>, Proj>> Pred> requires std::indirectly_copyable<ranges::iterator_t<R>, O> constexpr ranges::replace_copy_if_result<ranges::borrowed_iterator_t<R>, O> operator()( R&& r, O result, Pred pred, const T& new_value, Proj proj = {} ) const { return (*this)(ranges::begin(r), ranges::end(r), std::move(result), std::move(pred), new_value, std::move(proj)); } }; inline constexpr replace_copy_if_fn replace_copy_if{}; ``` | ### Example ``` #include <algorithm> #include <array> #include <iostream> #include <vector> int main() { auto print = [](const auto rem, const auto& v) { for (std::cout << rem << ": "; const auto& e : v) std::cout << e << ' '; std::cout << '\n'; }; std::vector<int> o; std::array p{1, 6, 1, 6, 1, 6}; o.resize(p.size()); print("p", p); std::ranges::replace_copy(p, o.begin(), 6, 9); print("o", o); std::array q{1, 2, 3, 6, 7, 8, 4, 5}; o.resize(q.size()); print("q", q); std::ranges::replace_copy_if(q, o.begin(), [](int x){ return 5 < x; }, 5); print("o", o); } ``` Output: ``` p: 1 6 1 6 1 6 o: 1 9 1 9 1 9 q: 1 2 3 6 7 8 4 5 o: 1 2 3 5 5 5 4 5 ``` ### See also | | | | --- | --- | | [ranges::replaceranges::replace\_if](replace "cpp/algorithm/ranges/replace") (C++20)(C++20) | replaces all values satisfying specific criteria with another value (niebloid) | | [replace\_copyreplace\_copy\_if](../replace_copy "cpp/algorithm/replace copy") | copies a range, replacing elements satisfying specific criteria with another value (function template) | cpp std::ranges::is_heap_until std::ranges::is\_heap\_until ============================ | Defined in header `[<algorithm>](../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | Call signature | | | | ``` template< std::random_access_iterator I, std::sentinel_for<I> S, class Proj = std::identity, std::indirect_strict_weak_order< std::projected<I, Proj>> Comp = ranges::less > constexpr I is_heap_until( I first, S last, Comp comp = {}, Proj proj = {} ); ``` | (1) | (since C++20) | | ``` template< ranges::random_access_range R, class Proj = std::identity, std::indirect_strict_weak_order<std::projected<ranges::iterator_t<R>, Proj>> Comp = ranges::less > constexpr ranges::borrowed_iterator_t<R> is_heap_until( R&& r, Comp comp = {}, Proj proj = {} ); ``` | (2) | (since C++20) | Examines the range `[first, last)` and finds the largest range beginning at `first` which is a [*max heap*](https://en.wikipedia.org/wiki/Binary_heap "enwiki:Binary heap"). 1) Elements are compared using the given binary comparison function `comp` and projection object `proj`. 2) Same as (1), but uses `r` as the range, as if using `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r)` as `first` and `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r)` as `last`. The function-like entities described on this page are *niebloids*, that is: * Explicit template argument lists cannot be specified when calling any of them. * None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl"). * When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited. In practice, they may be implemented as function objects, or with special compiler extensions. ### Parameters | | | | | --- | --- | --- | | first, last | - | the range of elements to examine | | r | - | the range of elements to examine | | pred | - | predicate to apply to the projected elements | | proj | - | projection to apply to the elements | ### Return value The upper bound of the largest range beginning at `first` which is a *max heap*. That is, the last iterator `it` for which range `[first, it)` is a *max heap* with respect to `comp` and `proj`. ### Complexity Linear in the distance between `first` and `last`. ### Notes A *max heap* is a range of elements `[f, l)`, arranged with respect to comparator `comp` and projection `proj`, that has the following properties: * With `N = l-f`, `p = f[(i-1)/2]`, and `q = f[i]`, for all `0 < i < N`, the expression `[std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(comp, [std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(proj, p), [std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(proj, q))` evaluates to `false`. * A new element can be added using `[ranges::push\_heap](push_heap "cpp/algorithm/ranges/push heap")`, in \(\scriptsize \mathcal{O}(\log N)\)𝓞(log N) time. * The first element can be removed using `[ranges::pop\_heap](pop_heap "cpp/algorithm/ranges/pop heap")`, in \(\scriptsize \mathcal{O}(\log N)\)𝓞(log N) time. ### Possible implementation | | | --- | | ``` struct is_heap_until_fn { template< std::random_access_iterator I, std::sentinel_for<I> S, class Proj = std::identity, std::indirect_strict_weak_order< std::projected<I, Proj>> Comp = ranges::less > constexpr I operator()( I first, S last, Comp comp = {}, Proj proj = {} ) const { std::iter_difference_t<I> n {ranges::distance(first, last)}, dad {0}, son {1}; for (; son != n; ++son) { if (std::invoke(comp, std::invoke(proj, *(first + dad)), std::invoke(proj, *(first + son)))) { return first + son; } else if ((son % 2) == 0) { ++dad; } } return first + n; } template< ranges::random_access_range R, class Proj = std::identity, std::indirect_strict_weak_order<std::projected<ranges::iterator_t<R>, Proj>> Comp = ranges::less > constexpr ranges::borrowed_iterator_t<R> operator()( R&& r, Comp comp = {}, Proj proj = {} ) const { return (*this)(ranges::begin(r), ranges::end(r), std::move(comp), std::move(proj)); } }; inline constexpr is_heap_until_fn is_heap_until{}; ``` | ### Example The example renders a given vector as a (balanced) [binary tree](https://en.wikipedia.org/wiki/Binary_tree "enwiki:Binary tree"). ``` #include <algorithm> #include <cmath> #include <iostream> #include <iterator> #include <vector> void out(const auto& what, int n = 1) { while (n-- > 0) std::cout << what; } void draw_bin_tree(auto first, auto last); int main() { std::vector<int> v { 3, 1, 4, 1, 5, 9, }; std::ranges::make_heap(v); // probably mess up the heap v.push_back(2); v.push_back(6); out("v after make_heap and push_back: \n"); draw_bin_tree(v.begin(), v.end()); out("the max-heap prefix of v: \n"); const auto heap_end = std::ranges::is_heap_until(v); draw_bin_tree(v.begin(), heap_end); } void draw_bin_tree(auto first, auto last) { auto bails = [](int n, int w) { auto b = [](int w) { out("┌"), out("─", w), out("┴"), out("─", w), out("┐"); }; n /= 2; if (!n) return; for (out(' ', w); n-- > 0; ) b(w), out(' ', w + w + 1); out('\n'); }; auto data = [](int n, int w, auto& first, auto last) { for(out(' ', w); n-- > 0 && first != last; ++first) out(*first), out(' ', w + w + 1); out('\n'); }; auto tier = [&](int t, int m, auto& first, auto last) { const int n {1 << t}; const int w {(1 << (m - t - 1)) - 1}; bails(n, w), data(n, w, first, last); }; const auto size {std::ranges::distance(first, last)}; const int m {static_cast<int>(std::ceil(std::log2(1 + size)))}; for (int i{}; i != m; ++i) { tier(i, m, first, last); } } ``` Output: ``` v after make_heap and push_back: 9 ┌───┴───┐ 5 4 ┌─┴─┐ ┌─┴─┐ 1 1 3 2 ┌┴┐ ┌┴┐ ┌┴┐ ┌┴┐ 6 the max-heap prefix of v: 9 ┌─┴─┐ 5 4 ┌┴┐ ┌┴┐ 1 1 3 2 ``` ### See also | | | | --- | --- | | [ranges::is\_heap](is_heap "cpp/algorithm/ranges/is heap") (C++20) | checks if the given range is a max heap (niebloid) | | [ranges::make\_heap](make_heap "cpp/algorithm/ranges/make heap") (C++20) | creates a max heap out of a range of elements (niebloid) | | [ranges::push\_heap](push_heap "cpp/algorithm/ranges/push heap") (C++20) | adds an element to a max heap (niebloid) | | [ranges::pop\_heap](pop_heap "cpp/algorithm/ranges/pop heap") (C++20) | removes the largest element from a max heap (niebloid) | | [ranges::sort\_heap](sort_heap "cpp/algorithm/ranges/sort heap") (C++20) | turns a max heap into a range of elements sorted in ascending order (niebloid) | | [is\_heap\_until](../is_heap_until "cpp/algorithm/is heap until") (C++11) | finds the largest subrange that is a max heap (function template) |
programming_docs
cpp std::ranges::iota, std::ranges::iota_result std::ranges::iota, std::ranges::iota\_result ============================================ | Defined in header `[<numeric>](../../header/numeric "cpp/header/numeric")` | | | | --- | --- | --- | | Call signature | | | | ``` template< std::input_or_output_iterator O, std::sentinel_for<O> S, std::weakly_incrementable T > requires std::indirectly_writable<O, const T&> constexpr iota_result<O, T> iota( O first, S last, T value ); ``` | (1) | (since C++23) | | ``` template< std::weakly_incrementable T, ranges::output_range<const T&> R > constexpr iota_result<ranges::borrowed_iterator_t<R>, T> iota( R&& r, T value ); ``` | (2) | (since C++23) | | Helper types | | | | ``` template< class O, class T > using iota_result = ranges::out_value_result<O, T>; ``` | (3) | (since C++23) | Fills the range `[first, last)` with sequentially increasing values, starting with `value` and repetitively evaluating `++value`. Equivalent operation: ``` *(first) = value; *(first+1) = ++value; *(first+2) = ++value; *(first+3) = ++value; ... ``` ### Parameters | | | | | --- | --- | --- | | first, last | - | the range of elements to fill with sequentially increasing values starting with `value` | | value | - | initial value to store; the expression `++value` must be well-formed | ### Return value `{last, value + [ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(first, last)}` ### Complexity Exactly `last - first` increments and assignments. ### Possible implementation | | | --- | | ``` struct iota_fn { template< std::input_or_output_iterator O, std::sentinel_for<O> S, std::weakly_incrementable T > requires std::indirectly_writable<O, const T&> constexpr iota_result<O, T> operator()(O first, S last, T value) const { while (first != last) { *first = as_const(value); ++first; ++value; } return {std::move(first), std::move(value)}; } template< std::weakly_incrementable T, std::ranges::output_range<const T&> R > constexpr iota_result<std::ranges::borrowed_iterator_t<R>, T> operator()(R&& r, T value) const { return (*this)(std::ranges::begin(r), std::ranges::end(r), std::move(value)); } }; inline constexpr iota_fn iota; ``` | ### Notes The function is named after the integer function ⍳ from the programming language [APL](https://en.wikipedia.org/wiki/APL_(programming_language) "enwiki:APL (programming language)"). | [Feature-test](../../utility/feature_test "cpp/utility/feature test") macro | Value | Std | | --- | --- | --- | | [`__cpp_lib_ranges_iota`](../../feature_test#Library_features "cpp/feature test") | `202202L` | (C++23) | ### Example The following example applies `[ranges::shuffle](shuffle "cpp/algorithm/ranges/shuffle")` to a `[vector](../../container/vector "cpp/container/vector")` of `[std::list](../../container/list "cpp/container/list")`s' iterators since `[ranges::shuffle](shuffle "cpp/algorithm/ranges/shuffle")` cannot be applied to a `[std::list](../../container/list "cpp/container/list")` directly. `ranges::iota` is used to populate both containers. ``` #include <algorithm> #include <iostream> #include <list> #include <numeric> #include <random> #include <vector> int main() { std::list<int> l(10); std::ranges::iota(l.begin(), l.end(), -4); std::vector<std::list<int>::iterator> v(l.size()); std::ranges::iota(v, l.begin()); std::ranges::shuffle(v, std::mt19937{std::random_device{}()}); std::cout << "Contents of the list: "; for(auto n: l) std::cout << n << ' '; std::cout << '\n'; std::cout << "Contents of the list, shuffled: "; for(auto i: v) std::cout << *i << ' '; std::cout << '\n'; } ``` Possible output: ``` Contents of the list: -4 -3 -2 -1 0 1 2 3 4 5 Contents of the list, shuffled: 0 -1 3 4 -4 1 -2 -3 2 5 ``` ### See also | | | | --- | --- | | [fill](../fill "cpp/algorithm/fill") | copy-assigns the given value to every element in a range (function template) | | [ranges::fill](fill "cpp/algorithm/ranges/fill") (C++20) | assigns a range of elements a certain value (niebloid) | | [generate](../generate "cpp/algorithm/generate") | assigns the results of successive function calls to every element in a range (function template) | | [ranges::generate](generate "cpp/algorithm/ranges/generate") (C++20) | saves the result of a function in a range (niebloid) | | [ranges::iota\_viewviews::iota](../../ranges/iota_view "cpp/ranges/iota view") (C++20) | a [`view`](../../ranges/view "cpp/ranges/view") consisting of a sequence generated by repeatedly incrementing an initial value (class template) (customization point object) | | [iota](../iota "cpp/algorithm/iota") (C++11) | fills a range with successive increments of the starting value (function template) | cpp std::ranges::starts_with std::ranges::starts\_with ========================= | Defined in header `[<algorithm>](../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | Call signature | | | | ``` template< std::input_iterator I1, std::sentinel_for<I1> S1, std::input_iterator I2, std::sentinel_for<I2> S2, class Pred = ranges::equal_to, class Proj1 = std::identity, class Proj2 = std::identity > requires std::indirectly_comparable<I1, I2, Pred, Proj1, Proj2> constexpr bool starts_with( I1 first1, S1 last1, I2 first2, S2 last2, Pred pred = {}, Proj1 proj1 = {}, Proj2 proj2 = {} ); ``` | (1) | (since C++23) | | ``` template< ranges::input_range R1, ranges::input_range R2, class Pred = ranges::equal_to, class Proj1 = std::identity, class Proj2 = std::identity > requires std::indirectly_comparable<ranges::iterator_t<R1>, ranges::iterator_t<R2>, Pred, Proj1, Proj2> constexpr bool starts_with( R1&& r1, R2&& r2, Pred pred = {}, Proj1 proj1 = {}, Proj2 proj2 = {} ); ``` | (2) | (since C++23) | Checks whether the second range matches the prefix of the first range. 1) Let `N1` and `N2` denote the size of ranges `[first1, last1)` and `[first2, last2)` respectively. If `N1 < N2`, returns `false`. Otherwise, returns `true` only if every element in the range `[first2, last2)` is equal to the corresponding element in `[first1, first1 + N2)`. Comparison is done by applying the binary predicate `pred` to elements in two ranges projected by `proj1` and `proj2` respectively. 2) Same as (1), but uses `r1` and `r2` as the source ranges, as if using `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r1)` as `first1`, `ranges:begin(r2)` as `first2`, `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r1)` as `last1`, and `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r2)` as `last2`. The function-like entities described on this page are *niebloids*, that is: * Explicit template argument lists cannot be specified when calling any of them. * None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl"). * When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited. In practice, they may be implemented as function objects, or with special compiler extensions. ### Parameters | | | | | --- | --- | --- | | first1, last1 | - | the range of elements to examine | | r1 | - | the range of elements to examine | | first2, last2 | - | the range of elements to be used as the prefix | | r2 | - | the range of elements to be used as the prefix | | pred | - | the binary predicate that compares the projected elements | | proj1 | - | the projection to apply to the elements of the range to examine | | proj2 | - | the projection to apply to the elements of the range to be used as the prefix | ### Return value `true` if the second range matches the prefix of the first range, `false` otherwise. ### Complexity Linear: at most `min(N1, N2)` applications of the predicate and both projections. ### Possible implementation | | | --- | | ``` struct starts_with_fn { template<std::input_iterator I1, std::sentinel_for<I1> S1, std::input_iterator I2, std::sentinel_for<I2> S2, class Pred = ranges::equal_to, class Proj1 = std::identity, class Proj2 = std::identity> requires std::indirectly_comparable<I1, I2, Pred, Proj1, Proj2> constexpr bool operator()(I1 first1, S1 last1, I2 first2, S2 last2, Pred pred = {}, Proj1 proj1 = {}, Proj2 proj2 = {}) const { return ranges::mismatch(std::move(first1), last1, std::move(first2), last2, std::move(pred), std::move(proj1), std::move(proj2) ).in2 == last2; } template<ranges::input_range R1, ranges::input_range R2, class Pred = ranges::equal_to, class Proj1 = std::identity, class Proj2 = std::identity> requires std::indirectly_comparable<ranges::iterator_t<R1>, ranges::iterator_t<R2>, Pred, Proj1, Proj2> constexpr bool operator()(R1&& r1, R2&& r2, Pred pred = {}, Proj1 proj1 = {}, Proj2 proj2 = {}) const { return (*this)(ranges::begin(r1), ranges::end(r1), ranges::begin(r2), ranges::end(r2), std::move(pred), std::move(proj1), std::move(proj2)); } }; inline constexpr starts_with_fn starts_with{}; ``` | ### Notes | [Feature-test](../../utility/feature_test "cpp/utility/feature test") macro | Value | Std | | --- | --- | --- | | [`__cpp_lib_ranges_starts_ends_with`](../../feature_test#Library_features "cpp/feature test") | `202106L` | (C++23) | ### Example ``` #include <string_view> #include <algorithm> #include <iostream> #include <ranges> int main() { using namespace std::literals; constexpr auto ascii_upper = [](char8_t c) { return u8'a' <= c && c <= u8'z' ? static_cast<char8_t>(c + u8'A' - u8'a') : c; }; constexpr auto cmp_ignore_case = [=](char8_t x, char8_t y) { return ascii_upper(x) == ascii_upper(y); }; static_assert(std::ranges::starts_with("const_cast", "const"sv)); static_assert(std::ranges::starts_with("constexpr", "const"sv)); static_assert(!std::ranges::starts_with("volatile", "const"sv)); std::cout << std::boolalpha << std::ranges::starts_with(u8"Constantinopolis", u8"constant"sv, {}, ascii_upper, ascii_upper) << ' ' << std::ranges::starts_with(u8"Istanbul", u8"constant"sv, {}, ascii_upper, ascii_upper) << ' ' << std::ranges::starts_with(u8"Metropolis", u8"metro"sv, cmp_ignore_case) << ' ' << std::ranges::starts_with(u8"Acropolis", u8"metro"sv, cmp_ignore_case) << '\n'; constexpr static auto v = { 1, 3, 5, 7, 9 }; constexpr auto odd = [](int x) { return x % 2; }; static_assert( std::ranges::starts_with( v, std::views::iota(1) | std::views::filter(odd) | std::views::take(3) ) ); } ``` Output: ``` true false true false ``` ### See also | | | | --- | --- | | [ranges::ends\_with](ends_with "cpp/algorithm/ranges/ends with") (C++23) | checks whether a range ends with another range (niebloid) | | [ranges::mismatch](mismatch "cpp/algorithm/ranges/mismatch") (C++20) | finds the first position where two ranges differ (niebloid) | | [starts\_with](../../string/basic_string/starts_with "cpp/string/basic string/starts with") (C++20) | checks if the string starts with the given prefix (public member function of `std::basic_string<CharT,Traits,Allocator>`) | | [starts\_with](../../string/basic_string_view/starts_with "cpp/string/basic string view/starts with") (C++20) | checks if the string view starts with the given prefix (public member function of `std::basic_string_view<CharT,Traits>`) | cpp std::ranges::is_sorted std::ranges::is\_sorted ======================= | Defined in header `[<algorithm>](../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | Call signature | | | | ``` template< std::forward_iterator I, std::sentinel_for<I> S, class Proj = std::identity, std::indirect_strict_weak_order<std::projected<I, Proj>> Comp = ranges::less > constexpr bool is_sorted( I first, S last, Comp comp = {}, Proj proj = {} ); ``` | (1) | (since C++20) | | ``` template< ranges::forward_range R, class Proj = std::identity, std::indirect_strict_weak_order< std::projected<ranges::iterator_t<R>, Proj>> Comp = ranges::less > constexpr bool is_sorted( R&& r, Comp comp = {}, Proj proj = {} ); ``` | (2) | (since C++20) | Checks if the elements in range `[first, last)` are sorted in non-descending order. A sequence is sorted with respect to a comparator `comp` if for any iterator `it` pointing to the sequence and any non-negative integer `n` such that `it + n` is a valid iterator pointing to an element of the sequence, `[std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(comp, [std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(proj, \*(it + n)), [std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(proj, \*it))` evaluates to `false`. 1) Elements are compared using the given binary comparison function `comp`. 2) Same as (1), but uses `r` as the source range, as if using `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r)` as `first` and `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r)` as `last`. The function-like entities described on this page are *niebloids*, that is: * Explicit template argument lists cannot be specified when calling any of them. * None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl"). * When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited. In practice, they may be implemented as function objects, or with special compiler extensions. ### Parameters | | | | | --- | --- | --- | | first, last | - | iterator-sentinel defining the range to check if it is sorted | | r | - | the range to check if it is sorted | | comp | - | comparison function to apply to the projected elements | | proj | - | projection to apply to the elements | ### Return value `true` if the elements in the range are sorted according to `comp`. ### Complexity Linear in the distance between `first` and `last`. ### Possible implementation | | | --- | | ``` struct is_sorted_fn { template<std::forward_iterator I, std::sentinel_for<I> S, class Proj = std::identity, std::indirect_strict_weak_order<std::projected<I, Proj>> Comp = ranges::less> constexpr bool operator()(I first, S last, Comp comp = {}, Proj proj = {}) const { return ranges::is_sorted_until(first, last, comp, proj) == last; } template<ranges::forward_range R, class Proj = std::identity, std::indirect_strict_weak_order< std::projected<ranges::iterator_t<R>, Proj>> Comp = ranges::less> constexpr bool operator()(R&& r, Comp comp = {}, Proj proj = {}) const { return (*this)(ranges::begin(r), ranges::end(r), std::ref(comp), std::ref(proj)); } }; inline constexpr is_sorted_fn is_sorted; ``` | ### Notes `ranges::is_sorted` returns `true` for empty ranges and ranges of length one. ### Example ``` #include <algorithm> #include <iostream> #include <iterator> int main() { namespace ranges = std::ranges; std::array digits {3, 1, 4, 1, 5}; ranges::copy(digits, std::ostream_iterator<int>(std::cout, " ")); std::cout << ": is_sorted: " << std::boolalpha << ranges::is_sorted(digits) << '\n'; ranges::sort(digits); ranges::copy(digits, std::ostream_iterator<int>(std::cout, " ")); std::cout << ": is_sorted: " << ranges::is_sorted(ranges::begin(digits), ranges::end(digits)) << '\n'; } ``` Output: ``` 3 1 4 1 5 : is_sorted: false 1 1 3 4 5 : is_sorted: true ``` ### See also | | | | --- | --- | | [ranges::is\_sorted\_until](is_sorted_until "cpp/algorithm/ranges/is sorted until") (C++20) | finds the largest sorted subrange (niebloid) | | [is\_sorted](../is_sorted "cpp/algorithm/is sorted") (C++11) | checks whether a range is sorted into ascending order (function template) | cpp std::ranges::max std::ranges::max ================ | Defined in header `[<algorithm>](../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | Call signature | | | | ``` template< class T, class Proj = std::identity, std::indirect_strict_weak_order< std::projected<const T*, Proj>> Comp = ranges::less > constexpr const T& max( const T& a, const T& b, Comp comp = {}, Proj proj = {} ); ``` | | (since C++20) | | ``` template< std::copyable T, class Proj = std::identity, std::indirect_strict_weak_order< std::projected<const T*, Proj>> Comp = ranges::less > constexpr const T max( std::initializer_list<T> r, Comp comp = {}, Proj proj = {} ); ``` | | (since C++20) | | ``` template< ranges::input_range R, class Proj = std::identity, std::indirect_strict_weak_order< std::projected<ranges::iterator_t<R>, Proj>> Comp = ranges::less > requires std::indirectly_copyable_storable<ranges::iterator_t<R>, ranges::range_value_t<R>*> constexpr ranges::range_value_t<R> max( R&& r, Comp comp = {}, Proj proj = {} ); ``` | | (since C++20) | Returns the greater of the given projected values. 1) Returns the greater of `a` and `b`. 2) Returns the first greatest value in the initializer list `r`. 3) Returns the first greatest value in the range `r`. The function-like entities described on this page are *niebloids*, that is: * Explicit template argument lists cannot be specified when calling any of them. * None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl"). * When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited. In practice, they may be implemented as function objects, or with special compiler extensions. ### Parameters | | | | | --- | --- | --- | | a, b | - | the values to compare | | r | - | the range of values to compare | | comp | - | comparison to apply to the projected elements | | proj | - | projection to apply to the elements | ### Return value 1) The greater of `a` and `b`, according to their respective projected values. If they are equivalent, returns `a`. 2-3) The greatest value in `r`, according to the projection. If several values are equivalent to the greatest, returns the leftmost one. If the range is empty (as determined by `[ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(r)`), the behavior is undefined. ### Complexity 1) Exactly one comparison. 2-3) Exactly `[ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(r) - 1` comparisons. ### Possible implementation | | | --- | | ``` struct max_fn { template<class T, class Proj = std::identity, std::indirect_strict_weak_order< std::projected<const T*, Proj>> Comp = ranges::less> constexpr const T& operator()(const T& a, const T& b, Comp comp = {}, Proj proj = {}) const { return std::invoke(comp, std::invoke(proj, a), std::invoke(proj, b)) ? b : a; } template<std::copyable T, class Proj = std::identity, std::indirect_strict_weak_order< std::projected<const T*, Proj>> Comp = ranges::less> constexpr const T operator()(std::initializer_list<T> r, Comp comp = {}, Proj proj = {}) const { return *ranges::max_element(r, std::ref(comp), std::ref(proj)); } template<ranges::input_range R, class Proj = std::identity, std::indirect_strict_weak_order< std::projected<ranges::iterator_t<R>, Proj>> Comp = ranges::less> requires std::indirectly_copyable_storable<ranges::iterator_t<R>, ranges::range_value_t<R>*> constexpr ranges::range_value_t<R> operator()(R&& r, Comp comp = {}, Proj proj = {}) const { using V = ranges::range_value_t<R>; if constexpr (ranges::forward_range<R>) { return static_cast<V>(*ranges::max_element(r, std::ref(comp), std::ref(proj))); } else { auto i = ranges::begin(r); auto s = ranges::end(r); V m(*i); while (++i != s) { if (std::invoke(comp, std::invoke(proj, m), std::invoke(proj, *i))) { m = *i; } } return m; } } }; inline constexpr max_fn max; ``` | ### Notes Capturing the result of `std::ranges::max` by reference produces a dangling reference if one of the parameters is a temporary and that parameter is returned: ``` int n = 1; const int& r = std::ranges::max(n-1, n+1); // r is dangling ``` ### Example ``` #include <algorithm> #include <iostream> #include <string> int main() { namespace ranges = std::ranges; using namespace std::string_view_literals; std::cout << "larger of 1 and 9999: " << ranges::max(1, 9999) << '\n' << "larger of 'a', and 'b': '" << ranges::max('a', 'b') << "'\n" << "longest of \"foo\", \"bar\", and \"hello\": \"" << ranges::max({ "foo"sv, "bar"sv, "hello"sv }, {}, &std::string_view::size) << "\"\n"; } ``` Output: ``` larger of 1 and 9999: 9999 larger of 'a', and 'b': 'b' longest of "foo", "bar", and "hello": "hello" ``` ### See also | | | | --- | --- | | [ranges::min](min "cpp/algorithm/ranges/min") (C++20) | returns the smaller of the given values (niebloid) | | [ranges::minmax](minmax "cpp/algorithm/ranges/minmax") (C++20) | returns the smaller and larger of two elements (niebloid) | | [ranges::max\_element](max_element "cpp/algorithm/ranges/max element") (C++20) | returns the largest element in a range (niebloid) | | [ranges::clamp](clamp "cpp/algorithm/ranges/clamp") (C++20) | clamps a value between a pair of boundary values (niebloid) | | [max](../max "cpp/algorithm/max") | returns the greater of the given values (function template) |
programming_docs
cpp std::ranges::is_heap std::ranges::is\_heap ===================== | Defined in header `[<algorithm>](../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | Call signature | | | | ``` template< std::random_access_iterator I, std::sentinel_for<I> S, class Proj = std::identity, std::indirect_strict_weak_order< std::projected<I, Proj>> Comp = ranges::less > constexpr bool is_heap( I first, S last, Comp comp = {}, Proj proj = {} ); ``` | (1) | (since C++20) | | ``` template< ranges::random_access_range R, class Proj = std::identity, std::indirect_strict_weak_order<std::projected<ranges::iterator_t<R>, Proj>> Comp = ranges::less > constexpr bool is_heap( R&& r, Comp comp = {}, Proj proj = {} ); ``` | (2) | (since C++20) | Checks if the elements in range `[first, last)` are a [*max heap*](https://en.wikipedia.org/wiki/Binary_heap "enwiki:Binary heap"). 1) Elements are compared using the given binary comparison function `comp` and projection object `proj`. 2) Same as (1), but uses `r` as the range, as if using `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r)` as `first` and `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r)` as `last`. The function-like entities described on this page are *niebloids*, that is: * Explicit template argument lists cannot be specified when calling any of them. * None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl"). * When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited. In practice, they may be implemented as function objects, or with special compiler extensions. ### Parameters | | | | | --- | --- | --- | | first, last | - | the range of elements to examine | | r | - | the range of elements to examine | | pred | - | predicate to apply to the projected elements | | proj | - | projection to apply to the elements | ### Return value `true` if the range is *max heap*, `false` otherwise. ### Complexity Linear in the distance between `first` and `last`. ### Notes A *max heap* is a range of elements `[f, l)`, arranged with respect to comparator `comp` and projection `proj`, that has the following properties: * With `N = l-f`, `p = f[(i-1)/2]`, and `q = f[i]`, for all `0 < i < N`, the expression `[std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(comp, [std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(proj, p), [std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(proj, q))` evaluates to `false`. * A new element can be added using `[ranges::push\_heap](push_heap "cpp/algorithm/ranges/push heap")`, in \(\scriptsize \mathcal{O}(\log N)\)𝓞(log N) time. * The first element can be removed using `[ranges::pop\_heap](pop_heap "cpp/algorithm/ranges/pop heap")`, in \(\scriptsize \mathcal{O}(\log N)\)𝓞(log N) time. ### Possible implementation | | | --- | | ``` struct is_heap_fn { template< std::random_access_iterator I, std::sentinel_for<I> S, class Proj = std::identity, std::indirect_strict_weak_order< std::projected<I, Proj>> Comp = ranges::less > constexpr bool operator()( I first, S last, Comp comp = {}, Proj proj = {} ) const { return (last == ranges::is_heap_until(first, last, std::move(comp), std::move(proj))); } template< ranges::random_access_range R, class Proj = std::identity, std::indirect_strict_weak_order<std::projected<ranges::iterator_t<R>, Proj>> Comp = ranges::less > constexpr bool operator()( R&& r, Comp comp = {}, Proj proj = {} ) const { return (*this)(ranges::begin(r), ranges::end(r), std::move(comp), std::move(proj)); } }; inline constexpr is_heap_fn is_heap{}; ``` | ### Example ``` #include <algorithm> #include <bit> #include <cmath> #include <iostream> #include <vector> void out(const auto& what, int n = 1) { while (n-- > 0) std::cout << what; } void draw_heap(auto const& v); int main() { std::vector<int> v { 3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9, 3, 2, 3, 8 }; out("initially, v:\n"); for (auto i : v) std::cout << i << ' '; out('\n'); if (!std::ranges::is_heap(v)) { out("making heap...\n"); std::ranges::make_heap(v); } out("after make_heap, v:\n"); for (auto t{1U}; auto i : v) { std::cout << i << (std::has_single_bit(++t) ? " │ " : " "); } out("\n" "corresponding binary tree is:\n"); draw_heap(v); } void draw_heap(auto const& v) { auto bails = [](int n, int w) { auto b = [](int w) { out("┌"), out("─", w), out("┴"), out("─", w), out("┐"); }; n /= 2; if (!n) return; for (out(' ', w); n-- > 0; ) b(w), out(' ', w + w + 1); out('\n'); }; auto data = [](int n, int w, auto& first, auto last) { for(out(' ', w); n-- > 0 && first != last; ++first) out(*first), out(' ', w + w + 1); out('\n'); }; auto tier = [&](int t, int m, auto& first, auto last) { const int n {1 << t}; const int w {(1 << (m - t - 1)) - 1}; bails(n, w), data(n, w, first, last); }; const int m {static_cast<int>(std::ceil(std::log2(1 + v.size())))}; auto first {v.cbegin()}; for (int i{}; i != m; ++i) { tier(i, m, first, v.cend()); } } ``` Output: ``` initially, v: 3 1 4 1 5 9 2 6 5 3 5 8 9 7 9 3 2 3 8 making heap... after make_heap, v: 9 │ 8 9 │ 6 5 8 9 │ 3 5 3 5 3 4 7 2 │ 1 2 3 1 corresponding binary tree is: 9 ┌───────┴───────┐ 8 9 ┌───┴───┐ ┌───┴───┐ 6 5 8 9 ┌─┴─┐ ┌─┴─┐ ┌─┴─┐ ┌─┴─┐ 3 5 3 5 3 4 7 2 ┌┴┐ ┌┴┐ ┌┴┐ ┌┴┐ ┌┴┐ ┌┴┐ ┌┴┐ ┌┴┐ 1 2 3 1 ``` ### See also | | | | --- | --- | | [ranges::is\_heap\_until](is_heap_until "cpp/algorithm/ranges/is heap until") (C++20) | finds the largest subrange that is a max heap (niebloid) | | [ranges::make\_heap](make_heap "cpp/algorithm/ranges/make heap") (C++20) | creates a max heap out of a range of elements (niebloid) | | [ranges::push\_heap](push_heap "cpp/algorithm/ranges/push heap") (C++20) | adds an element to a max heap (niebloid) | | [ranges::pop\_heap](pop_heap "cpp/algorithm/ranges/pop heap") (C++20) | removes the largest element from a max heap (niebloid) | | [ranges::sort\_heap](sort_heap "cpp/algorithm/ranges/sort heap") (C++20) | turns a max heap into a range of elements sorted in ascending order (niebloid) | | [is\_heap](../is_heap "cpp/algorithm/is heap") (C++11) | checks if the given range is a max heap (function template) | cpp std::ranges::minmax_element, std::ranges::minmax_element_result std::ranges::minmax\_element, std::ranges::minmax\_element\_result ================================================================== | Defined in header `[<algorithm>](../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | Call signature | | | | ``` template< std::forward_iterator I, std::sentinel_for<I> S, class Proj = std::identity, std::indirect_strict_weak_order<std::projected<I, Proj>> Comp = ranges::less > constexpr minmax_element_result<I> minmax_element( I first, S last, Comp comp = {}, Proj proj = {} ); ``` | (1) | (since C++20) | | ``` template< ranges::forward_range R, class Proj = std::identity, std::indirect_strict_weak_order< std::projected<ranges::iterator_t<R>, Proj>> Comp = ranges::less > constexpr minmax_element_result<ranges::borrowed_iterator_t<R>> minmax_element( R&& r, Comp comp = {}, Proj proj = {} ); ``` | (2) | (since C++20) | | Helper types | | | | ``` template< class I > using minmax_element_result = ranges::min_max_result<I>; ``` | (3) | (since C++20) | 1) Finds the smallest and largest elements in the range `[first, last)`. 2) Same as (1), but uses `r` as the source range, as if using `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r)` as `first` and `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r)` as `last`. The function-like entities described on this page are *niebloids*, that is: * Explicit template argument lists cannot be specified when calling any of them. * None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl"). * When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited. In practice, they may be implemented as function objects, or with special compiler extensions. ### Parameters | | | | | --- | --- | --- | | first, last | - | iterator-sentinel pair denoting the range to examine | | r | - | the range to examine | | comp | - | comparison to apply to the projected elements | | proj | - | projection to apply to the elements. | ### Return value An object consisting of an iterator to the smallest element as the first element and an iterator to the greatest element as the second. Returns `{first, first}` if the range is empty. If several elements are equivalent to the smallest element, the iterator to the first such element is returned. If several elements are equivalent to the largest element, the iterator to the last such element is returned. ### Complexity At most `max(floor((3/2)*(N−1)), 0)` applications of the comparison and twice as many applications of the projection, where `N = [ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(first, last)`. ### Possible implementation | | | --- | | ``` struct minmax_element_fn { template<std::forward_iterator I, std::sentinel_for<I> S, class Proj = std::identity, std::indirect_strict_weak_order<std::projected<I, Proj>> Comp = ranges::less> constexpr ranges::minmax_element_result<I> operator()(I first, S last, Comp comp = {}, Proj proj = {}) const { auto min = first, max = first; if (first == last || ++first == last) { return {min, max}; } if (std::invoke(comp, std::invoke(proj, *first), std::invoke(proj, *min))) { min = first; } else { max = first; } while (++first != last) { auto i = first; if (++first == last) { if (std::invoke(comp, std::invoke(proj, *i), std::invoke(proj, *min))) { min = i; } else if (!(std::invoke(comp, std::invoke(proj, *i), std::invoke(proj, *max)))) { max = i; } break; } else { if (std::invoke(comp, std::invoke(proj, *first), std::invoke(proj, *i))) { if (std::invoke(comp, std::invoke(proj, *first), std::invoke(proj, *min))) { min = first; } if (!(std::invoke(comp, std::invoke(proj, *i), std::invoke(proj, *max)))) { max = i; } } else { if (std::invoke(comp, std::invoke(proj, *i), std::invoke(proj, *min))) { min = i; } if (!(std::invoke(comp, std::invoke(proj, *first), std::invoke(proj, *max)))) { max = first; } } } } return {min, max}; } template<ranges::forward_range R, class Proj = std::identity, std::indirect_strict_weak_order< std::projected<ranges::iterator_t<R>, Proj>> Comp = ranges::less> constexpr ranges::minmax_element_result<ranges::borrowed_iterator_t<R>> operator()(R&& r, Comp comp = {}, Proj proj = {}) const { return (*this)(ranges::begin(r), ranges::end(r), std::ref(comp), std::ref(proj)); } }; inline constexpr minmax_element_fn minmax_element; ``` | ### Example ``` #include <algorithm> #include <iostream> #include <iterator> namespace rng = std::ranges; int main() { const auto v = { 3, 9, 1, 4, 1, 2, 5, 9 }; const auto [min, max] = rng::minmax_element(v); std::cout << "min = " << *min << ", at [" << rng::distance(v.begin(), min) << "]\n" << "max = " << *max << ", at [" << rng::distance(v.begin(), max) << "]\n"; } ``` Output: ``` min = 1, at [2] max = 9, at [7] ``` ### See also | | | | --- | --- | | [ranges::min\_element](min_element "cpp/algorithm/ranges/min element") (C++20) | returns the smallest element in a range (niebloid) | | [ranges::max\_element](max_element "cpp/algorithm/ranges/max element") (C++20) | returns the largest element in a range (niebloid) | | [ranges::minmax](minmax "cpp/algorithm/ranges/minmax") (C++20) | returns the smaller and larger of two elements (niebloid) | | [minmax\_element](../minmax_element "cpp/algorithm/minmax element") (C++11) | returns the smallest and the largest elements in a range (function template) | cpp std::ranges::shift_left, std::ranges::shift_right std::ranges::shift\_left, std::ranges::shift\_right =================================================== | Defined in header `[<algorithm>](../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | Call signature | | | | ``` template< std::permutable I, std::sentinel_for<I> S > constexpr ranges::subrange<I> shift_left( I first, S last, std::iter_difference_t<I> n ); ``` | (1) | (since C++23) | | ``` template< ranges::forward_range R > requires std::permutable<ranges::iterator_t<R>> constexpr ranges::borrowed_subrange_t<R> shift_left( R&& r, ranges::range_difference_t<R> n ); ``` | (2) | (since C++23) | | ``` template< std::permutable I, std::sentinel_for<I> S > constexpr ranges::subrange<I> shift_right( I first, S last, std::iter_difference_t<I> n ); ``` | (3) | (since C++23) | | ``` template< ranges::forward_range R > requires std::permutable<ranges::iterator_t<R>> constexpr ranges::borrowed_subrange_t<R> shift_right( R&& r, ranges::range_difference_t<R> n ); ``` | (4) | (since C++23) | Shifts the elements in the range `[first, last)` or `r` by `n` positions. The behavior is undefined if `[first, last)` is not a valid range. 1) Shifts the elements towards the beginning of the range: * If `n == 0 || n >= last - first`, there are no effects. * If `n < 0`, the behavior is undefined. * Otherwise, for every integer `i` in `[0, last - first - n)`, moves the element originally at position `first + n + i` to position `first + i`. The moves are performed in increasing order of `i` starting from `​0​`. 3) Shifts the elements towards the end of the range: * If `n == 0 || n >= last - first`, there are no effects. * If `n < 0`, the behavior is undefined. * Otherwise, for every integer `i` in `[0, last - first - n)`, moves the element originally at position `first + i` to position `first + n + i`. If `I` models [`bidirectional_iterator`](../../iterator/bidirectional_iterator "cpp/iterator/bidirectional iterator"), then the moves are performed in decreasing order of `i` starting from `last - first - n - 1`. 2, 4) Same as (1) or (3) respectively, but uses `r` as the range, as if using `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r)` as `first` and `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r)` as `last`. Elements that are in the original range but not the new range are left in a valid but unspecified state. The function-like entities described on this page are *niebloids*, that is: * Explicit template argument lists cannot be specified when calling any of them. * None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl"). * When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited. In practice, they may be implemented as function objects, or with special compiler extensions. ### Parameters | | | | | --- | --- | --- | | first | - | the beginning of the original range | | last | - | the end of the original range | | r | - | the range of elements to shift | | n | - | the number of positions to shift | ### Return value 1-2) `{first, /*NEW_LAST*/}`, where `*NEW\_LAST*` is the end of the resulting range and equivalent to: * `first + (last - first - n)`, if `n` is less than `last - first`; * `first` otherwise. 3-4) `{/*NEW_FIRST*/, last}`, where `*NEW\_FIRST*` is the beginning of the resulting range and equivalent to: * `first + n`, if `n` is less than `last - first`; * `last` otherwise. ### Complexity 1-2) At most `[ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(first, last) - n` assignments. 3-4) At most `[ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(first, last) - n` assignment or swaps. ### Notes `ranges::shift_left` / `ranges::shift_right` has better efficiency on common implementations if `I` models [`bidirectional_iterator`](../../iterator/bidirectional_iterator "cpp/iterator/bidirectional iterator") or (better) [`random_access_iterator`](../../iterator/random_access_iterator "cpp/iterator/random access iterator"). Implementations (e.g. [MSVC STL](https://github.com/microsoft/STL/blob/main/stl/src/vector_algorithms.cpp)) may enable vectorization when the iterator type models [`contiguous_iterator`](../../iterator/contiguous_iterator "cpp/iterator/contiguous iterator") and swapping its value type calls neither non-trivial special member function nor [ADL](../../language/adl "cpp/language/adl")-found `swap`. | [Feature-test](../../utility/feature_test "cpp/utility/feature test") macro | Value | Std | | --- | --- | --- | | [`__cpp_lib_shift`](../../feature_test#Library_features "cpp/feature test") | `202202L` | (C++23) | ### Example ``` #include <algorithm> #include <iostream> #include <string> #include <type_traits> #include <vector> struct S { int value{0}; bool specified_state{true}; S(int v = 0) : value{v} {} S(S const& rhs) = default; S(S&& rhs) { *this = std::move(rhs); } S& operator=(S const& rhs) = default; S& operator=(S&& rhs) { if (this != &rhs) { value = rhs.value; specified_state = rhs.specified_state; rhs.specified_state = false; } return *this; } }; template <typename T> std::ostream& operator<< (std::ostream& os, std::vector<T> const& v) { for (const auto& s : v) { if constexpr (std::is_same_v<T, S>) s.specified_state ? os << s.value << ' ' : os << ". "; else if constexpr (std::is_same_v<T, std::string>) os << (s.empty() ? "." : s) << ' '; else os << s << ' '; } return os; } int main() { std::cout << std::left; std::vector<S> a{1, 2, 3, 4, 5, 6, 7}; std::vector<int> b{1, 2, 3, 4, 5, 6, 7}; std::vector<std::string> c{"α", "β", "γ", "δ", "ε", "ζ", "η"}; std::cout << "vector<S> \tvector<int> \tvector<string>\n"; std::cout << a << " " << b << " " << c << '\n'; std::ranges::shift_left(a, 3); std::ranges::shift_left(b, 3); std::ranges::shift_left(c, 3); std::cout << a << " " << b << " " << c << '\n'; std::ranges::shift_right(a, 2); std::ranges::shift_right(b, 2); std::ranges::shift_right(c, 2); std::cout << a << " " << b << " " << c << '\n'; std::ranges::shift_left(a, 8); // has no effect: n >= last - first std::ranges::shift_left(b, 8); // ditto std::ranges::shift_left(c, 8); // ditto std::cout << a << " " << b << " " << c << '\n'; // std::ranges::shift_left(a, -3); // UB } ``` Possible output: ``` vector<S> vector<int> vector<string> 1 2 3 4 5 6 7 1 2 3 4 5 6 7 α β γ δ ε ζ η 4 5 6 7 . . . 4 5 6 7 5 6 7 δ ε ζ η . . . . . 4 5 6 7 . 4 5 4 5 6 7 5 . . δ ε ζ η . . . 4 5 6 7 . 4 5 4 5 6 7 5 . . δ ε ζ η . ``` ### See also | | | | --- | --- | | [ranges::move](move "cpp/algorithm/ranges/move") (C++20) | moves a range of elements to a new location (niebloid) | | [ranges::move\_backward](move_backward "cpp/algorithm/ranges/move backward") (C++20) | moves a range of elements to a new location in backwards order (niebloid) | | [ranges::rotate](rotate "cpp/algorithm/ranges/rotate") (C++20) | rotates the order of elements in a range (niebloid) | | [shift\_leftshift\_right](../shift "cpp/algorithm/shift") (C++20) | shifts elements in a range (function template) |
programming_docs
cpp std::ranges::min std::ranges::min ================ | Defined in header `[<algorithm>](../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | Call signature | | | | ``` template< class T, class Proj = std::identity, std::indirect_strict_weak_order< std::projected<const T*, Proj>> Comp = ranges::less > constexpr const T& min( const T& a, const T& b, Comp comp = {}, Proj proj = {} ); ``` | | (since C++20) | | ``` template< std::copyable T, class Proj = std::identity, std::indirect_strict_weak_order< std::projected<const T*, Proj>> Comp = ranges::less > constexpr const T min( std::initializer_list<T> r, Comp comp = {}, Proj proj = {} ); ``` | | (since C++20) | | ``` template< ranges::input_range R, class Proj = std::identity, std::indirect_strict_weak_order< std::projected<ranges::iterator_t<R>, Proj>> Comp = ranges::less > requires std::indirectly_copyable_storable<ranges::iterator_t<R>, ranges::range_value_t<R>*> constexpr ranges::range_value_t<R> min( R&& r, Comp comp = {}, Proj proj = {} ); ``` | | (since C++20) | Returns the smaller of the given projected elements. 1) Returns the smaller of `a` and `b`. 2) Returns the first smallest element in the initializer list `r`. 3) Returns the first smallest value in the range `r`. The function-like entities described on this page are *niebloids*, that is: * Explicit template argument lists cannot be specified when calling any of them. * None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl"). * When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited. In practice, they may be implemented as function objects, or with special compiler extensions. ### Parameters | | | | | --- | --- | --- | | a, b | - | the values to compare | | r | - | the range of values to compare | | comp | - | comparison to apply to the projected elements | | proj | - | projection to apply to the elements | ### Return value 1) The smaller of `a` and `b`, according to the projection. If they are equivalent, returns `a`. 2-3) The smallest element in `r`, according to the projection. If several values are equivalent to the smallest, returns the leftmost one. If the range is empty (as determined by `[ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(r)`), the behavior is undefined. ### Complexity 1) Exactly one comparison 2-3) Exactly `ranges::distance(r) - 1` comparisons ### Possible implementation | | | --- | | ``` struct min_fn { template<class T, class Proj = std::identity, std::indirect_strict_weak_order< std::projected<const T*, Proj>> Comp = ranges::less> constexpr const T& operator()(const T& a, const T& b, Comp comp = {}, Proj proj = {}) const { return std::invoke(comp, std::invoke(proj, b), std::invoke(proj, a)) ? b : a; } template<std::copyable T, class Proj = std::identity, std::indirect_strict_weak_order< std::projected<const T*, Proj>> Comp = ranges::less> constexpr const T operator()(std::initializer_list<T> r, Comp comp = {}, Proj proj = {}) const { return *ranges::min_element(r, std::ref(comp), std::ref(proj)); } template<ranges::input_range R, class Proj = std::identity, std::indirect_strict_weak_order< std::projected<ranges::iterator_t<R>, Proj>> Comp = ranges::less> requires std::indirectly_copyable_storable<ranges::iterator_t<R>, ranges::range_value_t<R>*> constexpr ranges::range_value_t<R> operator()(R&& r, Comp comp = {}, Proj proj = {}) const { using V = ranges::range_value_t<R>; if constexpr (ranges::forward_range<R>) { return static_cast<V>(*ranges::min_element(r, std::ref(comp), std::ref(proj))); } else { auto i = ranges::begin(r); auto s = ranges::end(r); V m(*i); while (++i != s) { if (std::invoke(comp, std::invoke(proj, *i), std::invoke(proj, m))) { m = *i; } } return m; } } }; inline constexpr min_fn min; ``` | ### Notes Capturing the result of `std::ranges::min` by reference produces a dangling reference if one of the parameters is a temporary and that parameter is returned: ``` int n = 1; const int& r = std::ranges::min(n-1, n+1); // r is dangling ``` ### Example ``` #include <algorithm> #include <iostream> #include <string> int main() { namespace ranges = std::ranges; using namespace std::string_view_literals; std::cout << "smaller of 1 and 9999: " << ranges::min(1, 9999) << '\n' << "smaller of 'a', and 'b': '" << ranges::min('a', 'b') << "'\n" << "shortest of \"foo\", \"bar\", and \"hello\": \"" << ranges::min({ "foo"sv, "bar"sv, "hello"sv }, {}, &std::string_view::size) << "\"\n"; } ``` Output: ``` smaller of 1 and 9999: 1 smaller of 'a', and 'b': 'a' shortest of "foo", "bar", and "hello": "foo" ``` ### See also | | | | --- | --- | | [ranges::max](max "cpp/algorithm/ranges/max") (C++20) | returns the greater of the given values (niebloid) | | [ranges::minmax](minmax "cpp/algorithm/ranges/minmax") (C++20) | returns the smaller and larger of two elements (niebloid) | | [ranges::min\_element](min_element "cpp/algorithm/ranges/min element") (C++20) | returns the smallest element in a range (niebloid) | | [ranges::clamp](clamp "cpp/algorithm/ranges/clamp") (C++20) | clamps a value between a pair of boundary values (niebloid) | | [min](../min "cpp/algorithm/min") | returns the smaller of the given values (function template) | cpp std::ranges::includes std::ranges::includes ===================== | Defined in header `[<algorithm>](../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | Call signature | | | | ``` template< std::input_iterator I1, std::sentinel_for<I1> S1, std::input_iterator I2, std::sentinel_for<I2> S2, class Proj1 = std::identity, class Proj2 = std::identity, std::indirect_strict_weak_order< std::projected<I1, Proj1>, std::projected<I2, Proj2>> Comp = ranges::less > constexpr bool includes( I1 first1, S1 last1, I2 first2, S2 last2, Comp comp = {}, Proj1 proj1 = {}, Proj2 proj2 = {} ) ``` | (1) | (since C++20) | | ``` template< ranges::input_range R1, ranges::input_range R2, class Proj1 = std::identity, class Proj2 = std::identity, std::indirect_strict_weak_order< std::projected<ranges::iterator_t<R1>, Proj1>, std::projected<ranges::iterator_t<R2>, Proj2>> Comp = ranges::less > constexpr bool includes( R1&& r1, R2&& r2, Comp comp = {}, Proj1 proj1 = {}, Proj2 proj2 = {} ) ``` | (2) | (since C++20) | 1) Returns `true` if the projections of the sorted range `[first2, last2)` is a [subsequence](https://en.wikipedia.org/wiki/subsequence "enwiki:subsequence") of the projections of the sorted range `[first1, last1)`. 2) Same as (1), but uses `r1` and `r2` as the source ranges, as if by using `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r1)` and `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r2)` as `first1` and `first2` respectively, and `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r1)` and `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r2)` as `last1` and `last2` respectively. Both ranges must be sorted with the given comparison function `comp`. A subsequence need not be contiguous. The function-like entities described on this page are *niebloids*, that is: * Explicit template argument lists cannot be specified when calling any of them. * None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl"). * When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited. In practice, they may be implemented as function objects, or with special compiler extensions. ### Parameters | | | | | --- | --- | --- | | first1, last1 | - | the sorted range of elements to examine | | r1 | - | the sorted range of elements to examine | | first2, last2 | - | the sorted range of elements to search for | | r2 | - | the sorted range of elements to search for | | comp | - | comparison function to apply to the projected elements | | proj1 | - | projection to apply to the elements in the first range | | proj2 | - | projection to apply to the elements in the second range | ### Return value `true` if `[first2, last2)` is a subsequence of `[first1, last1)`; otherwise `false`. ### Complexity At most \(\scriptsize 2 \cdot (N\_1+N\_2-1)\)2·(N1+N2-1) comparisons, where \(\scriptsize N\_1\)N1 is `[ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(r1)` and \(\scriptsize N\_2\)N2 is `[ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(r2)`. ### Possible implementation | | | --- | | ``` struct includes_fn { template<std::input_iterator I1, std::sentinel_for<I1> S1, std::input_iterator I2, std::sentinel_for<I2> S2, class Proj1 = std::identity, class Proj2 = std::identity, std::indirect_strict_weak_order< std::projected<I1, Proj1>, std::projected<I2, Proj2>> Comp = ranges::less> constexpr bool operator()(I1 first1, S1 last1, I2 first2, S2 last2, Comp comp = {}, Proj1 proj1 = {}, Proj2 proj2 = {}) const { for (; first2 != last2; ++first1) { if (first1 == last1 && comp(*first2, *first1)) return false; if (!comp(*first1, *first2)) ++first2; } return true; } template<ranges::input_range R1, ranges::input_range R2, class Proj1 = std::identity, class Proj2 = std::identity, std::indirect_strict_weak_order< std::projected<ranges::iterator_t<R1>, Proj1>, std::projected<ranges::iterator_t<R2>, Proj2>> Comp = ranges::less> constexpr bool operator()(R1&& r1, R2&& r2, Comp comp = {}, Proj1 proj1 = {}, Proj2 proj2 = {}) const { return (*this)(ranges::begin(r1), ranges::end(r1), ranges::begin(r2), ranges::end(r2), std::ref(comp), std::ref(proj1), std::ref(proj2)); } }; inline constexpr auto includes = includes_fn{}; ``` | ### Example ``` #include <algorithm> #include <cctype> #include <initializer_list> #include <iomanip> #include <iostream> #include <locale> #include <string> template <class T> std::ostream& operator<<(std::ostream& os, std::initializer_list<T> const& list) { for (os << "{ "; auto const& elem : list) os << elem << ' '; return os << "} "; } struct true_false : std::numpunct<char> { std::string do_truename() const { return "? Yes\n"; } std::string do_falsename() const { return "? No\n"; } }; int main() { std::cout.imbue(std::locale(std::cout.getloc(), new true_false)); auto ignore_case = [](char a, char b) { return std::tolower(a) < std::tolower(b); }; const auto a = {'a', 'b', 'c'}, b = {'a', 'c'}, c = {'a', 'a', 'b'}, d = {'g'}, e = {'a', 'c', 'g'}, f = {'A', 'B', 'C'}, z = {'a', 'b', 'c', 'f', 'h', 'x'}; std::cout << z << "includes\n" << std::boolalpha << a << std::ranges::includes(z.begin(), z.end(), a.begin(), a.end()) << b << std::ranges::includes(z, b) << c << std::ranges::includes(z, c) << d << std::ranges::includes(z, d) << e << std::ranges::includes(z, e) << f << std::ranges::includes(z, f, ignore_case); } ``` Output: ``` { a b c f h x } includes { a b c } ? Yes { a c } ? Yes { a a b } ? No { g } ? No { a c g } ? No { A B C } ? Yes ``` ### See also | | | | --- | --- | | [ranges::set\_difference](set_difference "cpp/algorithm/ranges/set difference") (C++20) | computes the difference between two sets (niebloid) | | [ranges::search](search "cpp/algorithm/ranges/search") (C++20) | searches for a range of elements (niebloid) | | [includes](../includes "cpp/algorithm/includes") | returns true if one sequence is a subsequence of another (function template) | cpp std::ranges::generate_n std::ranges::generate\_n ======================== | Defined in header `[<algorithm>](../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | Call signature | | | | ``` template<std::input_or_output_iterator O, std::copy_constructible F> requires std::invocable<F&> && std::indirectly_writable<O, std::invoke_result_t<F&>> constexpr O generate_n( O first, std::iter_difference_t<O> n, F gen ); ``` | | (since C++20) | Assigns the result of *successive* invocations of the function object `gen` to each element in the range `[first, first + n)`, if `0 < n`. Does nothing otherwise. The function-like entities described on this page are *niebloids*, that is: * Explicit template argument lists cannot be specified when calling any of them. * None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl"). * When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited. In practice, they may be implemented as function objects, or with special compiler extensions. ### Parameters | | | | | --- | --- | --- | | first | - | the beginning of the range of elements to modify | | n | - | number of elements to modify | | gen | - | the generator function object. | ### Return value Iterator one past the last element assigned if `0 < count`, `first` otherwise. ### Complexity Exactly `n` invocations of `gen()` and assignments. ### Possible implementation | | | --- | | ``` struct generate_n_fn { template<std::input_or_output_iterator O, std::copy_constructible F> requires std::invocable<F&> && std::indirectly_writable<O, std::invoke_result_t<F&>> constexpr O operator()( O first, std::iter_difference_t<O> n, F gen ) const { for (; n-- > 0; *first = std::invoke(gen), ++first); return first; } }; inline constexpr generate_n_fn generate_n{}; ``` | ### Example ``` #include <algorithm> #include <array> #include <iostream> #include <random> #include <string_view> auto dice() { static std::uniform_int_distribution<int> distr{1, 6}; static std::random_device engine; static std::mt19937 noise{engine()}; return distr(noise); } void print(const auto& v, std::string_view comment) { for (int i : v) { std::cout << i << ' '; } std::cout << "(" << comment << ")\n"; } int main() { std::array<int, 8> v; std::ranges::generate_n(v.begin(), v.size(), dice); print(v, "dice"); std::ranges::generate_n(v.begin(), v.size(), [n{0}] () mutable { return n++; }); // same effect as std::iota(v.begin(), v.end(), 0); print(v, "iota"); } ``` Possible output: ``` 5 5 2 2 6 6 3 5 (dice) 0 1 2 3 4 5 6 7 (iota) ``` ### See also | | | | --- | --- | | [ranges::generate](generate "cpp/algorithm/ranges/generate") (C++20) | saves the result of a function in a range (niebloid) | | [ranges::fill](fill "cpp/algorithm/ranges/fill") (C++20) | assigns a range of elements a certain value (niebloid) | | [ranges::fill\_n](fill_n "cpp/algorithm/ranges/fill n") (C++20) | assigns a value to a number of elements (niebloid) | | [ranges::transform](transform "cpp/algorithm/ranges/transform") (C++20) | applies a function to a range of elements (niebloid) | | [generate\_n](../generate_n "cpp/algorithm/generate n") | assigns the results of successive function calls to N elements in a range (function template) | cpp std::ranges::binary_search std::ranges::binary\_search =========================== | Defined in header `[<algorithm>](../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | Call signature | | | | ``` template< std::forward_iterator I, std::sentinel_for<I> S, class T, class Proj = std::identity, std::indirect_strict_weak_order< const T*, std::projected<I, Proj>> Comp = ranges::less > constexpr bool binary_search( I first, S last, const T& value, Comp comp = {}, Proj proj = {} ); ``` | (1) | (since C++20) | | ``` template< ranges::forward_range R, class T, class Proj = std::identity, std::indirect_strict_weak_order< const T*, std::projected<ranges::iterator_t<R>, Proj>> Comp = ranges::less > constexpr bool binary_search( R&& r, const T& value, Comp comp = {}, Proj proj = {} ); ``` | (2) | (since C++20) | 1) Checks if a projected element equivalent to `value` appears within the range `[first, last)`. 2) Same as (1), but uses `r` as the source range, as if using `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r)` as `first` and `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r)` as `last`. For `ranges::binary_search` to succeed, the range `[first, last)` must be at least partially ordered with respect to `value`, i.e. it must satisfy all of the following requirements: * partitioned with respect to `[std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(comp, [std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(proj, element), value)` (that is, all projected elements for which the expression is `true` precedes all elements for which the expression is `false`) * partitioned with respect to `![std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(comp, value, [std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(proj, element))` * for all elements, if `[std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(comp, [std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(proj, element), value)` is `true` then `![std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(comp, value, [std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(proj, element))` is also `true` A fully-sorted range meets these criteria. The function-like entities described on this page are *niebloids*, that is: * Explicit template argument lists cannot be specified when calling any of them. * None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl"). * When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited. In practice, they may be implemented as function objects, or with special compiler extensions. ### Parameters | | | | | --- | --- | --- | | first, last | - | the range of elements to examine | | r | - | the range of elements to examine | | value | - | value to compare the elements to | | comp | - | comparison function to apply to the projected elements | | proj | - | projection to apply to the elements | ### Return value `true` if an element equal to `value` is found, `false` otherwise. ### Complexity The number of comparisons and projections performed is logarithmic in the distance between `first` and `last` (At most log 2(last - first) + O(1) comparisons and projections). However, for iterator-sentinel pair that does not model `[std::random\_access\_iterator](../../iterator/random_access_iterator "cpp/iterator/random access iterator")`, number of iterator increments is linear. ### Possible implementation | | | --- | | ``` struct binary_search_fn { template<std::forward_iterator I, std::sentinel_for<I> S, class T, class Proj = std::identity, std::indirect_strict_weak_order< const T*, std::projected<I, Proj>> Comp = ranges::less> constexpr bool operator()(I first, S last, const T& value, Comp comp = {}, Proj proj = {}) const { first = std::lower_bound(first, last, value, comp); return (!(first == last) && !(comp(value, *first))); } template<ranges::forward_range R, class T, class Proj = std::identity, std::indirect_strict_weak_order< const T*, std::projected<ranges::iterator_t<R>, Proj>> Comp = ranges::less> constexpr bool operator()(R&& r, const T& value, Comp comp = {}, Proj proj = {}) const { return (*this)(ranges::begin(r), ranges::end(r), value, std::ref(comp), std::ref(proj)); } }; inline constexpr binary_search_fn binary_search; ``` | ### Example ``` #include <algorithm> #include <iostream> #include <ranges> int main() { constexpr static auto haystack = {1, 3, 4, 5, 9}; static_assert(std::ranges::is_sorted(haystack)); for (const int needle : std::views::iota(1) | std::views::take(3)) { std::cout << "Searching for " << needle << ": "; std::ranges::binary_search(haystack, needle) ? std::cout << "found " << needle << '\n' : std::cout << "no dice!\n"; } } ``` Output: ``` Searching for 1: found 1 Searching for 2: no dice! Searching for 3: found 3 ``` ### See also | | | | --- | --- | | [ranges::equal\_range](equal_range "cpp/algorithm/ranges/equal range") (C++20) | returns range of elements matching a specific key (niebloid) | | [ranges::lower\_bound](lower_bound "cpp/algorithm/ranges/lower bound") (C++20) | returns an iterator to the first element *not less* than the given value (niebloid) | | [ranges::upper\_bound](upper_bound "cpp/algorithm/ranges/upper bound") (C++20) | returns an iterator to the first element *greater* than a certain value (niebloid) | | [ranges::containsranges::contains\_subrange](contains "cpp/algorithm/ranges/contains") (C++23)(C++23) | checks if the range contains the given element or subrange (niebloid) | | [binary\_search](../binary_search "cpp/algorithm/binary search") | determines if an element exists in a partially-ordered range (function template) |
programming_docs
cpp std::ranges::partition std::ranges::partition ====================== | Defined in header `[<algorithm>](../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | Call signature | | | | ``` template< std::permutable I, std::sentinel_for<I> S, class Proj = std::identity, std::indirect_unary_predicate<std::projected<I, Proj>> Pred > constexpr ranges::subrange<I> partition( I first, S last, Pred pred, Proj proj = {} ); ``` | (1) | (since C++20) | | ``` template< ranges::forward_range R, class Proj = std::identity, std::indirect_unary_predicate< std::projected<ranges::iterator_t<R>, Proj>> Pred > requires std::permutable<ranges::iterator_t<R>> constexpr ranges::borrowed_subrange_t<R> partition( R&& r, Pred pred, Proj proj = {} ); ``` | (2) | (since C++20) | 1) Reorders the elements in the range `[first, last)` in such a way that the projection `proj` of all elements for which the predicate `pred` returns `true` precede the projection `proj` of elements for which predicate `pred` returns `false`. Relative order of elements is not preserved. 2) Same as (1), but uses `r` as the source range, as if using `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r)` as `first` and `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r)` as `last`. The function-like entities described on this page are *niebloids*, that is: * Explicit template argument lists cannot be specified when calling any of them. * None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl"). * When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited. In practice, they may be implemented as function objects, or with special compiler extensions. ### Parameters | | | | | --- | --- | --- | | first, last | - | the range of elements to reorder | | r | - | the range of elements to reorder | | pred | - | predicate to apply to the projected elements | | proj | - | projection to apply to the elements. | ### Return value A subrange starting with an iterator to the first element of the second group and finishing with an iterator equal to `last`. (2) returns `[std::ranges::dangling](../../ranges/dangling "cpp/ranges/dangling")` if `r` is an rvalue of non-[`borrowed_range`](../../ranges/borrowed_range "cpp/ranges/borrowed range") type. ### Complexity Given `N = [ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(first,last)`, exactly N applications of the predicate and projection. At most N/2 swaps if `I` models `ranges::bidirectional_iterator`, and at most N swaps otherwise. ### Possible implementation | | | --- | | ``` struct partition_fn { template<std::permutable I, std::sentinel_for<I> S, class Proj = std::identity, std::indirect_unary_predicate<std::projected<I, Proj>> Pred> constexpr ranges::subrange<I> operator()(I first, S last, Pred pred, Proj proj = {}) const { first = ranges::find_if_not(first, last, std::ref(pred), std::ref(proj)); if (first == last) { return {first, first}; } for (auto i = ranges::next(first); i != last; ++i) { if (std::invoke(pred, std::invoke(proj, *i))) { ranges::iter_swap(i, first); ++first; } } return {std::move(first), std::move(last)}; } template<ranges::forward_range R, class Proj = std::identity, std::indirect_unary_predicate< std::projected<ranges::iterator_t<R>, Proj>> Pred> requires std::permutable<ranges::iterator_t<R>> constexpr ranges::borrowed_subrange_t<R> operator()(R&& r, Pred pred, Proj proj = {}) const { return (*this)(ranges::begin(r), ranges::end(r), std::ref(pred), std::ref(proj)); } }; inline constexpr partition_fn partition; ``` | ### Example ``` #include <algorithm> #include <forward_list> #include <functional> #include <iostream> #include <iterator> #include <ranges> #include <vector> namespace ranges = std::ranges; template <class I, std::sentinel_for<I> S, class Cmp = ranges::less> requires std::sortable<I, Cmp> void quicksort(I first, S last, Cmp cmp = Cmp{}) { using reference = std::iter_reference_t<I>; if (first == last) return; auto size = ranges::distance(first, last); auto pivot = ranges::next(first, size - 1); ranges::iter_swap(pivot, ranges::next(first, size / 2)); auto tail = ranges::partition(first, pivot, [=](reference em) { // em < pivot return std::invoke(cmp, em, *pivot); }); ranges::iter_swap(pivot, tail.begin()); quicksort(first, tail.begin(), std::ref(cmp)); quicksort(ranges::next(tail.begin()), last, std::ref(cmp)); } int main() { std::ostream_iterator<int> cout {std::cout, " "}; std::vector<int> v {0,1,2,3,4,5,6,7,8,9}; std::cout << "Original vector: \t"; ranges::copy(v, cout); auto tail = ranges::partition(v, [](int i){return i % 2 == 0;}); std::cout << "\nPartitioned vector: \t"; ranges::copy(ranges::begin(v), ranges::begin(tail), cout); std::cout << "│ "; ranges::copy(tail, cout); std::forward_list<int> fl {1, 30, -4, 3, 5, -4, 1, 6, -8, 2, -5, 64, 1, 92}; std::cout << "\nUnsorted list: \t\t"; ranges::copy(fl, cout); quicksort(ranges::begin(fl), ranges::end(fl), ranges::greater{}); std::cout << "\nQuick-sorted list: \t"; ranges::copy(fl, cout); std::cout << '\n'; } ``` Possible output: ``` Original vector: 0 1 2 3 4 5 6 7 8 9 Partitioned vector: 0 8 2 6 4 │ 5 3 7 1 9 Unsorted list: 1 30 -4 3 5 -4 1 6 -8 2 -5 64 1 92 Quick-sorted list: 92 64 30 6 5 3 2 1 1 1 -4 -4 -5 -8 ``` ### See also | | | | --- | --- | | [ranges::partition\_copy](partition_copy "cpp/algorithm/ranges/partition copy") (C++20) | copies a range dividing the elements into two groups (niebloid) | | [ranges::is\_partitioned](is_partitioned "cpp/algorithm/ranges/is partitioned") (C++20) | determines if the range is partitioned by the given predicate (niebloid) | | [ranges::stable\_partition](stable_partition "cpp/algorithm/ranges/stable partition") (C++20) | divides elements into two groups while preserving their relative order (niebloid) | | [partition](../partition "cpp/algorithm/partition") | divides a range of elements into two groups (function template) | cpp std::ranges::is_partitioned std::ranges::is\_partitioned ============================ | Defined in header `[<algorithm>](../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | Call signature | | | | ``` template< std::input_iterator I, std::sentinel_for<I> S, class Proj = std::identity, std::indirect_unary_predicate<std::projected<I, Proj>> Pred > constexpr bool is_partitioned( I first, S last, Pred pred, Proj proj = {} ); ``` | (1) | (since C++20) | | ``` template< ranges::input_range R, class Proj = std::identity, std::indirect_unary_predicate<std::projected<ranges::iterator_t<R>, Proj>> Pred > constexpr bool is_partitioned( R&& r, Pred pred, Proj proj = {} ); ``` | (2) | (since C++20) | 1) Returns `true` if all elements in the range `[first, last)` that satisfy the predicate `p` after projection appear before all elements that don't. Also returns `true` if `[first, last)` is empty. 2) Same as (1), but uses `r` as the source range, as if using `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r)` as `first` and `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r)` as `last`. The function-like entities described on this page are *niebloids*, that is: * Explicit template argument lists cannot be specified when calling any of them. * None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl"). * When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited. In practice, they may be implemented as function objects, or with special compiler extensions. ### Parameters | | | | | --- | --- | --- | | first, last | - | iterator-sentinel pair denoting the range of elements to examine | | r | - | the range of elements to examine | | pred | - | predicate to apply to the projected elements | | proj | - | projection to apply to the elements | ### Return value `true` if the range `[first, last)` is empty or is partitioned by `p`. `false` otherwise. ### Complexity At most `ranges::distance(first, last)` applications of `pred` and `proj`. ### Possible implementation | | | --- | | ``` struct is_partitioned_fn { template<std::input_iterator I, std::sentinel_for<I> S, class Proj = std::identity, std::indirect_unary_predicate<std::projected<I, Proj>> Pred> constexpr bool operator()(I first, S last, Pred pred, Proj proj = {}) const { for (; first != last; ++first) { if (!std::invoke(pred, std::invoke(proj, *first))) { break; } } for (; first != last; ++first) { if (std::invoke(pred, std::invoke(proj, *first))) { return false; } } return true; } template<ranges::input_range R, class Proj = std::identity, std::indirect_unary_predicate<std::projected<ranges::iterator_t<R>, Proj>> Pred> constexpr bool operator()(R&& r, Pred pred, Proj proj = {}) const { return (*this)(ranges::begin(r), ranges::end(r), std::ref(pred), std::ref(proj)); } }; inline constexpr auto is_partitioned = is_partitioned_fn(); ``` | ### Example ``` #include <algorithm> #include <array> #include <iostream> #include <utility> int main() { std::array<int, 9> v; auto is_even = [](int i){ return i % 2 == 0; }; auto print = [&](bool o) { for (int x : v) std::cout << x << ' '; std::cout << (o ? "=> " : "=> not ") << "partitioned\n"; }; std::iota(v.begin(), v.end(), 1); print(std::ranges::is_partitioned(v, is_even)); std::ranges::partition(v, is_even); print(std::ranges::is_partitioned(std::as_const(v), is_even)); std::ranges::reverse(v); print(std::ranges::is_partitioned(v.cbegin(), v.cend(), is_even)); print(std::ranges::is_partitioned(v.crbegin(), v.crend(), is_even)); } ``` Output: ``` 1 2 3 4 5 6 7 8 9 => not partitioned 2 4 6 8 5 3 7 1 9 => partitioned 9 1 7 3 5 8 6 4 2 => not partitioned 9 1 7 3 5 8 6 4 2 => partitioned ``` ### See also | | | | --- | --- | | [ranges::partition](partition "cpp/algorithm/ranges/partition") (C++20) | divides a range of elements into two groups (niebloid) | | [ranges::partition\_point](partition_point "cpp/algorithm/ranges/partition point") (C++20) | locates the partition point of a partitioned range (niebloid) | | [is\_partitioned](../is_partitioned "cpp/algorithm/is partitioned") (C++11) | determines if the range is partitioned by the given predicate (function template) | cpp std::ranges::make_heap std::ranges::make\_heap ======================= | Defined in header `[<algorithm>](../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | Call signature | | | | ``` template< std::random_access_iterator I, std::sentinel_for<I> S, class Comp = ranges::less, class Proj = std::identity > requires std::sortable<I, Comp, Proj> constexpr I make_heap( I first, S last, Comp comp = {}, Proj proj = {} ); ``` | (1) | (since C++20) | | ``` template< ranges::random_access_range R, class Comp = ranges::less, class Proj = std::identity > requires std::sortable<ranges::iterator_t<R>, Comp, Proj> constexpr ranges::borrowed_iterator_t<R> make_heap( R&& r, Comp comp = {}, Proj proj = {} ); ``` | (2) | (since C++20) | Constructs a [*max heap*](https://en.wikipedia.org/wiki/Binary_heap "enwiki:Binary heap") in the range `[first, last)`. 1) Elements are compared using the given binary comparison function `comp` and projection object `proj`. 2) Same as (1), but uses `r` as the range, as if using `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r)` as `first` and `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r)` as `last`. The function-like entities described on this page are *niebloids*, that is: * Explicit template argument lists cannot be specified when calling any of them. * None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl"). * When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited. In practice, they may be implemented as function objects, or with special compiler extensions. ### Parameters | | | | | --- | --- | --- | | first, last | - | the range of elements to make the heap from | | r | - | the range of elements to make the heap from | | pred | - | predicate to apply to the projected elements | | proj | - | projection to apply to the elements | ### Return value An iterator equal to `last`. ### Complexity Given `N = [ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(first, last)`, at most \(\scriptsize 3\cdot N\)3•N comparisons and \(\scriptsize 6\cdot N\)6•N projections. ### Notes A *max heap* is a range of elements `[f, l)`, arranged with respect to comparator `comp` and projection `proj`, that has the following properties: * With `N = l-f`, `p = f[(i-1)/2]`, and `q = f[i]`, for all `0 < i < N`, the expression `[std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(comp, [std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(proj, p), [std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(proj, q))` evaluates to `false`. * A new element can be added using `[ranges::push\_heap](push_heap "cpp/algorithm/ranges/push heap")`, in \(\scriptsize \mathcal{O}(\log N)\)𝓞(log N) time. * The first element can be removed using `[ranges::pop\_heap](pop_heap "cpp/algorithm/ranges/pop heap")`, in \(\scriptsize \mathcal{O}(\log N)\)𝓞(log N) time. ### Example ``` #include <algorithm> #include <vector> #include <cmath> #include <functional> #include <iostream> void draw_heap(auto const& v); void out(const auto& what, int n = 1) { while (n-- > 0) std::cout << what; } void print(auto rem, auto const& v) { out(rem); for (auto e : v) { out(e), out(' '); } out('\n'); } int main() { std::vector h {1, 6, 1, 8, 0, 3, 3, 9, 8, 8, 7, 4, 9, 8, 9}; print("source: ", h); std::ranges::make_heap(h); print("\n" "max-heap: ", h); draw_heap(h); std::ranges::make_heap(h, std::greater{}); print("\n" "min-heap: ", h); draw_heap(h); } void draw_heap(auto const& v) { auto bails = [](int n, int w) { auto b = [](int w) { out("┌"), out("─", w), out("┴"), out("─", w), out("┐"); }; if (!(n /= 2)) return; for (out(' ', w); n-- > 0; ) b(w), out(' ', w + w + 1); out('\n'); }; auto data = [](int n, int w, auto& first, auto last) { for(out(' ', w); n-- > 0 && first != last; ++first) out(*first), out(' ', w + w + 1); out('\n'); }; auto tier = [&](int t, int m, auto& first, auto last) { const int n {1 << t}; const int w {(1 << (m - t - 1)) - 1}; bails(n, w), data(n, w, first, last); }; const int m {static_cast<int>(std::ceil(std::log2(1 + v.size())))}; auto first {v.cbegin()}; for (int i{}; i != m; ++i) { tier(i, m, first, v.cend()); } } ``` Output: ``` source: 1 6 1 8 0 3 3 9 8 8 7 4 9 8 9 max-heap: 9 8 9 8 8 4 9 6 1 0 7 1 3 8 3 9 ┌───┴───┐ 8 9 ┌─┴─┐ ┌─┴─┐ 8 8 4 9 ┌┴┐ ┌┴┐ ┌┴┐ ┌┴┐ 6 1 0 7 1 3 8 3 min-heap: 0 1 1 8 6 3 3 9 8 8 7 4 9 8 9 0 ┌───┴───┐ 1 1 ┌─┴─┐ ┌─┴─┐ 8 6 3 3 ┌┴┐ ┌┴┐ ┌┴┐ ┌┴┐ 9 8 8 7 4 9 8 9 ``` ### See also | | | | --- | --- | | [ranges::is\_heap](is_heap "cpp/algorithm/ranges/is heap") (C++20) | checks if the given range is a max heap (niebloid) | | [ranges::is\_heap\_until](is_heap_until "cpp/algorithm/ranges/is heap until") (C++20) | finds the largest subrange that is a max heap (niebloid) | | [ranges::push\_heap](push_heap "cpp/algorithm/ranges/push heap") (C++20) | adds an element to a max heap (niebloid) | | [ranges::pop\_heap](pop_heap "cpp/algorithm/ranges/pop heap") (C++20) | removes the largest element from a max heap (niebloid) | | [ranges::sort\_heap](sort_heap "cpp/algorithm/ranges/sort heap") (C++20) | turns a max heap into a range of elements sorted in ascending order (niebloid) | | [make\_heap](../make_heap "cpp/algorithm/make heap") | creates a max heap out of a range of elements (function template) | cpp std::ranges::search std::ranges::search =================== | Defined in header `[<algorithm>](../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | Call signature | | | | ``` template< std::forward_iterator I1, std::sentinel_for<I1> S1, std::forward_iterator I2, std::sentinel_for<I2> S2, class Pred = ranges::equal_to, class Proj1 = std::identity, class Proj2 = std::identity > requires std::indirectly_comparable<I1, I2, Pred, Proj1, Proj2> constexpr ranges::subrange<I1> search( I1 first1, S1 last1, I2 first2, S2 last2, Pred pred = {}, Proj1 proj1 = {}, Proj2 proj2 = {} ); ``` | (1) | (since C++20) | | ``` template< ranges::forward_range R1, ranges::forward_range R2, class Pred = ranges::equal_to, class Proj1 = std::identity, class Proj2 = std::identity> requires std::indirectly_comparable<ranges::iterator_t<R1>, ranges::iterator_t<R2>, Pred, Proj1, Proj2> constexpr ranges::borrowed_subrange_t<R1> search( R1&& r1, R2&& r2, Pred pred = {}, Proj1 proj1 = {}, Proj2 proj2 = {} ); ``` | (2) | (since C++20) | 1) Searches for the *first* occurrence of the sequence of elements `[first2, last2)` in the range `[first1, last1)`. Elements are compared using binary predicate `pred` after being projected with `proj2` and `proj1`, respectively. 2) Same as (1), but uses `r1` as the first source range and `r2` as the second source range, as if using `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r1)` as `first1`, `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r1)` as `last1`, `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r2)` as `first2`, and `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r2)` as `last2`. The function-like entities described on this page are *niebloids*, that is: * Explicit template argument lists cannot be specified when calling any of them. * None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl"). * When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited. In practice, they may be implemented as function objects, or with special compiler extensions. ### Parameters | | | | | --- | --- | --- | | first1, last1 | - | the range of elements to examine (aka *haystack*) | | first2, last2 | - | the range of elements to search for (aka *needle*) | | r1 | - | the range of elements to examine (aka *haystack*) | | r2 | - | the range of elements to search for (aka *needle*) | | pred | - | binary predicate to apply to the projected elements | | proj1 | - | projection to apply to the elements in the first range | | proj2 | - | projection to apply to the elements in the second range | ### Return value 1) Returns a `[ranges::subrange](http://en.cppreference.com/w/cpp/ranges/subrange)` value that is the first occurrence of the sequence `[first2, last2)` (aka *needle*) in the range `[first1, last1)` (aka *haystack*), after application of the projections `proj1` and `proj2` to the elements of both sequences respectively with consequencing application of the binary predicate `pred` to compare projected elements. If no such occurrence is found, `[ranges::subrange](http://en.cppreference.com/w/cpp/ranges/subrange){last1, last1}` is returned. If the range to search for (aka. *needle*) is empty, that is `first2 == last2`, then the `[ranges::subrange](http://en.cppreference.com/w/cpp/ranges/subrange){first1, first1}` is returned. 2) Same as (1) but the return type is `[ranges::borrowed\_subrange\_t](http://en.cppreference.com/w/cpp/ranges/borrowed_iterator_t)<R1>`. ### Complexity At most `S*N` applications of the corresponding predicate and each projection, where (1) `S = [ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(first2, last2)` and `N = [ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(first1, last1)`; (2) `S = [ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(r2)` and `N = [ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(r1)`. ### Possible implementation | | | --- | | ``` struct search_fn { template<std::forward_iterator I1, std::sentinel_for<I1> S1, std::forward_iterator I2, std::sentinel_for<I2> S2, class Pred = ranges::equal_to, class Proj1 = std::identity, class Proj2 = std::identity> requires std::indirectly_comparable<I1, I2, Pred, Proj1, Proj2> constexpr ranges::subrange<I1> operator()(I1 first1, S1 last1, I2 first2, S2 last2, Pred pred = {}, Proj1 proj1 = {}, Proj2 proj2 = {}) const { for (;; ++first1) { I1 it1 = first1; for (I2 it2 = first2;; ++it1, ++it2) { if (it2 == last2) return {first1, it1}; if (it1 == last1) return {it1, it1}; if (!std::invoke(pred, std::invoke(proj1, *it1), std::invoke(proj2, *it2))) break; } } } template<ranges::forward_range R1, ranges::forward_range R2, class Pred = ranges::equal_to, class Proj1 = std::identity, class Proj2 = std::identity> requires std::indirectly_comparable<ranges::iterator_t<R1>, ranges::iterator_t<R2>, Pred, Proj1, Proj2> constexpr ranges::borrowed_subrange_t<R1> operator()(R1&& r1, R2&& r2, Pred pred = {}, Proj1 proj1 = {}, Proj2 proj2 = {}) const { return (*this)(ranges::begin(r1), ranges::end(r1), ranges::begin(r2), ranges::end(r2), std::move(pred), std::move(proj1), std::move(proj2)); } }; inline constexpr search_fn search{}; ``` | ### Example ``` #include <algorithm> #include <cctype> #include <iostream> #include <iterator> #include <string_view> using namespace std::literals; void print(int id, const auto& haystack, const auto& needle, const auto& found) { std::cout << id << "). search(\"" << haystack << "\", \"" << needle << "\"); "; const auto first = std::distance(haystack.begin(), found.begin()); const auto last = std::distance(haystack.begin(), found.end()); if (found.empty()) { std::cout << "not found;"; } else { std::cout << "found: \""; for (const auto x: found) { std::cout << x; } std::cout << "\";"; } std::cout << " subrange: {" << first << ", " << last << "}\n"; } int main() { constexpr auto haystack {"abcd abcd"sv}; constexpr auto needle {"bcd"sv}; // the search uses iterator pairs begin()/end(): constexpr auto found1 = std::ranges::search( haystack.begin(), haystack.end(), needle.begin(), needle.end()); print(1, haystack, needle, found1); // the search uses ranges r1, r2: constexpr auto found2 = std::ranges::search(haystack, needle); print(2, haystack, needle, found2); // 'needle' range is empty: constexpr auto none {""sv}; constexpr auto found3 = std::ranges::search(haystack, none); print(3, haystack, none, found3); // 'needle' will not be found: constexpr auto awl {"efg"sv}; constexpr auto found4 = std::ranges::search(haystack, awl); print(4, haystack, awl, found4); // the search uses custom comparator and projections: constexpr auto bodkin {"234"sv}; auto found5 = std::ranges::search(haystack, bodkin, [](const int x, const int y) { return x == y; }, // pred [](const int x) { return std::toupper(x); }, // proj1 [](const int y) { return y + 'A' - '1'; } // proj2 ); print(5, haystack, bodkin, found5); } ``` Output: ``` 1). search("abcd abcd", "bcd"); found: "bcd"; subrange: {1, 4} 2). search("abcd abcd", "bcd"); found: "bcd"; subrange: {1, 4} 3). search("abcd abcd", ""); not found; subrange: {0, 0} 4). search("abcd abcd", "efg"); not found; subrange: {9, 9} 5). search("abcd abcd", "234"); found: "bcd"; subrange: {1, 4} ``` ### See also | | | | --- | --- | | [ranges::adjacent\_find](adjacent_find "cpp/algorithm/ranges/adjacent find") (C++20) | finds the first two adjacent items that are equal (or satisfy a given predicate) (niebloid) | | [ranges::findranges::find\_ifranges::find\_if\_not](find "cpp/algorithm/ranges/find") (C++20)(C++20)(C++20) | finds the first element satisfying specific criteria (niebloid) | | [ranges::find\_end](find_end "cpp/algorithm/ranges/find end") (C++20) | finds the last sequence of elements in a certain range (niebloid) | | [ranges::find\_first\_of](find_first_of "cpp/algorithm/ranges/find first of") (C++20) | searches for any one of a set of elements (niebloid) | | [ranges::includes](includes "cpp/algorithm/ranges/includes") (C++20) | returns true if one sequence is a subsequence of another (niebloid) | | [ranges::mismatch](mismatch "cpp/algorithm/ranges/mismatch") (C++20) | finds the first position where two ranges differ (niebloid) | | [ranges::search\_n](search_n "cpp/algorithm/ranges/search n") (C++20) | searches for a number consecutive copies of an element in a range (niebloid) | | [search](../search "cpp/algorithm/search") | searches for a range of elements (function template) |
programming_docs
cpp std::ranges::sort_heap std::ranges::sort\_heap ======================= | Defined in header `[<algorithm>](../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | Call signature | | | | ``` template< std::random_access_iterator I, std::sentinel_for<I> S, class Comp = ranges::less, class Proj = std::identity > requires std::sortable<I, Comp, Proj> constexpr I sort_heap( I first, S last, Comp comp = {}, Proj proj = {} ); ``` | (1) | (since C++20) | | ``` template< ranges::random_access_range R, class Comp = ranges::less, class Proj = std::identity > requires std::sortable<ranges::iterator_t<R>, Comp, Proj> constexpr ranges::borrowed_iterator_t<R> sort_heap( R&& r, Comp comp = {}, Proj proj = {} ); ``` | (2) | (since C++20) | Converts the [*max heap*](https://en.wikipedia.org/wiki/Binary_heap "enwiki:Binary heap") `[first, last)` into a sorted range in ascending order. The resulting range no longer has the heap property. 1) Elements are compared using the given binary comparison function `comp` and projection object `proj`. 2) Same as (1), but uses `r` as the range, as if using `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r)` as `first` and `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r)` as `last`. The function-like entities described on this page are *niebloids*, that is: * Explicit template argument lists cannot be specified when calling any of them. * None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl"). * When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited. In practice, they may be implemented as function objects, or with special compiler extensions. ### Parameters | | | | | --- | --- | --- | | first, last | - | the range of elements to sort | | r | - | the range of elements to sort | | pred | - | predicate to apply to the projected elements | | proj | - | projection to apply to the elements | ### Return value An iterator equal to `last`. ### Complexity Given `N = [ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(first, last)`, at most \(\scriptsize 2N\log{(N)}\)2Nlog(N) comparisons and \(\scriptsize 4N\log{(N)}\)4Nlog(N) projections. ### Notes A *max heap* is a range of elements `[f, l)`, arranged with respect to comparator `comp` and projection `proj`, that has the following properties: * With `N = l-f`, `p = f[(i-1)/2]`, and `q = f[i]`, for all `0 < i < N`, the expression `[std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(comp, [std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(proj, p), [std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(proj, q))` evaluates to `false`. * A new element can be added using `[ranges::push\_heap](push_heap "cpp/algorithm/ranges/push heap")`, in \(\scriptsize \mathcal{O}(\log N)\)𝓞(log N) time. * The first element can be removed using `[ranges::pop\_heap](pop_heap "cpp/algorithm/ranges/pop heap")`, in \(\scriptsize \mathcal{O}(\log N)\)𝓞(log N) time. ### Possible implementation | | | --- | | ``` struct sort_heap_fn { template< std::random_access_iterator I, std::sentinel_for<I> S, class Comp = ranges::less, class Proj = std::identity > requires std::sortable<I, Comp, Proj> constexpr I operator()( I first, S last, Comp comp = {}, Proj proj = {} ) const { auto ret {ranges::next(first, last)}; for (; first != last; --last) { ranges::pop_heap(first, last, comp, proj); } return ret; } template< ranges::random_access_range R, class Comp = ranges::less, class Proj = std::identity > requires std::sortable<ranges::iterator_t<R>, Comp, Proj> constexpr ranges::borrowed_iterator_t<R> operator()( R&& r, Comp comp = {}, Proj proj = {} ) const { return (*this)(ranges::begin(r), ranges::end(r), std::move(comp), std::move(proj)); } }; inline constexpr sort_heap_fn sort_heap{}; ``` | ### Example ``` #include <algorithm> #include <array> #include <iostream> void print(auto const& rem, auto const& v) { std::cout << rem; for (const auto i : v) std::cout << i << ' '; std::cout << '\n'; } int main() { std::array v {3, 1, 4, 1, 5, 9}; print("original array: ", v); std::ranges::make_heap(v); print("after make_heap: ", v); std::ranges::sort_heap(v); print("after sort_heap: ", v); } ``` Output: ``` original array: 3 1 4 1 5 9 after make_heap: 9 5 4 1 1 3 after sort_heap: 1 1 3 4 5 9 ``` ### See also | | | | --- | --- | | [ranges::is\_heap](is_heap "cpp/algorithm/ranges/is heap") (C++20) | checks if the given range is a max heap (niebloid) | | [ranges::is\_heap\_until](is_heap_until "cpp/algorithm/ranges/is heap until") (C++20) | finds the largest subrange that is a max heap (niebloid) | | [ranges::make\_heap](make_heap "cpp/algorithm/ranges/make heap") (C++20) | creates a max heap out of a range of elements (niebloid) | | [ranges::pop\_heap](pop_heap "cpp/algorithm/ranges/pop heap") (C++20) | removes the largest element from a max heap (niebloid) | | [ranges::push\_heap](push_heap "cpp/algorithm/ranges/push heap") (C++20) | adds an element to a max heap (niebloid) | | [sort\_heap](../sort_heap "cpp/algorithm/sort heap") | turns a max heap into a range of elements sorted in ascending order (function template) | cpp std::ranges::is_permutation std::ranges::is\_permutation ============================ | Defined in header `[<algorithm>](../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | Call signature | | | | ``` template< std::forward_iterator I1, std::sentinel_for<I1> S1, std::forward_iterator I2, std::sentinel_for<I2> S2, class Proj1 = std::identity, class Proj2 = std::identity, std::indirect_equivalence_relation<std::projected<I1, Proj1>, std::projected<I2, Proj2>> Pred = ranges::equal_to > constexpr bool is_permutation( I1 first1, S1 last1, I2 first2, S2 last2, Pred pred = {}, Proj1 proj1 = {}, Proj2 proj2 = {} ); ``` | (1) | (since C++20) | | ``` template< ranges::forward_range R1, ranges::forward_range R2, class Proj1 = std::identity, class Proj2 = std::identity, std::indirect_equivalence_relation<std::projected<ranges::iterator_t<R1>, Proj1>, std::projected<ranges::iterator_t<R2>, Proj2>> Pred = ranges::equal_to > constexpr bool is_permutation( R1&& r1, R2&& r2, Pred pred = {}, Proj1 proj1 = {}, Proj2 proj2 = {} ); ``` | (2) | (since C++20) | 1) Returns `true` if there exists a permutation of the elements in range `[first1, last1)` that makes the range *equal* to `[first2, last2)` (after application of corresponding projections `Proj1`, `Proj2`, and using the binary predicate `Pred` as a comparator). Otherwise returns `false`. 2) Same as (1), but uses `r1` as the first source range and `r2` as the second source range, as if using `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r1)` as `first1`, `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r1)` as `last1`, `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r2)` as `first2`, and `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r2)` as `last2`. The function-like entities described on this page are *niebloids*, that is: * Explicit template argument lists cannot be specified when calling any of them. * None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl"). * When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited. In practice, they may be implemented as function objects, or with special compiler extensions. ### Parameters | | | | | --- | --- | --- | | first1, last1 | - | the first range of the elements | | first2, last2 | - | the second range of the elements | | r1 | - | the first range of the elements | | r2 | - | the second range of the elements | | pred | - | predicate to apply to the projected elements | | proj1 | - | projection to apply to the elements in the first range | | proj2 | - | projection to apply to the elements in the second range | ### Return value `true` if the range `[first1, last1)` is a permutation of the range `[first2, last2)`. ### Complexity At most \(\scriptsize \mathcal{O}(N^2)\)O(N2) applications of the predicate and each projection, or exactly \(\scriptsize N\)N if the sequences are already equal, where \(\scriptsize N\)N is `[ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(first1, last1)`. However if `[ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(first1, last1) != [ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(first2, last2)`, no applications of the predicate and projections are made. ### Notes The *permutation* relation is an [equivalence relation](https://en.wikipedia.org/wiki/equivalence_relation "enwiki:equivalence relation"). The **`ranges::is_permutation`** can be used in *testing*, namely to check the correctness of rearranging algorithms (e.g. sorting, shuffling, partitioning). If `x` is an original range and `y` is a *permuted* range then `[std::is\_permutation](http://en.cppreference.com/w/cpp/algorithm/is_permutation)(x, y) == true` means that `y` consist of *"the same"* elements, maybe staying at other positions. ### Possible implementation | | | --- | | ``` struct is_permutation_fn { template< std::forward_iterator I1, std::sentinel_for<I1> S1, std::forward_iterator I2, std::sentinel_for<I2> S2, class Proj1 = std::identity, class Proj2 = std::identity, std::indirect_equivalence_relation<std::projected<I1, Proj1>, std::projected<I2, Proj2>> Pred = ranges::equal_to > constexpr bool operator()( I1 first1, S1 last1, I2 first2, S2 last2, Pred pred = {}, Proj1 proj1 = {}, Proj2 proj2 = {} ) const { // skip common prefix auto ret = std::ranges::mismatch(first1, last1, first2, last2, std::ref(pred), std::ref(proj1), std::ref(proj2)); first1 = ret.in1, first2 = ret.in2; // iterate over the rest, counting how many times each element // from [first1, last1) appears in [first2, last2) for (auto i{ first1 }; i != last1; ++i) { const auto i_proj{ std::invoke(proj1, *i) }; auto i_cmp = [&]<typename T>(T&& t) { return std::invoke(pred, i_proj, std::forward<T>(t)); }; if (i != ranges::find_if(first1, i, i_cmp, proj1)) continue; // this *i has been checked if (const auto m{ ranges::count_if(first2, last2, i_cmp, proj2) }; m == 0 or m != ranges::count_if(i, last1, i_cmp, proj1)) return false; } return true; } template< ranges::forward_range R1, ranges::forward_range R2, class Proj1 = std::identity, class Proj2 = std::identity, std::indirect_equivalence_relation<std::projected<ranges::iterator_t<R1>, Proj1>, std::projected<ranges::iterator_t<R2>, Proj2>> Pred = ranges::equal_to > constexpr bool operator()( R1&& r1, R2&& r2, Pred pred = {}, Proj1 proj1 = {}, Proj2 proj2 = {} ) const { return (*this)(ranges::begin(r1), ranges::end(r1), ranges::begin(r2), ranges::end(r2), std::move(pred), std::move(proj1), std::move(proj2)); } }; inline constexpr is_permutation_fn is_permutation{}; ``` | ### Example ``` #include <algorithm> #include <array> #include <cmath> #include <iostream> #include <ranges> auto& operator<< (auto& os, std::ranges::forward_range auto const& v) { os << "{ "; for (auto const& e : v) os << e << ' '; return os << "}"; } int main() { static constexpr auto r1 = {1,2,3,4,5}; static constexpr auto r2 = {3,5,4,1,2}; static constexpr auto r3 = {3,5,4,1,1}; static_assert( std::ranges::is_permutation(r1, r1) && std::ranges::is_permutation(r1, r2) && std::ranges::is_permutation(r2, r1) && std::ranges::is_permutation(r1.begin(), r1.end(), r2.begin(), r2.end()) ); std::cout << std::boolalpha << "is_permutation( " << r1 << ", " << r2 << " ): " << std::ranges::is_permutation(r1, r2) << '\n' << "is_permutation( " << r1 << ", " << r3 << " ): " << std::ranges::is_permutation(r1, r3) << '\n' << "is_permutation with custom predicate and projections: " << std::ranges::is_permutation( std::array{ -14, -11, -13, -15, -12 }, // 1st range std::array{ 'F', 'E', 'C', 'B', 'D' }, // 2nd range [](int x, int y) { return abs(x) == abs(y); }, // predicate [](int x) { return x + 10; }, // projection for 1st range [](char y) { return int(y - 'A'); }) // projection for 2nd range << '\n'; } ``` Output: ``` is_permutation( { 1 2 3 4 5 }, { 3 5 4 1 2 } ): true is_permutation( { 1 2 3 4 5 }, { 3 5 4 1 1 } ): false is_permutation with custom predicate and projections: true ``` ### See also | | | | --- | --- | | [ranges::next\_permutation](next_permutation "cpp/algorithm/ranges/next permutation") (C++20) | generates the next greater lexicographic permutation of a range of elements (niebloid) | | [ranges::prev\_permutation](prev_permutation "cpp/algorithm/ranges/prev permutation") (C++20) | generates the next smaller lexicographic permutation of a range of elements (niebloid) | | [is\_permutation](../is_permutation "cpp/algorithm/is permutation") (C++11) | determines if a sequence is a permutation of another sequence (function template) | | [next\_permutation](../next_permutation "cpp/algorithm/next permutation") | generates the next greater lexicographic permutation of a range of elements (function template) | | [prev\_permutation](../prev_permutation "cpp/algorithm/prev permutation") | generates the next smaller lexicographic permutation of a range of elements (function template) | | [equivalence\_relation](../../concepts/equivalence_relation "cpp/concepts/equivalence relation") (C++20) | specifies that a [`relation`](../../concepts/relation "cpp/concepts/relation") imposes an equivalence relation (concept) | cpp std::ranges::copy, std::ranges::copy_if, std::ranges::copy_result, std::ranges::copy_if_result std::ranges::copy, std::ranges::copy\_if, std::ranges::copy\_result, std::ranges::copy\_if\_result ================================================================================================== | Defined in header `[<algorithm>](../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | Call signature | | | | ``` template< std::input_iterator I, std::sentinel_for<I> S, std::weakly_incrementable O > requires std::indirectly_copyable<I, O> constexpr copy_result<I, O> copy( I first, S last, O result ); ``` | (1) | (since C++20) | | ``` template< ranges::input_range R, std::weakly_incrementable O > requires std::indirectly_copyable<ranges::iterator_t<R>, O> constexpr copy_result<ranges::borrowed_iterator_t<R>, O> copy( R&& r, O result ); ``` | (2) | (since C++20) | | ``` template< std::input_iterator I, std::sentinel_for<I> S, std::weakly_incrementable O, class Proj = std::identity, std::indirect_unary_predicate<std::projected<I, Proj>> Pred > requires std::indirectly_copyable<I, O> constexpr copy_if_result<I, O> copy_if( I first, S last, O result, Pred pred, Proj proj = {} ); ``` | (3) | (since C++20) | | ``` template< ranges::input_range R, std::weakly_incrementable O, class Proj = std::identity, std::indirect_unary_predicate<std::projected<ranges::iterator_t<R>, Proj>> Pred > requires std::indirectly_copyable<ranges::iterator_t<R>, O> constexpr copy_if_result<ranges::borrowed_iterator_t<R>, O> copy_if( R&& r, O result, Pred pred, Proj proj = {} ); ``` | (4) | (since C++20) | | Helper types | | | | ``` template< class I, class O > using copy_result = ranges::in_out_result<I, O>; ``` | (5) | (since C++20) | | ``` template< class I, class O > using copy_if_result = ranges::in_out_result<I, O>; ``` | (6) | (since C++20) | Copies the elements in the range, defined by `[first, last)`, to another range beginning at `result`. 1) Copies all elements in the range `[first, last)` starting from first and proceeding to last - 1. The behavior is undefined if `result` is within the range `[first, last)`. In this case, `[ranges::copy\_backward](copy_backward "cpp/algorithm/ranges/copy backward")` may be used instead. 3) Only copies the elements for which the predicate `pred` returns `true`. The relative order of the elements that are copied is preserved. The behavior is undefined if the source and the destination ranges overlap. 2,4) Same as (1,3), but uses `r` as the source range, as if using `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r)` as `first` and `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r)` as `last`. The function-like entities described on this page are *niebloids*, that is: * Explicit template argument lists cannot be specified when calling any of them. * None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl"). * When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited. In practice, they may be implemented as function objects, or with special compiler extensions. ### Parameters | | | | | --- | --- | --- | | first, last | - | the range of elements to copy | | r | - | the range of elements to copy | | result | - | the beginning of the destination range. | | pred | - | predicate to apply to the projected elements | | proj | - | projection to apply to the elements | ### Return value A `[ranges::in\_out\_result](return_types/in_out_result "cpp/algorithm/ranges/return types/in out result")` containing an input iterator equal to `last` and an output iterator past the last element copied. ### Complexity 1-2) Exactly `(last - first)` assignments 3-4) Exactly `(last - first)` applications of the predicate and projection, between `​0​` and `(last - first)` assignments (assignment for every element for which predicate returns `true`, dependent on predicate and input data) ### Notes In practice, implementations of `std::ranges::copy` avoid multiple assignments and use bulk copy functions such as `[std::memmove](../../string/byte/memmove "cpp/string/byte/memmove")` if the value type is [TriviallyCopyable](../../named_req/triviallycopyable "cpp/named req/TriviallyCopyable") and the iterator types satisfy [`contiguous_iterator`](../../iterator/contiguous_iterator "cpp/iterator/contiguous iterator"). When copying overlapping ranges, `std::ranges::copy` is appropriate when copying to the left (beginning of the destination range is outside the source range) while `std::ranges::copy_backward` is appropriate when copying to the right (end of the destination range is outside the source range). ### Possible implementation | First version | | --- | | ``` struct copy_fn { template< std::input_iterator I, std::sentinel_for<I> S, std::weakly_incrementable O > requires std::indirectly_copyable<I, O> constexpr ranges::copy_result<I, O> operator()( I first, S last, O result ) const { for (; first != last; ++first, (void)++result) { *result = *first; } return {std::move(first), std::move(result)}; } template< ranges::input_range R, std::weakly_incrementable O > requires std::indirectly_copyable<ranges::iterator_t<R>, O> constexpr ranges::copy_result<ranges::borrowed_iterator_t<R>, O> operator()( R&& r, O result ) const { return (*this)(ranges::begin(r), ranges::end(r), std::move(result)); } }; inline constexpr copy_fn copy; ``` | | Second version | | ``` struct copy_if_fn { template< std::input_iterator I, std::sentinel_for<I> S, std::weakly_incrementable O, class Proj = std::identity, std::indirect_unary_predicate<std::projected<I, Proj>> Pred > requires std::indirectly_copyable<I, O> constexpr ranges::copy_if_result<I, O> operator()( I first, S last, O result, Pred pred, Proj proj = {} ) const { for (; first != last; ++first) { if (std::invoke(pred, std::invoke(proj, *first))) { *result = *first; ++result; } } return {std::move(first), std::move(result)}; } template< ranges::input_range R, std::weakly_incrementable O, class Proj = std::identity, std::indirect_unary_predicate< std::projected<ranges::iterator_t<R>, Proj>> Pred > requires std::indirectly_copyable<ranges::iterator_t<R>, O> constexpr ranges::copy_if_result<ranges::borrowed_iterator_t<R>, O> operator()( R&& r, O result, Pred pred, Proj proj = {} ) const { return (*this)(ranges::begin(r), ranges::end(r), std::move(result), std::ref(pred), std::ref(proj)); } }; inline constexpr copy_if_fn copy_if; ``` | ### Example The following code uses `copy` to both copy the contents of one `vector` to another and to display the resulting `vector`: ``` #include <algorithm> #include <iostream> #include <vector> #include <iterator> #include <numeric> int main() { std::vector<int> from_vector(10); std::iota(from_vector.begin(), from_vector.end(), 0); std::vector<int> to_vector; namespace ranges = std::ranges; ranges::copy(from_vector.begin(), from_vector.end(), std::back_inserter(to_vector)); // or, alternatively, // std::vector<int> to_vector(from_vector.size()); // ranges::copy(from_vector.begin(), from_vector.end(), to_vector.begin()); // either way is equivalent to // std::vector<int> to_vector = from_vector; std::cout << "to_vector contains: "; ranges::copy(to_vector, std::ostream_iterator<int>(std::cout, " ")); std::cout << '\n'; std::cout << "odd numbers in to_vector are: "; ranges::copy_if(to_vector, std::ostream_iterator<int>(std::cout, " "), [](int x) { return (x % 2) == 1; }); std::cout << '\n'; } ``` Output: ``` to_vector contains: 0 1 2 3 4 5 6 7 8 9 odd numbers in to_vector are: 1 3 5 7 9 ``` ### See also | | | | --- | --- | | [ranges::copy\_backward](copy_backward "cpp/algorithm/ranges/copy backward") (C++20) | copies a range of elements in backwards order (niebloid) | | [ranges::reverse\_copy](reverse_copy "cpp/algorithm/ranges/reverse copy") (C++20) | creates a copy of a range that is reversed (niebloid) | | [ranges::copy\_n](copy_n "cpp/algorithm/ranges/copy n") (C++20) | copies a number of elements to a new location (niebloid) | | [ranges::fill](fill "cpp/algorithm/ranges/fill") (C++20) | assigns a range of elements a certain value (niebloid) | | [ranges::remove\_copyranges::remove\_copy\_if](remove_copy "cpp/algorithm/ranges/remove copy") (C++20)(C++20) | copies a range of elements omitting those that satisfy specific criteria (niebloid) | | [copycopy\_if](../copy "cpp/algorithm/copy") (C++11) | copies a range of elements to a new location (function template) |
programming_docs
cpp std::ranges::max_element std::ranges::max\_element ========================= | Defined in header `[<algorithm>](../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | Call signature | | | | ``` template< std::forward_iterator I, std::sentinel_for<I> S, class Proj = std::identity, std::indirect_strict_weak_order<std::projected<I, Proj>> Comp = ranges::less > constexpr I max_element( I first, S last, Comp comp = {}, Proj proj = {} ); ``` | (1) | (since C++20) | | ``` template< ranges::forward_range R, class Proj = std::identity, std::indirect_strict_weak_order< std::projected<ranges::iterator_t<R>, Proj>> Comp = ranges::less > constexpr ranges::borrowed_iterator_t<R> max_element( R&& r, Comp comp = {}, Proj proj = {} ); ``` | (2) | (since C++20) | 1) Finds the greatest element in the range `[first, last)`. 2) Same as (1), but uses `r` as the source range, as if using `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r)` as `first` and `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r)` as `last`. The function-like entities described on this page are *niebloids*, that is: * Explicit template argument lists cannot be specified when calling any of them. * None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl"). * When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited. In practice, they may be implemented as function objects, or with special compiler extensions. ### Parameters | | | | | --- | --- | --- | | first, last | - | iterator-sentinel pair denoting the range to examine | | r | - | the range to examine | | comp | - | comparison to apply to the projected elements | | proj | - | projection to apply to the elements | ### Return value Iterator to the greatest element in the range `[first, last)`. If several elements in the range are equivalent to the greatest element, returns the iterator to the first such element. Returns `first` if the range is empty. ### Complexity Exactly max(N-1,0) comparisons, where `N = [ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(first, last)`. ### Possible implementation | | | --- | | ``` struct max_element_fn { template<std::forward_iterator I, std::sentinel_for<I> S, class Proj = std::identity, std::indirect_strict_weak_order<std::projected<I, Proj>> Comp = ranges::less> constexpr I operator()(I first, S last, Comp comp = {}, Proj proj = {}) const { if (first == last) { return last; } auto largest = first; ++first; for (; first != last; ++first) { if (std::invoke(comp, std::invoke(proj, *largest), std::invoke(proj, *first))) { largest = first; } } return largest; } template<ranges::forward_range R, class Proj = std::identity, std::indirect_strict_weak_order< std::projected<ranges::iterator_t<R>, Proj>> Comp = ranges::less> constexpr ranges::borrowed_iterator_t<R> operator()(R&& r, Comp comp = {}, Proj proj = {}) const { return (*this)(ranges::begin(r), ranges::end(r), std::ref(comp), std::ref(proj)); } }; inline constexpr max_element_fn max_element; ``` | ### Example ``` #include <algorithm> #include <iostream> #include <vector> #include <cmath> int main() { std::vector<int> v{ 3, 1, -14, 1, 5, 9 }; namespace ranges = std::ranges; auto result = ranges::max_element(v.begin(), v.end()); std::cout << "max element at: " << ranges::distance(v.begin(), result) << '\n'; auto abs_compare = [](int a, int b) { return (std::abs(a) < std::abs(b)); }; result = ranges::max_element(v, abs_compare); std::cout << "max element (absolute) at: " << ranges::distance(v.begin(), result) << '\n'; } ``` Output: ``` max element at: 5 max element (absolute) at: 2 ``` ### See also | | | | --- | --- | | [ranges::min\_element](min_element "cpp/algorithm/ranges/min element") (C++20) | returns the smallest element in a range (niebloid) | | [ranges::minmax\_element](minmax_element "cpp/algorithm/ranges/minmax element") (C++20) | returns the smallest and the largest elements in a range (niebloid) | | [ranges::max](max "cpp/algorithm/ranges/max") (C++20) | returns the greater of the given values (niebloid) | | [max\_element](../max_element "cpp/algorithm/max element") | returns the largest element in a range (function template) | cpp std::ranges::find_first_of std::ranges::find\_first\_of ============================ | Defined in header `[<algorithm>](../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | Call signature | | | | ``` template< std::input_iterator I1, std::sentinel_for<I1> S1, std::forward_iterator I2, std::sentinel_for<I2> S2, class Pred = ranges::equal_to, class Proj1 = std::identity, class Proj2 = std::identity > requires std::indirectly_comparable<I1, I2, Pred, Proj1, Proj2> constexpr I1 find_first_of( I1 first1, S1 last1, I2 first2, S2 last2, Pred pred = {}, Proj1 proj1 = {}, Proj2 proj2 = {} ); ``` | (1) | (since C++20) | | ``` template< ranges::input_range R1, ranges::forward_range R2, class Pred = ranges::equal_to, class Proj1 = std::identity, class Proj2 = std::identity > requires std::indirectly_comparable<ranges::iterator_t<R1>, ranges::iterator_t<R2>, Pred, Proj1, Proj2> constexpr ranges::borrowed_iterator_t<R1> find_first_of( R1&& r1, R2&& r2, Pred pred = {}, Proj1 proj1 = {}, Proj2 proj2 = {} ); ``` | (2) | (since C++20) | 1) Searches the range `[first1, last1)` for *any* of the elements in the range `[first2, last2)`, after projecting the ranges with `proj1` and `proj2` respectively. The projected elements are compared using the binary predicate `pred`. 2) Same as (1), but uses `r1` as the first source range and `r2` as the second source range, as if using `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r1)` as `first1`, `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r1)` as `last1`, `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r2)` as `first2`, and `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r2)` as `last2`. The function-like entities described on this page are *niebloids*, that is: * Explicit template argument lists cannot be specified when calling any of them. * None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl"). * When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited. In practice, they may be implemented as function objects, or with special compiler extensions. ### Parameters | | | | | --- | --- | --- | | first1, last1 | - | the range of elements to examine (aka *haystack*) | | first2, last2 | - | the range of elements to search for (aka *needles*) | | r1 | - | the range of elements to examine (aka *haystack*) | | r2 | - | the range of elements to search for (aka *needles*) | | pred | - | binary predicate to compare the elements | | proj1 | - | projection to apply to the elements in the first range | | proj2 | - | projection to apply to the elements in the second range | ### Return value Iterator to the first element in the range `[first1, last1)` that is equal to an element from the range `[first2, last2)` after projection. If no such element is found, an iterator comparing equal to `last1` is returned. ### Complexity At most `(S*N)` applications of the predicate and each projection, where (1) `S = [ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(first2, last2)` and `N = [ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(first1, last1)`; (2) `S = [ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(r2)` and `N = [ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(r1)`. ### Possible implementation | | | --- | | ``` struct find_first_of_fn { template<std::input_iterator I1, std::sentinel_for<I1> S1, std::forward_iterator I2, std::sentinel_for<I2> S2, class Pred = ranges::equal_to, class Proj1 = std::identity, class Proj2 = std::identity> requires std::indirectly_comparable<I1, I2, Pred, Proj1, Proj2> constexpr I1 operator()(I1 first1, S1 last1, I2 first2, S2 last2, Pred pred = {}, Proj1 proj1 = {}, Proj2 proj2 = {}) const { for (; first1 != last1; ++first1) for (auto i = first2; i != last2; ++i) if (std::invoke(pred, std::invoke(proj1, *first1), std::invoke(proj2, *i))) return first1; return first1; } template<ranges::input_range R1, ranges::forward_range R2, class Pred = ranges::equal_to, class Proj1 = std::identity, class Proj2 = std::identity> requires std::indirectly_comparable<ranges::iterator_t<R1>, ranges::iterator_t<R2>, Pred, Proj1, Proj2> constexpr ranges::borrowed_iterator_t<R1> operator()(R1&& r1, R2&& r2, Pred pred = {}, Proj1 proj1 = {}, Proj2 proj2 = {}) const { return (*this)(ranges::begin(r1), ranges::end(r1), ranges::begin(r2), ranges::end(r2), std::move(pred), std::move(proj1), std::move(proj2)); } }; inline constexpr find_first_of_fn find_first_of{}; ``` | ### Example ``` #include <algorithm> #include <iostream> #include <iterator> int main() { namespace rng = std::ranges; constexpr static auto haystack = {1, 2, 3, 4}; constexpr static auto needles = {0, 3, 4, 3}; constexpr auto found1 = rng::find_first_of(haystack.begin(), haystack.end(), needles.begin(), needles.end()); static_assert(std::distance(haystack.begin(), found1) == 2); constexpr auto found2 = rng::find_first_of(haystack, needles); static_assert(std::distance(haystack.begin(), found2) == 2); constexpr static auto negatives = {-6, -3, -4, -3}; constexpr auto not_found = rng::find_first_of(haystack, negatives); static_assert(not_found == haystack.end()); constexpr auto found3 = rng::find_first_of(haystack, negatives, [](int x, int y) { return x == -y; }); // uses a binary comparator static_assert(std::distance(haystack.begin(), found3) == 2); struct P { int x, y; }; constexpr static auto p1 = { P{1, -1}, P{2, -2}, P{3, -3}, P{4, -4} }; constexpr static auto p2 = { P{5, -5}, P{6, -3}, P{7, -5}, P{8, -3} }; // Compare only P::y data members by projecting them: const auto found4 = rng::find_first_of(p1, p2, {}, &P::y, &P::y); std::cout << "First equivalent element {" << found4->x << ", " << found4->y << "} was found at position " << std::distance(p1.begin(), found4) << ".\n"; } ``` Output: ``` First equavalent element {3, -3} was found at position 2. ``` ### See also | | | | --- | --- | | [find\_first\_of](../find_first_of "cpp/algorithm/find first of") | searches for any one of a set of elements (function template) | | [ranges::adjacent\_find](adjacent_find "cpp/algorithm/ranges/adjacent find") (C++20) | finds the first two adjacent items that are equal (or satisfy a given predicate) (niebloid) | | [ranges::findranges::find\_ifranges::find\_if\_not](find "cpp/algorithm/ranges/find") (C++20)(C++20)(C++20) | finds the first element satisfying specific criteria (niebloid) | | [ranges::find\_end](find_end "cpp/algorithm/ranges/find end") (C++20) | finds the last sequence of elements in a certain range (niebloid) | | [ranges::search](search "cpp/algorithm/ranges/search") (C++20) | searches for a range of elements (niebloid) | | [ranges::search\_n](search_n "cpp/algorithm/ranges/search n") (C++20) | searches for a number consecutive copies of an element in a range (niebloid) | cpp std::ranges::min_element std::ranges::min\_element ========================= | Defined in header `[<algorithm>](../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | Call signature | | | | ``` template< std::forward_iterator I, std::sentinel_for<I> S, class Proj = std::identity, std::indirect_strict_weak_order<std::projected<I, Proj>> Comp = ranges::less > constexpr I min_element( I first, S last, Comp comp = {}, Proj proj = {} ); ``` | (1) | (since C++20) | | ``` template< ranges::forward_range R, class Proj = std::identity, std::indirect_strict_weak_order< std::projected<ranges::iterator_t<R>, Proj>> Comp = ranges::less > constexpr ranges::borrowed_iterator_t<R> min_element( R&& r, Comp comp = {}, Proj proj = {} ); ``` | (2) | (since C++20) | 1) Finds the smallest element in the range `[first, last)`. 2) Same as (1), but uses `r` as the source range, as if using `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r)` as `first` and `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r)` as `last`. The function-like entities described on this page are *niebloids*, that is: * Explicit template argument lists cannot be specified when calling any of them. * None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl"). * When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited. In practice, they may be implemented as function objects, or with special compiler extensions. ### Parameters | | | | | --- | --- | --- | | first, last | - | iterator-sentinel pair denoting the range to examine | | r | - | the range to examine | | comp | - | comparison to apply to the projected elements | | proj | - | projection to apply to the elements | ### Return value Iterator to the smallest element in the range `[first, last)`. If several elements in the range are equivalent to the smallest element, returns the iterator to the first such element. Returns `first` if the range is empty. ### Complexity Exactly max(N-1,0) comparisons, where `N = [ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(first, last)`. ### Possible implementation | | | --- | | ``` struct min_element_fn { template<std::forward_iterator I, std::sentinel_for<I> S, class Proj = std::identity, std::indirect_strict_weak_order<std::projected<I, Proj>> Comp = ranges::less> constexpr I operator()(I first, S last, Comp comp = {}, Proj proj = {}) const { if (first == last) { return last; } auto smallest = first; ++first; for (; first != last; ++first) { if (!std::invoke(comp, std::invoke(proj, *smallest), std::invoke(proj, *first))) { smallest = first; } } return smallest; } template<ranges::forward_range R, class Proj = std::identity, std::indirect_strict_weak_order< std::projected<ranges::iterator_t<R>, Proj>> Comp = ranges::less> constexpr ranges::borrowed_iterator_t<R> operator()(R&& r, Comp comp = {}, Proj proj = {}) const { return (*this)(ranges::begin(r), ranges::end(r), std::ref(comp), std::ref(proj)); } }; inline constexpr min_element_fn min_element; ``` | ### Example ``` #include <algorithm> #include <iostream> #include <vector> #include <cmath> int main() { std::vector<int> v{ 3, 1, -14, 1, 5, 9 }; namespace ranges = std::ranges; auto result = ranges::min_element(v.begin(), v.end()); std::cout << "min element at: " << ranges::distance(v.begin(), result) << '\n'; auto abs_compare = [](int a, int b) { return (std::abs(a) < std::abs(b)); }; result = ranges::min_element(v, abs_compare); std::cout << "min element (absolute) at: " << ranges::distance(v.begin(), result) << '\n'; } ``` Output: ``` min element at: 2 min element (absolute) at: 1 ``` ### See also | | | | --- | --- | | [ranges::max\_element](max_element "cpp/algorithm/ranges/max element") (C++20) | returns the largest element in a range (niebloid) | | [ranges::minmax\_element](minmax_element "cpp/algorithm/ranges/minmax element") (C++20) | returns the smallest and the largest elements in a range (niebloid) | | [ranges::max](max "cpp/algorithm/ranges/max") (C++20) | returns the greater of the given values (niebloid) | | [min\_element](../min_element "cpp/algorithm/min element") | returns the smallest element in a range (function template) | cpp std::ranges::is_sorted_until std::ranges::is\_sorted\_until ============================== | Defined in header `[<algorithm>](../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | Call signature | | | | ``` template< std::forward_iterator I, std::sentinel_for<I> S, class Proj = std::identity, std::indirect_strict_weak_order<std::projected<I, Proj>> Comp = ranges::less > constexpr I is_sorted_until( I first, S last, Comp comp = {}, Proj proj = {} ); ``` | (1) | (since C++20) | | ``` template< std::forward_range R, class Proj = std::identity, std::indirect_strict_weak_order< std::projected<ranges::iterator_t<R>, Proj>> Comp = ranges::less > constexpr ranges::borrowed_iterator_t<R> is_sorted_until( R&& r, Comp comp = {}, Proj proj = {} ); ``` | (2) | (since C++20) | Examines the range `[first, last)` and finds the largest range beginning at `first` in which the elements are sorted in non-descending order. A sequence is sorted with respect to a comparator `comp` if for any iterator `it` pointing to the sequence and any non-negative integer `n` such that `it + n` is a valid iterator pointing to an element of the sequence, `[std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(comp, [std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(proj, \*(it + n)), [std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(proj, \*it))` evaluates to `false`. 1) Elements are compared using the given binary comparison function `comp`. 2) Same as (1), but uses `r` as the source range, as if using `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r)` as `first` and `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r)` as `last`. The function-like entities described on this page are *niebloids*, that is: * Explicit template argument lists cannot be specified when calling any of them. * None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl"). * When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited. In practice, they may be implemented as function objects, or with special compiler extensions. ### Parameters | | | | | --- | --- | --- | | first, last | - | iterator-sentinel defining the range to find its sorted upper bound | | r | - | the range to find its sorted upper bound | | comp | - | comparison function to apply to the projected elements | | proj | - | projection to apply to the elements | ### Return value The upper bound of the largest range beginning at `first` in which the elements are sorted in non-descending order. That is, the last iterator `it` for which range `[first, it)` is sorted. ### Complexity Linear in the distance between `first` and `last`. ### Possible implementation | | | --- | | ``` struct is_sorted_until_fn { template<std::forward_iterator I, std::sentinel_for<I> S, class Proj = std::identity, std::indirect_strict_weak_order<std::projected<I, Proj>> Comp = ranges::less> constexpr I operator()(I first, S last, Comp comp = {}, Proj proj = {}) const { if (first == last) { return first; } auto next = first; while (++next != last) { if (std::invoke(comp, std::invoke(proj, *next), std::invoke(proj, *first))) { return next; } first = next; } return first; } template< ranges::forward_range R, class Proj = std::identity, std::indirect_strict_weak_order< std::projected<ranges::iterator_t<R>, Proj>> Comp = ranges::less > constexpr ranges::borrowed_iterator_t<R> operator()( R&& r, Comp comp = {}, Proj proj = {} ) const { return (*this)(ranges::begin(r), ranges::end(r), std::ref(comp), std::ref(proj)); } }; inline constexpr is_sorted_until_fn is_sorted_until; ``` | ### Notes `ranges::is_sorted_until` returns an iterator equal to `last` for empty ranges and ranges of length one. ### Example ``` #include <algorithm> #include <iostream> #include <iterator> #include <random> int main() { std::random_device rd; std::mt19937 g{rd()}; std::array nums {3, 1, 4, 1, 5, 9}; constexpr int min_sorted_size = 4; int sorted_size = 0; do { std::ranges::shuffle(nums, g); const auto sorted_end = std::ranges::is_sorted_until(nums); sorted_size = std::ranges::distance(nums.begin(), sorted_end); std::ranges::copy(nums, std::ostream_iterator<int>(std::cout, " ")); std::cout << " : " << sorted_size << " leading sorted element(s)\n"; } while (sorted_size < min_sorted_size); } ``` Possible output: ``` 4 1 9 5 1 3 : 1 leading sorted element(s) 4 5 9 3 1 1 : 3 leading sorted element(s) 9 3 1 4 5 1 : 1 leading sorted element(s) 1 3 5 4 1 9 : 3 leading sorted element(s) 5 9 1 1 3 4 : 2 leading sorted element(s) 4 9 1 5 1 3 : 2 leading sorted element(s) 1 1 4 9 5 3 : 4 leading sorted element(s) ``` ### See also | | | | --- | --- | | [ranges::is\_sorted](is_sorted "cpp/algorithm/ranges/is sorted") (C++20) | checks whether a range is sorted into ascending order (niebloid) | | [is\_sorted\_until](../is_sorted_until "cpp/algorithm/is sorted until") (C++11) | finds the largest sorted subrange (function template) |
programming_docs
cpp std::ranges::upper_bound std::ranges::upper\_bound ========================= | Defined in header `[<algorithm>](../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | Call signature | | | | ``` template< std::forward_iterator I, std::sentinel_for<I> S, class T, class Proj = std::identity, std::indirect_strict_weak_order< const T*, std::projected<I, Proj>> Comp = ranges::less > constexpr I upper_bound( I first, S last, const T& value, Comp comp = {}, Proj proj = {} ); ``` | (1) | (since C++20) | | ``` template< ranges::forward_range R, class T, class Proj = std::identity, std::indirect_strict_weak_order< const T*, std::projected<ranges::iterator_t<R>, Proj>> Comp = ranges::less > constexpr ranges::borrowed_iterator_t<R> upper_bound( R&& r, const T& value, Comp comp = {}, Proj proj = {} ); ``` | (2) | (since C++20) | 1) Returns an iterator pointing to the first element in the range `[first, last)` that is *greater* than `value`, or `last` if no such element is found. The range `[first, last)` must be partitioned with respect to the expression or `!comp(value, element)`, i.e., all elements for which the expression is `true` must precede all elements for which the expression is `false`. A fully-sorted range meets this criterion. 2) Same as (1), but uses `r` as the source range, as if using `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r)` as `first` and `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r)` as `last`. The function-like entities described on this page are *niebloids*, that is: * Explicit template argument lists cannot be specified when calling any of them. * None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl"). * When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited. In practice, they may be implemented as function objects, or with special compiler extensions. ### Parameters | | | | | --- | --- | --- | | first, last | - | iterator-sentinel defining the partially-ordered range to examine | | r | - | the partially-ordered range to examine | | value | - | value to compare the elements to | | pred | - | predicate to apply to the projected elements | | proj | - | projection to apply to the elements | ### Return value Iterator pointing to the first element that is *greater* than `value`, or `last` if no such element is found. ### Complexity The number of comparisons and applications of the projection performed are logarithmic in the distance between `first` and `last` (At most log 2(last - first) + O(1) comparisons and applications of the projection). However, for an iterator that does not model [`random_access_iterator`](../../iterator/random_access_iterator "cpp/iterator/random access iterator"), the number of iterator increments is linear. ### Possible implementation | | | --- | | ``` struct upper_bound_fn { template<std::forward_iterator I, std::sentinel_for<I> S, class T, class Proj = std::identity, std::indirect_strict_weak_order< const T*, std::projected<I, Proj>> Comp = ranges::less> constexpr I operator()( I first, S last, const T& value, Comp comp = {}, Proj proj = {} ) const { I it; std::iter_difference_t<I> count, step; count = ranges::distance(first, last); while (count > 0) { it = first; step = count / 2; ranges::advance(it, step, last); if (!comp(value, std::invoke(proj, *it))) { first = ++it; count -= step + 1; } else { count = step; } } return first; } template<ranges::forward_range R, class T, class Proj = std::identity, std::indirect_strict_weak_order< const T*, std::projected<ranges::iterator_t<R>, Proj>> Comp = ranges::less> constexpr ranges::borrowed_iterator_t<R> operator()( R&& r, const T& value, Comp comp = {}, Proj proj = {} ) const { return (*this)(ranges::begin(r), ranges::end(r), value, std::ref(comp), std::ref(proj)); } }; inline constexpr upper_bound_fn upper_bound; ``` | ### Example ``` #include <algorithm> #include <iostream> #include <iterator> #include <vector> int main() { namespace ranges = std::ranges; std::vector<int> data = { 1, 1, 2, 3, 3, 3, 3, 4, 4, 4, 5, 5, 6 }; { auto lower = ranges::lower_bound(data.begin(), data.end(), 4); auto upper = ranges::upper_bound(data.begin(), data.end(), 4); ranges::copy(lower, upper, std::ostream_iterator<int>(std::cout, " ")); std::cout << '\n'; } { auto lower = ranges::lower_bound(data, 3); auto upper = ranges::upper_bound(data, 3); ranges::copy(lower, upper, std::ostream_iterator<int>(std::cout, " ")); std::cout << '\n'; } } ``` Output: ``` 4 4 4 3 3 3 3 ``` ### See also | | | | --- | --- | | [ranges::equal\_range](equal_range "cpp/algorithm/ranges/equal range") (C++20) | returns range of elements matching a specific key (niebloid) | | [ranges::lower\_bound](lower_bound "cpp/algorithm/ranges/lower bound") (C++20) | returns an iterator to the first element *not less* than the given value (niebloid) | | [ranges::partition](partition "cpp/algorithm/ranges/partition") (C++20) | divides a range of elements into two groups (niebloid) | | [upper\_bound](../upper_bound "cpp/algorithm/upper bound") | returns an iterator to the first element *greater* than a certain value (function template) | cpp std::ranges::stable_sort std::ranges::stable\_sort ========================= | Defined in header `[<algorithm>](../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | Call signature | | | | ``` template< std::random_access_iterator I, std::sentinel_for<I> S, class Comp = ranges::less, class Proj = std::identity > requires std::sortable<I, Comp, Proj> I stable_sort( I first, S last, Comp comp = {}, Proj proj = {} ); ``` | (1) | (since C++20) | | ``` template< ranges::random_access_range R, class Comp = ranges::less, class Proj = std::identity > requires std::sortable<ranges::iterator_t<R>, Comp, Proj> ranges::borrowed_iterator_t<R> stable_sort( R&& r, Comp comp = {}, Proj proj = {} ); ``` | (2) | (since C++20) | Sorts the elements in the range `[first, last)` in non-descending order. The order of equivalent elements is *stable*, i.e. guaranteed to be preserved. A sequence is sorted with respect to a comparator `comp` if for any iterator `it` pointing to the sequence and any non-negative integer `n` such that `it + n` is a valid iterator pointing to an element of the sequence, `[std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(comp, [std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(proj, \*(it + n)), [std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(proj, \*it)` evaluates to `false`. 1) Elements are compared using the given binary comparison function `comp`. 2) Same as (1), but uses `r` as the range, as if using `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r)` as `first` and `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r)` as `last`. The function-like entities described on this page are *niebloids*, that is: * Explicit template argument lists cannot be specified when calling any of them. * None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl"). * When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited. In practice, they may be implemented as function objects, or with special compiler extensions. ### Parameters | | | | | --- | --- | --- | | first, last | - | iterator-sentinel defining the range to sort | | r | - | the range to sort | | comp | - | comparison to apply to the projected elements | | proj | - | projection to apply to the elements | ### Return value An iterator equal to `last`. ### Complexity \(\scriptsize N\cdot\log{(N)}\)N·log(N) comparisons, if extra memory is available; where \(\scriptsize N\)N is `[ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(first, last)`. \(\scriptsize N\cdot\log^2{(N)}\)N·log²(N) comparisons otherwise. Twice as many projections as the number of comparisons in both cases. ### Possible implementation This implementation only shows the slower algorithm used when no additional memory is available. See also implementation in [MSVC STL](https://github.com/microsoft/STL/blob/e745bad3b1d05b5b19ec652d68abb37865ffa454/stl/inc/algorithm#L7842-L8094) and [libstdc++](https://github.com/gcc-mirror/gcc/blob/54258e22b0846aaa6bd3265f592feb161eecda75/libstdc%2B%2B-v3/include/bits/ranges_algo.h#L1836-L1862). | | | --- | | ``` struct stable_sort_fn { template< std::random_access_iterator I, std::sentinel_for<I> S, class Comp = ranges::less, class Proj = std::identity > requires std::sortable<I, Comp, Proj> I operator()( I first, S last, Comp comp = {}, Proj proj = {} ) const { auto count = ranges::distance(first, last); auto mid = first + count / 2; auto last_it = first + count; if (count <= 1) return last_it; (*this)(first, mid, std::ref(comp), std::ref(proj)); (*this)(mid, last_it, std::ref(comp), std::ref(proj)); ranges::inplace_merge(first, mid, last_it); return last_it; } template< ranges::random_access_range R, class Comp = ranges::less, class Proj = std::identity > requires std::sortable<ranges::iterator_t<R>, Comp, Proj> ranges::borrowed_iterator_t<R> operator()( R&& r, Comp comp = {}, Proj proj = {} ) const { return (*this)(ranges::begin(r), ranges::end(r), std::move(comp), std::move(proj)); } }; inline constexpr stable_sort_fn stable_sort{}; ``` | ### Example ``` #include <algorithm> #include <array> #include <functional> #include <iomanip> #include <iostream> void print(auto const& seq) { for (auto const& elem : seq) std::cout << elem << ' '; std::cout << '\n'; } struct Particle { std::string name; double mass; // MeV friend std::ostream& operator<< (std::ostream& os, Particle const& p) { return os << "\n" << std::left << std::setw(8) << p.name << " : " << p.mass; } }; int main() { std::array s {5, 7, 4, 2, 8, 6, 1, 9, 0, 3}; // sort using the default operator< std::ranges::stable_sort(s); print(s); // sort using a standard library compare function object std::ranges::stable_sort(s, std::ranges::greater()); print(s); // sort using a custom function object struct { bool operator()(int a, int b) const { return a < b; } } customLess; std::ranges::stable_sort(s.begin(), s.end(), customLess); print(s); // sort using a lambda expression std::ranges::stable_sort(s, [](int a, int b) { return a > b; }); print(s); // sort with projection Particle particles[] { {"Electron", 0.511}, {"Muon", 105.66}, {"Tau", 1776.86}, {"Positron", 0.511}, {"Proton", 938.27}, {"Neutron", 939.57}, }; print(particles); std::ranges::stable_sort(particles, {}, &Particle::name); //< sort by name print(particles); std::ranges::stable_sort(particles, {}, &Particle::mass); //< sort by mass print(particles); } ``` Output: ``` 0 1 2 3 4 5 6 7 8 9 9 8 7 6 5 4 3 2 1 0 0 1 2 3 4 5 6 7 8 9 9 8 7 6 5 4 3 2 1 0 Electron : 0.511 Muon : 105.66 Tau : 1776.86 Positron : 0.511 Proton : 938.27 Neutron : 939.57 Electron : 0.511 Muon : 105.66 Neutron : 939.57 Positron : 0.511 Proton : 938.27 Tau : 1776.86 Electron : 0.511 Positron : 0.511 Muon : 105.66 Proton : 938.27 Neutron : 939.57 Tau : 1776.86 ``` ### See also | | | | --- | --- | | [ranges::sort](sort "cpp/algorithm/ranges/sort") (C++20) | sorts a range into ascending order (niebloid) | | [ranges::partial\_sort](partial_sort "cpp/algorithm/ranges/partial sort") (C++20) | sorts the first N elements of a range (niebloid) | | [ranges::stable\_partition](stable_partition "cpp/algorithm/ranges/stable partition") (C++20) | divides elements into two groups while preserving their relative order (niebloid) | | [stable\_sort](../stable_sort "cpp/algorithm/stable sort") | sorts a range of elements while preserving order between equal elements (function template) | cpp std::ranges::move, std::ranges::move_result std::ranges::move, std::ranges::move\_result ============================================ | Defined in header `[<algorithm>](../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | Call signature | | | | ``` template< std::input_iterator I, std::sentinel_for<I> S, std::weakly_incrementable O > requires std::indirectly_movable<I, O> constexpr move_result<I, O> move( I first, S last, O result ); ``` | (1) | (since C++20) | | ``` template< ranges::input_range R, std::weakly_incrementable O > requires std::indirectly_movable<ranges::iterator_t<R>, O> constexpr move_result<ranges::borrowed_iterator_t<R>, O> move( R&& r, O result ); ``` | (2) | (since C++20) | | Helper types | | | | ``` template< class I, class O > using move_result = ranges::in_out_result<I, O>; ``` | (3) | (since C++20) | 1) Moves the elements in the range, defined by `[first, last)`, to another range beginning at `result`. The behavior is undefined if `result` is within the range `[first, last)`. In such a case, `[ranges::move\_backward](move_backward "cpp/algorithm/ranges/move backward")` may be used instead. 2) Same as (1), but uses `r` as the source range, as if using `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r)` as `first`, and `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r)` as `last`. The elements in the *moved-from* range will still contain valid values of the appropriate type, but not necessarily the same values as before the move. The function-like entities described on this page are *niebloids*, that is: * Explicit template argument lists cannot be specified when calling any of them. * None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl"). * When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited. In practice, they may be implemented as function objects, or with special compiler extensions. ### Parameters | | | | | --- | --- | --- | | first | - | the beginning of the range of elements to move | | last | - | the end of the range of elements to move | | r | - | the range of the elements to move | | result | - | the beginning of the destination range | ### Return value `{last, result + N}`, where. 1) `N = [ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(first, last)`. 2) `N = [ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(r)`. ### Complexity Exactly `N` move assignments. ### Notes When moving overlapping ranges, `ranges::move` is appropriate when moving to the left (beginning of the destination range is outside the source range) while `[ranges::move\_backward](move_backward "cpp/algorithm/ranges/move backward")` is appropriate when moving to the right (end of the destination range is outside the source range). ### Possible implementation | | | --- | | ``` struct move_fn { template<std::input_iterator I, std::sentinel_for<I> S, std::weakly_incrementable O> requires std::indirectly_movable<I, O> constexpr ranges::move_result<I, O> operator()( I first, S last, O result ) const { for (; first != last; ++first, ++result) *result = ranges::iter_move(first); return {std::move(first), std::move(result)}; } template<ranges::input_range R, std::weakly_incrementable O> requires std::indirectly_movable<ranges::iterator_t<R>, O> constexpr ranges::move_result<ranges::borrowed_iterator_t<R>, O> operator()( R&& r, O result ) const { return (*this)(ranges::begin(r), ranges::end(r), std::move(result)); } }; inline constexpr move_fn move{}; ``` | ### Example The following code moves thread objects (which themselves are *non copyable*) from one container to another. ``` #include <algorithm> #include <iostream> #include <vector> #include <list> #include <iterator> #include <thread> #include <chrono> using namespace std::literals::chrono_literals; void f(std::chrono::milliseconds n) { std::this_thread::sleep_for(n); std::cout << "thread with n=" << n.count() << "ms ended" << std::endl; } int main() { std::vector<std::jthread> v; v.emplace_back(f, 400ms); v.emplace_back(f, 600ms); v.emplace_back(f, 800ms); std::list<std::jthread> l; // std::ranges::copy() would not compile, because std::jthread is non-copyable std::ranges::move(v, std::back_inserter(l)); } ``` Output: ``` thread with n=400ms ended thread with n=600ms ended thread with n=800ms ended ``` ### See also | | | | --- | --- | | [ranges::move\_backward](move_backward "cpp/algorithm/ranges/move backward") (C++20) | moves a range of elements to a new location in backwards order (niebloid) | | [ranges::copyranges::copy\_if](copy "cpp/algorithm/ranges/copy") (C++20)(C++20) | copies a range of elements to a new location (niebloid) | | [ranges::copy\_backward](copy_backward "cpp/algorithm/ranges/copy backward") (C++20) | copies a range of elements in backwards order (niebloid) | | [move](../move "cpp/algorithm/move") (C++11) | moves a range of elements to a new location (function template) | | [move](../../utility/move "cpp/utility/move") (C++11) | obtains an rvalue reference (function template) | cpp std::ranges::find_last, std::ranges::find_last_if, std::ranges::find_last_if_not std::ranges::find\_last, std::ranges::find\_last\_if, std::ranges::find\_last\_if\_not ====================================================================================== | Defined in header `[<algorithm>](../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | Call signature | | | | ``` template< std::forward_iterator I, std::sentinel_for<I> S, class T, class Proj = std::identity > requires std::indirect_binary_predicate<ranges::equal_to, std::projected<I, Proj>, const T*> constexpr ranges::subrange<I> find_last( I first, S last, const T& value, Proj proj = {} ); ``` | (1) | (since C++23) | | ``` template< ranges::forward_range R, class T, class Proj = std::identity > requires std::indirect_binary_predicate<ranges::equal_to, std::projected<ranges::iterator_t<R>, Proj>, const T*> constexpr ranges::borrowed_subrange_t<R> find_last( R&& r, const T& value, Proj proj = {} ); ``` | (2) | (since C++23) | | ``` template< std::forward_iterator I, std::sentinel_for<I> S, class Proj = std::identity, std::indirect_unary_predicate<std::projected<I, Proj>> Pred > constexpr ranges::subrange<I> find_last_if( I first, S last, Pred pred, Proj proj = {} ); ``` | (3) | (since C++23) | | ``` template< ranges::forward_range R, class Proj = std::identity, std::indirect_unary_predicate<std::projected<ranges::iterator_t<R>, Proj>> Pred > constexpr ranges::borrowed_subrange_t<R> find_last_if( R&& r, Pred pred, Proj proj = {} ); ``` | (4) | (since C++23) | | ``` template< std::forward_iterator I, std::sentinel_for<I> S, class Proj = std::identity, std::indirect_unary_predicate<std::projected<I, Proj>> Pred > constexpr ranges::subrange<I> find_last_if_not( I first, S last, Pred pred, Proj proj = {} ); ``` | (5) | (since C++23) | | ``` template< ranges::forward_range R, class Proj = std::identity, std::indirect_unary_predicate<std::projected<ranges::iterator_t<R>, Proj>> Pred > constexpr ranges::borrowed_subrange_t<R> find_last_if_not( R&& r, Pred pred, Proj proj = {} ); ``` | (6) | (since C++23) | Returns the last element in the range `[first, last)` that satisfies specific criteria: 1) `find_last` searches for an element equal to `value` 3) `find_last_if` searches for the last element in the range `[first, last)` for which predicate `pred` returns `true` 5) `find_last_if_not` searches for the last element in the range `[first, last)` for which predicate `pred` returns `false` 2,4,6) Same as (1,3,5), but uses `r` as the source range, as if using `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r)` as `first` and `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r)` as `last`. The function-like entities described on this page are *niebloids*, that is: * Explicit template argument lists cannot be specified when calling any of them. * None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl"). * When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited. In practice, they may be implemented as function objects, or with special compiler extensions. ### Parameters | | | | | --- | --- | --- | | first, last | - | the range of elements to examine | | r | - | the range of the elements to examine | | value | - | value to compare the elements to | | pred | - | predicate to apply to the projected elements | | proj | - | projection to apply to the elements | ### Return value 1,2,3) Let `i` be the last iterator in the range `[first,last)` for which `E` is `true`. Returns `[ranges::subrange](http://en.cppreference.com/w/cpp/ranges/subrange)<I>{i, last}`, or `[ranges::subrange](http://en.cppreference.com/w/cpp/ranges/subrange)<I>{last, last}` if no such iterator is found. 2,4,6) Same as (1,2,3) but the return type is `[ranges::borrowed\_subrange\_t](http://en.cppreference.com/w/cpp/ranges/borrowed_iterator_t)<I>`. ### Complexity At most `last` - `first` applications of the predicate and projection. ### Example ### See also | | | | --- | --- | | [ranges::find\_end](find_end "cpp/algorithm/ranges/find end") (C++20) | finds the last sequence of elements in a certain range (niebloid) | | [ranges::findranges::find\_ifranges::find\_if\_not](find "cpp/algorithm/ranges/find") (C++20)(C++20)(C++20) | finds the first element satisfying specific criteria (niebloid) | | [ranges::search](search "cpp/algorithm/ranges/search") (C++20) | searches for a range of elements (niebloid) | | [ranges::binary\_search](binary_search "cpp/algorithm/ranges/binary search") (C++20) | determines if an element exists in a partially-ordered range (niebloid) | | [ranges::containsranges::contains\_subrange](contains "cpp/algorithm/ranges/contains") (C++23)(C++23) | checks if the range contains the given element or subrange (niebloid) |
programming_docs
cpp std::ranges::equal std::ranges::equal ================== | Defined in header `[<algorithm>](../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | Call signature | | | | ``` template< std::input_iterator I1, std::sentinel_for<I1> S1, std::input_iterator I2, std::sentinel_for<I2> S2, class Pred = ranges::equal_to, class Proj1 = std::identity, class Proj2 = std::identity > requires std::indirectly_comparable<I1, I2, Pred, Proj1, Proj2> constexpr bool equal( I1 first1, S1 last1, I2 first2, S2 last2, Pred pred = {}, Proj1 proj1 = {}, Proj2 proj2 = {} ); ``` | (1) | (since C++20) | | ``` template< ranges::input_range R1, ranges::input_range R2, class Pred = ranges::equal_to, class Proj1 = std::identity, class Proj2 = std::identity > requires std::indirectly_comparable<ranges::iterator_t<R1>, ranges::iterator_t<R2>, Pred, Proj1, Proj2> constexpr bool equal( R1&& r1, R2&& r2, Pred pred = {}, Proj1 proj1 = {}, Proj2 proj2 = {} ); ``` | (2) | (since C++20) | 1) Returns `true` if the projected values of the range `[first1, last1)` are equal to the projected values of the range `[first2, last2)`, and `false` otherwise. 2) Same as (1), but uses `r` as the source range, as if using `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r)` as `first` and `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r)` as `last`. Two ranges are considered equal if they have the same number of elements and every pair of corresponding projected elements satisfies `pred`. That is, `[std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(pred, [std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(proj1, \*first1), [std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(proj2, \*first2))` returns `true` for all pairs of corresponding elements in both ranges. The function-like entities described on this page are *niebloids*, that is: * Explicit template argument lists cannot be specified when calling any of them. * None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl"). * When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited. In practice, they may be implemented as function objects, or with special compiler extensions. ### Parameters | | | | | --- | --- | --- | | first1, last1 | - | an iterator-sentinel pair denoting the first range of the elements to compare | | r1 | - | the first range of the elements to compare | | first2, last2 | - | an iterator-sentinel pair denoting the second range of the elements to compare | | r2 | - | the second range of the elements to compare | | pred | - | predicate to apply to the projected elements | | proj1 | - | projection to apply to the first range of elements | | proj2 | - | projection to apply to the second range of elements | ### Return value If the length of the range `[first1, last1)` does not equal the length of the range `[first2, last2)`, returns `false`. If the elements in the two ranges are equal after projection, returns `true`. Otherwise returns `false`. ### Notes `ranges::equal` should not be used to compare the ranges formed by the iterators from `[std::unordered\_set](../../container/unordered_set "cpp/container/unordered set")`, `[std::unordered\_multiset](../../container/unordered_multiset "cpp/container/unordered multiset")`, `[std::unordered\_map](../../container/unordered_map "cpp/container/unordered map")`, or `[std::unordered\_multimap](../../container/unordered_multimap "cpp/container/unordered multimap")` because the order in which the elements are stored in those containers may be different even if the two containers store the same elements. When comparing entire containers for equality, `operator==` for the corresponding container are usually preferred. ### Complexity At most min(`last1` - `first1`, `last2` - `first2`) applications of the predicate and corresponding projections. However, if `S1` and `S2` both model `[std::sized\_sentinel\_for](../../iterator/sized_sentinel_for "cpp/iterator/sized sentinel for")` their respective iterators, and `last1 - first1 != last2 - first2` then no applications of the predicate are made (size mismatch is detected without looking at any elements). ### Possible implementation | | | --- | | ``` struct equal_fn { template<std::input_iterator I1, std::sentinel_for<I1> S1, std::input_iterator I2, std::sentinel_for<I2> S2, class Pred = ranges::equal_to, class Proj1 = std::identity, class Proj2 = std::identity> requires std::indirectly_comparable<I1, I2, Pred, Proj1, Proj2> constexpr bool operator()(I1 first1, S1 last1, I2 first2, S2 last2, Pred pred = {}, Proj1 proj1 = {}, Proj2 proj2 = {}) const { if constexpr (std::sized_sentinel_for<S1, I1> and std::sized_sentinel_for<S2, I2>) { if (std::ranges::distance(first1, last1) != std::ranges::distance(first2, last2)) { return false; } } for (; first1 != last1; ++first1, (void)++first2) { if (!std::invoke(pred, std::invoke(proj1, *first1), std::invoke(proj2, *first2))) { return false; } } return true; } template<ranges::input_range R1, ranges::input_range R2, class Pred = ranges::equal_to, class Proj1 = std::identity, class Proj2 = std::identity> requires std::indirectly_comparable<ranges::iterator_t<R1>, ranges::iterator_t<R2>, Pred, Proj1, Proj2> constexpr bool operator()(R1&& r1, R2&& r2, Pred pred = {}, Proj1 proj1 = {}, Proj2 proj2 = {}) const { return (*this)(ranges::begin(r1), ranges::end(r1), ranges::begin(r2), ranges::end(r2), std::ref(pred), std::ref(proj1), std::ref(proj2)); } }; inline constexpr equal_fn equal; ``` | ### Example The following code uses `ranges::equal` to test if a string is a palindrome. ``` #include <algorithm> #include <iomanip> #include <iostream> #include <string_view> #include <ranges> constexpr bool is_palindrome(const std::string_view s) { namespace views = std::views; auto forward = s | views::take(s.size() / 2); auto backward = s | views::reverse | views::take(s.size() / 2); return std::ranges::equal(forward, backward); } void test(const std::string_view s) { std::cout << quoted(s) << " is " << (is_palindrome(s) ? "" : "not ") << "a palindrome\n"; } int main() { test("radar"); test("hello"); static_assert(is_palindrome("ABBA") and not is_palindrome("AC/DC")); } ``` Output: ``` "radar" is a palindrome "hello" is not a palindrome ``` ### See also | | | | --- | --- | | [ranges::findranges::find\_ifranges::find\_if\_not](find "cpp/algorithm/ranges/find") (C++20)(C++20)(C++20) | finds the first element satisfying specific criteria (niebloid) | | [ranges::lexicographical\_compare](lexicographical_compare "cpp/algorithm/ranges/lexicographical compare") (C++20) | returns true if one range is lexicographically less than another (niebloid) | | [ranges::mismatch](mismatch "cpp/algorithm/ranges/mismatch") (C++20) | finds the first position where two ranges differ (niebloid) | | [ranges::search](search "cpp/algorithm/ranges/search") (C++20) | searches for a range of elements (niebloid) | | [ranges::equal\_range](equal_range "cpp/algorithm/ranges/equal range") (C++20) | returns range of elements matching a specific key (niebloid) | | [equal\_to](../../utility/functional/equal_to "cpp/utility/functional/equal to") | function object implementing `x == y` (class template) | | [equal](../equal "cpp/algorithm/equal") | determines if two sets of elements are the same (function template) | cpp std::ranges::all_of, std::ranges::any_of, std::ranges::none_of std::ranges::all\_of, std::ranges::any\_of, std::ranges::none\_of ================================================================= | Defined in header `[<algorithm>](../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | Call signature | | | | ``` template< std::input_iterator I, std::sentinel_for<I> S, class Proj = std::identity, std::indirect_unary_predicate<std::projected<I, Proj>> Pred > constexpr bool all_of( I first, S last, Pred pred, Proj proj = {} ); ``` | (1) | (since C++20) | | ``` template< ranges::input_range R, class Proj = std::identity, std::indirect_unary_predicate< std::projected<ranges::iterator_t<R>,Proj>> Pred > constexpr bool all_of( R&& r, Pred pred, Proj proj = {} ); ``` | (2) | (since C++20) | | ``` template< std::input_iterator I, std::sentinel_for<I> S, class Proj = std::identity, std::indirect_unary_predicate<std::projected<I, Proj>> Pred > constexpr bool any_of( I first, S last, Pred pred, Proj proj = {} ); ``` | (3) | (since C++20) | | ``` template< ranges::input_range R, class Proj = std::identity, std::indirect_unary_predicate< std::projected<ranges::iterator_t<R>,Proj>> Pred > constexpr bool any_of( R&& r, Pred pred, Proj proj = {} ); ``` | (4) | (since C++20) | | ``` template< std::input_iterator I, std::sentinel_for<I> S, class Proj = std::identity, std::indirect_unary_predicate<std::projected<I, Proj>> Pred > constexpr bool none_of( I first, S last, Pred pred, Proj proj = {} ); ``` | (5) | (since C++20) | | ``` template< ranges::input_range R, class Proj = std::identity, std::indirect_unary_predicate< std::projected<ranges::iterator_t<R>,Proj>> Pred > constexpr bool none_of( R&& r, Pred pred, Proj proj = {} ); ``` | (6) | (since C++20) | 1) Checks if unary predicate `pred` returns `true` for all elements in the range `[first, last)` (after projecting with the projection `proj`). 3) Checks if unary predicate `pred` returns `true` for at least one element in the range `[first, last)` (after projecting with the projection `proj`). 5) Checks if unary predicate `pred` returns `true` for no elements in the range `[first, last)` (after projecting with the projection `proj`). 2,4,6) Same as (1,3,5), but uses `r` as the source range, as if using `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r)` as `first` and `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r)` as `last`. The function-like entities described on this page are *niebloids*, that is: * Explicit template argument lists cannot be specified when calling any of them. * None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl"). * When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited. In practice, they may be implemented as function objects, or with special compiler extensions. ### Parameters | | | | | --- | --- | --- | | first, last | - | the range of the elements to examine | | r | - | the range of the elements to examine | | pred | - | predicate to apply to the projected elements | | proj | - | projection to apply to the elements | ### Return value See also [Notes](#Notes) below. 1-2) `true` if `[std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(pred, [std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(proj, \*i)) != false` for every iterator `i` in the range, `false` otherwise. Returns `true` if the range is empty. 3-4) `true` if `[std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(pred, [std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(proj, \*i)) != false` for at least one iterator `i` in the range, `false` otherwise. Returns `false` if the range is empty. 5-6) `true` if `[std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(pred, [std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(proj, \*i)) == false` for every iterator `i` in the range, `false` otherwise. Returns `true` if the range is empty. ### Complexity At most `last - first` applications of the predicate and the projection. ### Possible implementation | First version | | --- | | ``` struct all_of_fn { template< std::input_iterator I, std::sentinel_for<I> S, class Proj = std::identity, std::indirect_unary_predicate<std::projected<I, Proj>> Pred > constexpr bool operator()( I first, S last, Pred pred, Proj proj = {} ) const { return ranges::find_if_not(first, last, std::ref(pred), std::ref(proj)) == last; } template< ranges::input_range R, class Proj = std::identity, std::indirect_unary_predicate< std::projected<ranges::iterator_t<R>,Proj>> Pred > constexpr bool operator()( R&& r, Pred pred, Proj proj = {} ) const { return operator()(ranges::begin(r), ranges::end(r), std::ref(pred), std::ref(proj)); } }; inline constexpr all_of_fn all_of; ``` | | Second version | | ``` struct any_of_fn { template< std::input_iterator I, std::sentinel_for<I> S, class Proj = std::identity, std::indirect_unary_predicate<std::projected<I, Proj>> Pred > constexpr bool operator()( I first, S last, Pred pred, Proj proj = {} ) const { return ranges::find_if(first, last, std::ref(pred), std::ref(proj)) != last; } template< ranges::input_range R, class Proj = std::identity, std::indirect_unary_predicate< std::projected<ranges::iterator_t<R>,Proj>> Pred > constexpr bool operator()( R&& r, Pred pred, Proj proj = {} ) const { return operator()(ranges::begin(r), ranges::end(r), std::ref(pred), std::ref(proj)); } }; inline constexpr any_of_fn any_of; ``` | | Third version | | ``` struct none_of_fn { template< std::input_iterator I, std::sentinel_for<I> S, class Proj = std::identity, std::indirect_unary_predicate<std::projected<I, Proj>> Pred > constexpr bool operator()( I first, S last, Pred pred, Proj proj = {} ) const { return ranges::find_if(first, last, std::ref(pred), std::ref(proj)) == last; } template< ranges::input_range R, class Proj = std::identity, std::indirect_unary_predicate< std::projected<ranges::iterator_t<R>,Proj>> Pred > constexpr bool operator()( R&& r, Pred pred, Proj proj = {} ) const { return operator()(ranges::begin(r), ranges::end(r), std::ref(pred), std::ref(proj)); } }; inline constexpr none_of_fn none_of; ``` | ### Notes The [return value](#Return_value) represented in the form of the [Truth table](https://en.wikipedia.org/wiki/Truth_table "enwiki:Truth table") is: | | | | --- | --- | | | input range contains | | | all `true`,none `false` | some `true`,some `false` | none `true`,all `false` | none `true`,none `false`(empty range) | | 1–2) `all_of` | `true` | `false` | `false` | `true` | | 3–4) `any_of` | `true` | `true` | `false` | `false` | | 5–6) `none_of` | `false` | `false` | `true` | `true` | ### Example ``` #include <vector> #include <numeric> #include <algorithm> #include <iterator> #include <iostream> #include <functional> namespace ranges = std::ranges; int main() { std::vector<int> v(10, 2); std::partial_sum(v.cbegin(), v.cend(), v.begin()); std::cout << "Among the numbers: "; ranges::copy(v, std::ostream_iterator<int>(std::cout, " ")); std::cout << '\n'; if (ranges::all_of(v.cbegin(), v.cend(), [](int i){ return i % 2 == 0; })) { std::cout << "All numbers are even\n"; } if (ranges::none_of(v, std::bind(std::modulus<int>(), std::placeholders::_1, 2))) { std::cout << "None of them are odd\n"; } auto DivisibleBy = [](int d) { return [d](int m) { return m % d == 0; }; }; if (ranges::any_of(v, DivisibleBy(7))) { std::cout << "At least one number is divisible by 7\n"; } } ``` Output: ``` Among the numbers: 2 4 6 8 10 12 14 16 18 20 All numbers are even None of them are odd At least one number is divisible by 7 ``` ### See also | | | | --- | --- | | [all\_ofany\_ofnone\_of](../all_any_none_of "cpp/algorithm/all any none of") (C++11)(C++11)(C++11) | checks if a predicate is `true` for all, any or none of the elements in a range (function template) | cpp std::ranges::clamp std::ranges::clamp ================== | Defined in header `[<algorithm>](../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | Call signature | | | | ``` template< class T, class Proj = std::identity, std::indirect_strict_weak_order<std::projected<const T*, Proj>> Comp = ranges::less > constexpr const T& clamp( const T& v, const T& lo, const T& hi, Comp comp = {}, Proj proj = {} ); ``` | | (since C++20) | If `v` compares less than `lo`, returns `lo`; otherwise if `hi` compares less than `v`, returns `hi`; otherwise returns `v`. The behavior is undefined if `lo` is greater than `hi`. The function-like entities described on this page are *niebloids*, that is: * Explicit template argument lists cannot be specified when calling any of them. * None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl"). * When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited. In practice, they may be implemented as function objects, or with special compiler extensions. ### Parameters | | | | | --- | --- | --- | | v | - | the value to clamp | | lo, hi | - | the boundaries to clamp `v` to | | comp | - | the comparison to apply to the projected elements | | proj | - | the projection to apply to `v`, `lo` and `hi` | ### Return value Reference to `lo` if the projected value of `v` is less than the projected value of `lo`, reference to `hi` if the projected value of `hi` is less than the projected value of `v`, otherwise reference to `v`. ### Complexity At most two comparisons and three applications of the projection. ### Possible implementation | | | --- | | ``` struct clamp_fn { template<class T, class Proj = std::identity, std::indirect_strict_weak_order<std::projected<const T*, Proj>> Comp = ranges::less> constexpr const T& operator()(const T& v, const T& lo, const T& hi, Comp comp = {}, Proj proj = {}) const { auto&& pv = std::invoke(proj, v); return std::invoke(comp, std::forward<decltype(pv)>(pv), std::invoke(proj, lo)) ? lo : std::invoke(comp, std::invoke(proj, hi), std::forward<decltype(pv)>(pv)) ? hi : v; } }; inline constexpr clamp_fn clamp; ``` | ### Notes Capturing the result of `std::ranges::clamp` by reference produces a dangling reference if one of the parameters is a temporary and that parameter is returned: ``` int n = 1; const int& r = std::ranges::clamp(n-1, n+1); // r is dangling ``` If `v` compares equivalent to either bound, returns a reference to `v`, not the bound. ### Example ``` #include <algorithm> #include <cstdint> #include <iostream> #include <iomanip> #include <string> using namespace std::literals; namespace ranges = std::ranges; int main() { std::cout << " raw clamped to int8_t clamped to uint8_t\n"; for(int const v: {-129, -128, -1, 0, 42, 127, 128, 255, 256}) { std::cout << std::setw(04) << v << std::setw(20) << ranges::clamp(v, INT8_MIN, INT8_MAX) << std::setw(21) << ranges::clamp(v, 0, UINT8_MAX) << '\n'; } std::cout << '\n'; // Projection function const auto stoi = [](std::string s) { return std::stoi(s); }; // Same as above, but with strings for(std::string const v: {"-129", "-128", "-1", "0", "42", "127", "128", "255", "256"}) { std::cout << std::setw(04) << v << std::setw(20) << ranges::clamp(v, "-128"s, "127"s, {}, stoi) << std::setw(21) << ranges::clamp(v, "0"s, "255"s, {}, stoi) << '\n'; } } ``` Output: ``` raw clamped to int8_t clamped to uint8_t -129 -128 0 -128 -128 0 -1 -1 0 0 0 0 42 42 42 127 127 127 128 127 128 255 127 255 256 127 255 -129 -128 0 -128 -128 0 -1 -1 0 0 0 0 42 42 42 127 127 127 128 127 128 255 127 255 256 127 255 ``` ### See also | | | | --- | --- | | [ranges::min](min "cpp/algorithm/ranges/min") (C++20) | returns the smaller of the given values (niebloid) | | [ranges::max](max "cpp/algorithm/ranges/max") (C++20) | returns the greater of the given values (niebloid) | | [in\_range](../../utility/in_range "cpp/utility/in range") (C++20) | checks if an integer value is in the range of a given integer type (function template) | | [clamp](../clamp "cpp/algorithm/clamp") (C++17) | clamps a value between a pair of boundary values (function template) |
programming_docs
cpp std::ranges::for_each_n, std::ranges::for_each_n_result std::ranges::for\_each\_n, std::ranges::for\_each\_n\_result ============================================================ | Defined in header `[<algorithm>](../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | Call signature | | | | ``` template< std::input_iterator I, class Proj = identity, std::indirectly_unary_invocable<std::projected<I, Proj>> Fun > constexpr for_each_n_result<I, Fun> for_each_n( I first, std::iter_difference_t<I> n, Fun f, Proj proj = {}); ``` | (1) | (since C++20) | | Helper types | | | | ``` template< class I, class F > using for_each_n_result = ranges::in_fun_result<I, F>; ``` | (2) | (since C++20) | 1) Applies the given function object `f` to the projected result by `proj` of dereferencing each iterator in the range `[first, first + n)`, in order. If the iterator type is mutable, `f` may modify the elements of the range through the dereferenced iterator. If `f` returns a result, the result is ignored. If `n` is less than zero, the behavior is undefined. The function-like entities described on this page are *niebloids*, that is: * Explicit template argument lists cannot be specified when calling any of them. * None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl"). * When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited. In practice, they may be implemented as function objects, or with special compiler extensions. ### Parameters | | | | | --- | --- | --- | | first | - | iterator denoting the begin of the range to apply the function to | | n | - | the number of elements to apply the function to | | f | - | the function to apply to the projected range `[first, first + n)` | | proj | - | projection to apply to the elements | ### Return value An object `{first + n, std::move(f)}`, where `first + n` may be evaluated as `std::[ranges::next](http://en.cppreference.com/w/cpp/iterator/ranges/next)(std::move(first), n)` depending on iterator category. ### Complexity Exactly `n` applications of `f` and `proj`. ### Notes The overload in `namespace::ranges` requires `Fun` to model [`copy_constructible`](../../concepts/copy_constructible "cpp/concepts/copy constructible"). ### Possible implementation ``` struct for_each_n_fn { template<std::input_iterator I, class Proj = std::identity, std::indirectly_unary_invocable<std::projected<I, Proj>> Fun> constexpr for_each_n_result<I, Fun> operator()(I first, std::iter_difference_t<I> n, Fun fun, Proj proj = Proj{}) const { for (; n-- > 0; ++first) { std::invoke(fun, std::invoke(proj, *first)); } return {std::move(first), std::move(fun)}; } }; inline constexpr for_each_n_fn for_each_n{}; ``` ### Example ``` #include <algorithm> #include <array> #include <iostream> #include <ranges> #include <string_view> struct P { int first; char second; friend std::ostream& operator<< (std::ostream& os, const P& p) { return os << '{' << p.first << ",'" << p.second << "'}"; } }; auto print = [](std::string_view name, auto const& v) { std::cout << name << ": "; for (auto n = v.size(); const auto& e: v) { std::cout << e << (--n ? ", " : "\n"); } }; int main() { std::array a{1, 2, 3, 4, 5}; print("a", a); // Negate first three numbers: std::ranges::for_each_n(a.begin(), 3, [](auto& n) { n *= -1; }); print("a", a); std::array s{ P{1,'a'}, P{2, 'b'}, P{3, 'c'}, P{4, 'd'} }; print("s", s); // Negate data members 'pair::first' using projection: std::ranges::for_each_n(s.begin(), 2, [](auto& x) { x *= -1; }, &P::first); print("s", s); // Capitalize data members 'pair::second' using projection: std::ranges::for_each_n(s.begin(), 3, [](auto& c) { c -= 'a'-'A'; }, &P::second); print("s", s); } ``` Output: ``` a: 1, 2, 3, 4, 5 a: -1, -2, -3, 4, 5 s: {1,'a'}, {2,'b'}, {3,'c'}, {4,'d'} s: {-1,'a'}, {-2,'b'}, {3,'c'}, {4,'d'} s: {-1,'A'}, {-2,'B'}, {3,'C'}, {4,'d'} ``` ### See also | | | | --- | --- | | [range-`for` loop](../../language/range-for "cpp/language/range-for")(C++11) | executes loop over range | | [ranges::for\_each](for_each "cpp/algorithm/ranges/for each") (C++20) | applies a function to a range of elements (niebloid) | | [for\_each\_n](../for_each_n "cpp/algorithm/for each n") (C++17) | applies a function object to the first n elements of a sequence (function template) | | [for\_each](../for_each "cpp/algorithm/for each") | applies a function to a range of elements (function template) | cpp std::ranges::unique std::ranges::unique =================== | Defined in header `[<algorithm>](../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | Call signature | | | | ``` template< std::permutable I, std::sentinel_for<I> S, class Proj = std::identity, std::indirect_equivalence_relation<std::projected<I, Proj>> C = ranges::equal_to > constexpr ranges::subrange<I> unique( I first, S last, C comp = {}, Proj proj = {} ); ``` | (1) | (since C++20) | | ``` template< ranges::forward_range R, class Proj = std::identity, std::indirect_equivalence_relation<std::projected<ranges::iterator_t<R>, Proj>> C = ranges::equal_to > requires std::permutable<ranges::iterator_t<R>> constexpr ranges::borrowed_subrange_t<R> unique( R&& r, C comp = {}, Proj proj = {} ); ``` | (2) | (since C++20) | 1) Eliminates all except the first element from every consecutive group of equivalent elements from the range `[first, last)` and returns a subrange `[ret, last)`, where `ret` is a past-the-end iterator for the new end of the range. Two consecutive elements `*(i - 1)` and `*i` are considered equivalent if `[std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(comp, [std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(proj, \*(i - 1)), [std::invoke](http://en.cppreference.com/w/cpp/utility/functional/invoke)(proj, \*i)) == true`, where `i` is an iterator in the range `[first + 1, last)`. 2) Same as (1), but uses `r` as the range, as if using `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r)` as `first`, and `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r)` as `last`. The function-like entities described on this page are *niebloids*, that is: * Explicit template argument lists cannot be specified when calling any of them. * None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl"). * When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited. In practice, they may be implemented as function objects, or with special compiler extensions. ### Parameters | | | | | --- | --- | --- | | first, last | - | the range of elements to process | | r | - | the range of elements to process | | comp | - | the binary predicate to compare the projected elements | | proj | - | the projection to apply to the elements | ### Return value Returns `{ret, last}`, where `ret` is a past-the-end iterator for the new end of the range. ### Complexity For nonempty ranges, exactly `[ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(first, last) - 1` applications of the corresponding predicate `comp` and no more that twice as many applications of any projection `proj`. ### Notes Removing is done by shifting (by means of move assignment) the elements in the range in such a way that the elements that are not to be removed appear in the beginning of the range. Relative order of the elements that remain is preserved and the *physical* size of the container is unchanged. Iterators in `[ret, last)` (if any) are still dereferenceable, but the elements themselves have unspecified values (as per [MoveAssignable](../../named_req/moveassignable "cpp/named req/MoveAssignable") post-condition). A call to `ranges::unique` is sometimes followed by a call to a container’s `erase` member function, which erases the unspecified values and reduces the *physical* size of the container to match its new *logical* size. These two invocations together model the [*Erase–remove* idiom](https://en.wikipedia.org/wiki/Erase-remove_idiom "enwiki:Erase-remove idiom"). ### Possible implementation | | | --- | | ``` struct unique_fn { template<std::permutable I, std::sentinel_for<I> S, class Proj = std::identity, std::indirect_equivalence_relation<std::projected<I, Proj>> C = ranges::equal_to> constexpr ranges::subrange<I> operator() ( I first, S last, C comp = {}, Proj proj = {} ) const { first = ranges::adjacent_find(first, last, comp, proj); if (first == last) return {first, first}; auto i {first}; ++first; while (++first != last) if (!std::invoke(comp, std::invoke(proj, *i), std::invoke(proj, *first))) *++i = ranges::iter_move(first); return {++i, first}; } template<ranges::forward_range R, class Proj = std::identity, std::indirect_equivalence_relation<std::projected<ranges::iterator_t<R>, Proj>> C = ranges::equal_to> requires std::permutable<ranges::iterator_t<R>> constexpr ranges::borrowed_subrange_t<R> operator() ( R&& r, C comp = {}, Proj proj = {} ) const { return (*this)(ranges::begin(r), ranges::end(r), std::move(comp), std::move(proj)); } }; inline constexpr unique_fn unique{}; ``` | ### Example ``` #include <algorithm> #include <cmath> #include <complex> #include <iostream> #include <vector> struct id { int i; explicit id(int i) : i{i} {} }; void print(id i, const auto& v) { std::cout << i.i << ") "; std::ranges::for_each(v, [](auto const& e) { std::cout << e << ' '; }); std::cout << '\n'; } int main() { // a vector containing several duplicated elements std::vector<int> v{1, 2, 1, 1, 3, 3, 3, 4, 5, 4}; print(id{1}, v); // remove consecutive (adjacent) duplicates const auto ret = std::ranges::unique(v); // v now holds {1 2 1 3 4 5 4 x x x}, where 'x' is indeterminate v.erase(ret.begin(), ret.end()); print(id{2}, v); // sort followed by unique, to remove all duplicates std::ranges::sort(v); // {1 1 2 3 4 4 5} print(id{3}, v); const auto [first, last] = std::ranges::unique(v.begin(), v.end()); // v now holds {1 2 3 4 5 x x}, where 'x' is indeterminate v.erase(first, last); print(id{4}, v); // unique with custom comparison and projection std::vector<std::complex<int>> vc{ {1, 1}, {-1, 2}, {-2, 3}, {2, 4}, {-3, 5} }; print(id{5}, vc); const auto ret2 = std::ranges::unique(vc, // consider two complex nums equal if their real parts are equal by module: [](int x, int y) { return std::abs(x) == std::abs(y); }, // comp [](std::complex<int> z) { return z.real(); } // proj ); vc.erase(ret2.begin(), ret2.end()); print(id{6}, vc); } ``` Output: ``` 1) 1 2 1 1 3 3 3 4 5 4 2) 1 2 1 3 4 5 4 3) 1 1 2 3 4 4 5 4) 1 2 3 4 5 5) (1,1) (-1,2) (-2,3) (2,4) (-3,5) 6) (1,1) (-2,3) (-3,5) ``` ### See also | | | | --- | --- | | [ranges::unique\_copy](unique_copy "cpp/algorithm/ranges/unique copy") (C++20) | creates a copy of some range of elements that contains no consecutive duplicates (niebloid) | | [ranges::adjacent\_find](adjacent_find "cpp/algorithm/ranges/adjacent find") (C++20) | finds the first two adjacent items that are equal (or satisfy a given predicate) (niebloid) | | [ranges::removeranges::remove\_if](remove "cpp/algorithm/ranges/remove") (C++20)(C++20) | removes elements satisfying specific criteria (niebloid) | | [unique](../unique "cpp/algorithm/unique") | removes consecutive duplicate elements in a range (function template) | | [unique](../../container/list/unique "cpp/container/list/unique") | removes consecutive duplicate elements (public member function of `std::list<T,Allocator>`) | | [unique](../../container/forward_list/unique "cpp/container/forward list/unique") (C++11) | removes consecutive duplicate elements (public member function of `std::forward_list<T,Allocator>`) | cpp std::ranges::next_permutation, std::ranges::next_permutation_result std::ranges::next\_permutation, std::ranges::next\_permutation\_result ====================================================================== | Defined in header `[<algorithm>](../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | Call signature | | | | ``` template< std::bidirectional_iterator I, std::sentinel_for<I> S, class Comp = ranges::less, class Proj = std::identity > requires std::sortable<I, Comp, Proj> constexpr next_permutation_result<I> next_permutation( I first, S last, Comp comp = {}, Proj proj = {} ); ``` | (1) | (since C++20) | | ``` template< ranges::bidirectional_range R, class Comp = ranges::less, class Proj = std::identity > requires std::sortable<ranges::iterator_t<R>, Comp, Proj> constexpr next_permutation_result<ranges::borrowed_iterator_t<R>> next_permutation( R&& r, Comp comp = {}, Proj proj = {} ); ``` | (2) | (since C++20) | | Helper type | | | | ``` template<class I> using next_permutation_result = ranges::in_found_result<I>; ``` | (3) | (since C++20) | 1) Transforms the range `[first, last)` into the next *permutation*, where the set of all permutations is ordered *lexicographically* with respect to binary comparison function object `comp` and projection function object `proj`. Returns `{last, true}` if such a *"next permutation"* exists; otherwise transforms the range into the lexicographically first permutation as if by `[ranges::sort](http://en.cppreference.com/w/cpp/ranges-algorithm-placeholder/sort)(first, last, comp, proj)`, and returns `{last, false}`. 2) Same as (1), but uses `r` as the source range, as if using `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r)` as `first`, and `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r)` as `last`. The function-like entities described on this page are *niebloids*, that is: * Explicit template argument lists cannot be specified when calling any of them. * None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl"). * When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited. In practice, they may be implemented as function objects, or with special compiler extensions. ### Parameters | | | | | --- | --- | --- | | first, last | - | the range of elements to *permute* | | r | - | the range of elements to *permute* | | comp | - | comparison function object which returns `true` if the first argument is *less* than the second | | proj | - | projection to apply to the elements | ### Return value 1) `ranges::next_permutation_result<I>{last, true}` if the new permutation is lexicographically *greater* than the old one. `ranges::next_permutation_result<I>{last, false}` if the last permutation was reached and the range was reset to the first permutation. 2) same as (1) except that the return type is `ranges::next\_permutation\_result<[ranges::borrowed\_iterator\_t](http://en.cppreference.com/w/cpp/ranges/borrowed_iterator_t)<R>>`. ### Exceptions Any exceptions thrown from iterator operations or the element swap. ### Complexity At most \(\scriptsize N/2\)N/2 swaps, where \(\scriptsize N\)N is `[ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(first, last)` in case (1) or `[ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(r)` in case (2). Averaged over the entire sequence of permutations, typical implementations use about 3 comparisons and 1.5 swaps per call. ### Notes Implementations (e.g. [MSVC STL](https://github.com/microsoft/STL/blob/main/stl/src/vector_algorithms.cpp)) may enable vectorization when the iterator type models [`contiguous_iterator`](../../iterator/contiguous_iterator "cpp/iterator/contiguous iterator") and swapping its value type calls neither non-trivial special member function nor [ADL](../../language/adl "cpp/language/adl")-found `swap`. ### Possible implementation | | | --- | | ``` struct next_permutation_fn { template<std::bidirectional_iterator I, std::sentinel_for<I> S, class Comp = ranges::less, class Proj = std::identity> requires std::sortable<I, Comp, Proj> constexpr ranges::next_permutation_result<I> operator()(I first, S last, Comp comp = {}, Proj proj = {}) const { // check that the sequence has at least two elements if (first == last) return {std::move(first), false}; I i_last {ranges::next(first, last)}; I i {i_last}; if (first == --i) return {std::move(i_last), false}; // main "permutating" loop for (;;) { I i1 {i}; if (std::invoke(comp, std::invoke(proj, *--i), std::invoke(proj, *i1))) { I j {i_last}; while (!std::invoke(comp, std::invoke(proj, *i), std::invoke(proj, *--j))) { } std::iter_swap(i, j); std::reverse(i1, i_last); return {std::move(i_last), true}; } // permutation "space" is exhausted if (i == first) { std::reverse(first, i_last); return {std::move(i_last), false}; } } } template<ranges::bidirectional_range R, class Comp = ranges::less, class Proj = std::identity> requires std::sortable<ranges::iterator_t<R>, Comp, Proj> constexpr ranges::next_permutation_result<ranges::borrowed_iterator_t<R>> operator()(R&& r, Comp comp = {}, Proj proj = {}) const { return (*this)(ranges::begin(r), ranges::end(r), std::move(comp), std::move(proj)); } }; inline constexpr next_permutation_fn next_permutation{}; ``` | ### Example ``` #include <algorithm> #include <array> #include <compare> #include <functional> #include <iostream> #include <string> struct S { char c; int i; auto operator<=>(const S&) const = default; friend std::ostream& operator<< (std::ostream& os, const S& s) { return os << "{'" << s.c << "', " << s.i << "}"; } }; auto print = [](auto const& v, char term = ' ') { std::cout << "{ "; for (const auto& e: v) { std::cout << e << ' '; } std::cout << '}' << term; }; int main() { std::cout << "Generate all permutations (iterators case):\n"; std::string s{"abc"}; do { print(s); } while(std::ranges::next_permutation(s.begin(), s.end()).found); std::cout << "\n" "Generate all permutations (range case):\n"; std::array a{'a', 'b', 'c'}; do { print(a); } while(std::ranges::next_permutation(a).found); std::cout << "\n" "Generate all permutations using comparator:\n"; using namespace std::literals; std::array z{ "█"s, "▄"s, "▁"s }; do { print(z); } while(std::ranges::next_permutation(z, std::greater()).found); std::cout << "\n" "Generate all permutations using projection:\n"; std::array<S, 3> r{ S{'A',3}, S{'B',2}, S{'C',1} }; do { print(r, '\n'); } while(std::ranges::next_permutation(r, {}, &S::c).found); } ``` Output: ``` Generate all permutations (iterators case): { a b c } { a c b } { b a c } { b c a } { c a b } { c b a } Generate all permutations (range case): { a b c } { a c b } { b a c } { b c a } { c a b } { c b a } Generate all permutations using comparator: { █ ▄ ▁ } { █ ▁ ▄ } { ▄ █ ▁ } { ▄ ▁ █ } { ▁ █ ▄ } { ▁ ▄ █ } Generate all permutations using projection: { {'A', 3} {'B', 2} {'C', 1} } { {'A', 3} {'C', 1} {'B', 2} } { {'B', 2} {'A', 3} {'C', 1} } { {'B', 2} {'C', 1} {'A', 3} } { {'C', 1} {'A', 3} {'B', 2} } { {'C', 1} {'B', 2} {'A', 3} } ``` ### See also | | | | --- | --- | | [ranges::prev\_permutation](prev_permutation "cpp/algorithm/ranges/prev permutation") (C++20) | generates the next smaller lexicographic permutation of a range of elements (niebloid) | | [ranges::is\_permutation](is_permutation "cpp/algorithm/ranges/is permutation") (C++20) | determines if a sequence is a permutation of another sequence (niebloid) | | [next\_permutation](../next_permutation "cpp/algorithm/next permutation") | generates the next greater lexicographic permutation of a range of elements (function template) | | [prev\_permutation](../prev_permutation "cpp/algorithm/prev permutation") | generates the next smaller lexicographic permutation of a range of elements (function template) | | [is\_permutation](../is_permutation "cpp/algorithm/is permutation") (C++11) | determines if a sequence is a permutation of another sequence (function template) |
programming_docs
cpp std::ranges::set_union, std::ranges::set_union_result std::ranges::set\_union, std::ranges::set\_union\_result ======================================================== | Defined in header `[<algorithm>](../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | Call signature | | | | ``` template< std::input_iterator I1, std::sentinel_for<I1> S1, std::input_iterator I2, std::sentinel_for<I2> S2, std::weakly_incrementable O, class Comp = ranges::less, class Proj1 = std::identity, class Proj2 = std::identity > requires std::mergeable<I1, I2, O, Comp, Proj1, Proj2> constexpr set_union_result<I1, I2, O> set_union( I1 first1, S1 last1, I2 first2, S2 last2, O result, Comp comp = {}, Proj1 proj1 = {}, Proj2 proj2 = {} ); ``` | (1) | (since C++20) | | ``` template< ranges::input_range R1, ranges::input_range R2, std::weakly_incrementable O, class Comp = ranges::less, class Proj1 = std::identity, class Proj2 = std::identity > requires std::mergeable<ranges::iterator_t<R1>, ranges::iterator_t<R2>, O, Comp, Proj1, Proj2> constexpr set_union_result<ranges::borrowed_iterator_t<R1>, ranges::borrowed_iterator_t<R2>, O> set_union( R1&& r1, R2&& r2, O result, Comp comp = {}, Proj1 proj1 = {}, Proj2 proj2 = {} ); ``` | (2) | (since C++20) | | Helper types | | | | ``` template<class I1, class I2, class O> using set_union_result = ranges::in_in_out_result<I1, I2, O>; ``` | (3) | (since C++20) | Constructs a sorted union beginning at `result` consisting of the set of elements present in one or both sorted input ranges `[first1, last1)` and `[first2, last2)`. If some element is found `m` times in `[first1, last1)` and `n` times in `[first2, last2)`, then all `m` elements will be copied from `[first1, last1)` to `result`, preserving order, and then exactly `max(n-m, 0)` elements will be copied from `[first2, last2)` to `result`, also preserving order. The behavior is undefined if. * the input ranges are not sorted with respect to `comp` and `proj1` or `proj2`, respectively, or * the resulting range overlaps with either of the input ranges. 1) Elements are compared using the given binary comparison function `comp`. 2) Same as (1), but uses `r1` as the first range and `r2` as the second range, as if using `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r1)` as `first1`, `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r1)` as `last1`, `[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r2)` as `first2`, and `[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r2)` as `last2`. The function-like entities described on this page are *niebloids*, that is: * Explicit template argument lists cannot be specified when calling any of them. * None of them are visible to [argument-dependent lookup](../../language/adl "cpp/language/adl"). * When any of them are found by [normal unqualified lookup](../../language/unqualified_lookup "cpp/language/unqualified lookup") as the name to the left of the function-call operator, [argument-dependent lookup](../../language/adl "cpp/language/adl") is inhibited. In practice, they may be implemented as function objects, or with special compiler extensions. ### Parameters | | | | | --- | --- | --- | | first1, last1 | - | iterator-sentinel pair denoting the first input sorted range | | first2, last2 | - | iterator-sentinel pair denoting the second input sorted range | | r1 | - | the first input sorted range | | r2 | - | the second input sorted range | | result | - | the beginning of the output range | | comp | - | comparison to apply to the projected elements | | proj1 | - | projection to apply to the elements in the first range | | proj2 | - | projection to apply to the elements in the second range | ### Return value `{last1, last2, result_last}`, where `result_last` is the end of the constructed range. ### Complexity At most \(\scriptsize 2\cdot(N\_1+N\_2)-1\)2·(N 1+N 2)-1 comparisons and applications of each projection, where \(\scriptsize N\_1\)N 1 and \(\scriptsize N\_2\)N 2 are `[ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(first1, last1)` and `[ranges::distance](http://en.cppreference.com/w/cpp/iterator/ranges/distance)(first2, last2)`, respectively. ### Notes This algorithm performs a similar task as `[ranges::merge](merge "cpp/algorithm/ranges/merge")` does. Both consume two sorted input ranges and produce a sorted output with elements from both inputs. The difference between these two algorithms is with handling values from both input ranges which compare equivalent (see notes on [LessThanComparable](../../named_req/lessthancomparable "cpp/named req/LessThanComparable")). If any equivalent values appeared `n` times in the first range and `m` times in the second, `[ranges::merge](merge "cpp/algorithm/ranges/merge")` would output all `n+m` occurrences whereas `ranges::set_union` would output `[std::max](http://en.cppreference.com/w/cpp/algorithm/max)(n, m)` ones only. So `[ranges::merge](merge "cpp/algorithm/ranges/merge")` outputs exactly \(\scriptsize (N\_1+N\_2)\)(N 1+N 2) values and `ranges::set_union` may produce less. ### Possible implementation | | | --- | | ``` struct set_union_fn { template< std::input_iterator I1, std::sentinel_for<I1> S1, std::input_iterator I2, std::sentinel_for<I2> S2, std::weakly_incrementable O, class Comp = ranges::less, class Proj1 = std::identity, class Proj2 = std::identity > requires std::mergeable<I1, I2, O, Comp, Proj1, Proj2> constexpr ranges::set_union_result<I1, I2, O> operator()( I1 first1, S1 last1, I2 first2, S2 last2, O result, Comp comp = {}, Proj1 proj1 = {}, Proj2 proj2 = {} ) const { for (; !(first1 == last1 or first2 == last2); ++result) { if (std::invoke(comp, std::invoke(proj1, *first1), std::invoke(proj2, *first2))) { *result = *first1; ++first1; } else if (std::invoke(comp, std::invoke(proj2, *first2), std::invoke(proj1, *first1))) { *result = *first2; ++first2; } else { *result = *first1; ++first1; ++first2; } } auto res1 = ranges::copy(std::move(first1), std::move(last1), std::move(result)); auto res2 = ranges::copy(std::move(first2), std::move(last2), std::move(res1.out)); return {std::move(res1.in), std::move(res2.in), std::move(res2.out)}; } template< ranges::input_range R1, ranges::input_range R2, std::weakly_incrementable O, class Comp = ranges::less, class Proj1 = std::identity, class Proj2 = std::identity > requires std::mergeable<ranges::iterator_t<R1>, ranges::iterator_t<R2>, O, Comp, Proj1, Proj2> constexpr ranges::set_union_result<ranges::borrowed_iterator_t<R1>, ranges::borrowed_iterator_t<R2>, O> operator()( R1&& r1, R2&& r2, O result, Comp comp = {}, Proj1 proj1 = {}, Proj2 proj2 = {} ) const { return (*this)(ranges::begin(r1), ranges::end(r1), ranges::begin(r2), ranges::end(r2), std::move(result), std::move(comp), std::move(proj1), std::move(proj2)); } }; inline constexpr set_union_fn set_union{}; ``` | ### Example ``` #include <algorithm> #include <iostream> #include <iterator> #include <vector> void print(const auto& in1, const auto& in2, auto first, auto last) { std::cout << "{ "; for (const auto& e : in1) { std::cout << e << ' '; } std::cout << "} ∪ { "; for (const auto& e : in2) { std::cout << e << ' '; } std::cout << "} =\n{ "; while (!(first == last)) { std::cout << *first++ << ' '; } std::cout << "}\n\n"; } int main() { std::vector<int> in1, in2, out; in1 = {1, 2, 3, 4, 5}; in2 = { 3, 4, 5, 6, 7}; out.resize(in1.size() + in2.size()); const auto ret = std::ranges::set_union(in1, in2, out.begin()); print(in1, in2, out.begin(), ret.out); in1 = {1, 2, 3, 4, 5, 5, 5}; in2 = { 3, 4, 5, 6, 7}; out.clear(); out.reserve(in1.size() + in2.size()); std::ranges::set_union(in1, in2, std::back_inserter(out)); print(in1, in2, out.cbegin(), out.cend()); } ``` Output: ``` { 1 2 3 4 5 } ∪ { 3 4 5 6 7 } = { 1 2 3 4 5 6 7 } { 1 2 3 4 5 5 5 } ∪ { 3 4 5 6 7 } = { 1 2 3 4 5 5 5 6 7 } ``` ### See also | | | | --- | --- | | [ranges::set\_difference](set_difference "cpp/algorithm/ranges/set difference") (C++20) | computes the difference between two sets (niebloid) | | [ranges::set\_intersection](set_intersection "cpp/algorithm/ranges/set intersection") (C++20) | computes the intersection of two sets (niebloid) | | [ranges::set\_symmetric\_difference](set_symmetric_difference "cpp/algorithm/ranges/set symmetric difference") (C++20) | computes the symmetric difference between two sets (niebloid) | | [ranges::merge](merge "cpp/algorithm/ranges/merge") (C++20) | merges two sorted ranges (niebloid) | | [ranges::includes](includes "cpp/algorithm/ranges/includes") (C++20) | returns true if one sequence is a subsequence of another (niebloid) | | [set\_union](../set_union "cpp/algorithm/set union") | computes the union of two sets (function template) | cpp std::ranges::min_max_result std::ranges::min\_max\_result ============================= | Defined in header `[<algorithm>](../../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | ``` template <class T> struct min_max_result; ``` | | (since C++20) | `ranges::min_max_result` is a class template that provides a way to store two objects or references of the same type as a single unit. This class template has no base classes or declared members other than those shown below. Thus it is suitable for use with [structured bindings](../../../language/structured_binding "cpp/language/structured binding"). All special member functions of this class template are implicitly declared, which makes specializations be [aggregate classes](../../../language/aggregate_initialization "cpp/language/aggregate initialization"), and propagate triviality, potentially-throwing-ness, and constexpr-ness of corresponding operations on data members. ### Template parameters | | | | | --- | --- | --- | | T | - | the type of the objects or references that the `ranges::min_max_result` stores. | ### Data members std::ranges::min\_max\_result::min ----------------------------------- | | | | | --- | --- | --- | | ``` [[no_unique_address]] T min; ``` | | | May be a reference to, a copy of, or an iterator to a minimum element in a range. std::ranges::min\_max\_result::max ----------------------------------- | | | | | --- | --- | --- | | ``` [[no_unique_address]] T max; ``` | | | May be a reference to, a copy of, or an iterator to a maximum element in a range. ### Member functions std::ranges::min\_max\_result::operator min\_max\_result<T2> ------------------------------------------------------------- | | | | | --- | --- | --- | | ``` template<class T2> requires std::convertible_to<const T&, T2> constexpr operator min_max_result<T2>() const &; ``` | (1) | | | ``` template<class T2> requires std::convertible_to<T, T2> constexpr operator min_max_result<T2>() &&; ``` | (2) | | Converts `*this` to the result by constructing every data member of the result from the corresponding member of `*this`. 1) Equivalent to `return {min, max};`. 2) Equivalent to `return {std::move(min), std::move(max)};`. ### Standard library The following standard library functions use `ranges::min_max_result` as the return type: | | | --- | | Algorithm functions | | [ranges::minmax](../minmax "cpp/algorithm/ranges/minmax") (C++20) | returns the smaller and larger of two elements (niebloid) | | [ranges::minmax\_element](../minmax_element "cpp/algorithm/ranges/minmax element") (C++20) | returns the smallest and the largest elements in a range (niebloid) | ### Synopsis ``` namespace std::ranges { template<class T> struct min_max_result { [[no_unique_address]] T min; [[no_unique_address]] T max; template<class T2> requires std::convertible_to<const T&, T2> constexpr operator min_max_result<T2>() const & { return {min, max}; } template<class T2> requires std::convertible_to<T, T2> constexpr operator min_max_result<T2>() && { return {std::move(min), std::move(max)}; } }; } ``` ### Notes Each standard library algorithm that uses this family of return types declares a new [alias type](../../../language/type_alias "cpp/language/type alias"), e.g. `using merge_result = in_in_out_result<I1, I2, O>;`. The names for such aliases are formed by adding the suffix "*`_result`*" to the algorithm's name. So, the return type of `std::ranges::merge` can be named as `std::ranges::merge_result`. Unlike `[std::pair](../../../utility/pair "cpp/utility/pair")` and `[std::tuple](../../../utility/tuple "cpp/utility/tuple")`, this class template has data members of meaningful names. ### Example ``` #include <algorithm> #include <ranges> int main() { constexpr static auto v = {3, 1, 4, 1, 5, 9, 2}; { constexpr auto result = std::ranges::minmax(v); static_assert(1 == result.min && 9 == result.max); } { constexpr auto result = std::ranges::minmax_element(v); static_assert(1 == *result.min && 9 == *result.max); } } ``` ### See also | | | | --- | --- | | [pair](../../../utility/pair "cpp/utility/pair") | implements binary tuple, i.e. a pair of values (class template) | | [tuple](../../../utility/tuple "cpp/utility/tuple") (C++11) | implements fixed size container, which holds elements of possibly different types (class template) | cpp std::ranges::in_value_result std::ranges::in\_value\_result ============================== | Defined in header `[<algorithm>](../../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | ``` template<class I, class T> struct in_value_result; ``` | | (since C++23) | `ranges::in_value_result` is a class template that provides a way to store an iterator and a value as a single unit. This class template has no base classes or declared members other than those shown below. Thus it is suitable for use with [structured bindings](../../../language/structured_binding "cpp/language/structured binding"). All special member functions of this class template are implicitly declared, which makes specializations be [aggregate classes](../../../language/aggregate_initialization "cpp/language/aggregate initialization"), and propagate triviality, potentially-throwing-ness, and constexpr-ness of corresponding operations on data members. ### Template parameters | | | | | --- | --- | --- | | I, T | - | the types of the objects that the `ranges::in_value_result` stores. | ### Data members std::ranges::in\_value\_result::in ----------------------------------- | | | | | --- | --- | --- | | ``` [[no_unique_address]] I in; ``` | | | a value (that is supposed to be an iterator). std::ranges::out\_value\_result::value --------------------------------------- | | | | | --- | --- | --- | | ``` [[no_unique_address]] T value; ``` | | | a value (that is supposed to be a stored value). ### Member functions std::ranges::in\_value\_result::operator in\_value\_result<I2, T2> ------------------------------------------------------------------- | | | | | --- | --- | --- | | ``` template<class I2, class T2> requires convertible_to<const I&, I2> && convertible_to<const T&, T2> constexpr operator in_value_result<I2, T2>() const &; ``` | (1) | | | ``` template<class I2, class T2> requires convertible_to<I, I2> && convertible_to<T, T2> constexpr operator in_value_result<I2, T2>() &&; ``` | (2) | | Converts `*this` to the result by constructing every data member of the result from the corresponding member of `*this`. 1) Equivalent to `return {in, value};`. 2) Equivalent to `return {std::move(in), std::move(value)};`. ### Standard library The following standard library functions use `ranges::in_value_result` as the return type: | | | --- | | Algorithm functions | | fold\_left\_with\_iter | | fold\_left\_first\_with\_iter | ### Synopsis ``` namespace std::ranges { template<class I, class T> struct in_value_result { [[no_unique_address]] I in; [[no_unique_address]] T value; template<class I2, class T2> requires convertible_to<const I&, I2> && convertible_to<const T&, T2> constexpr operator in_value_result<I2, T2>() const & { return {in, value}; } template<class I2, class T2> requires convertible_to<I, I2> && convertible_to<T, T2> constexpr operator in_value_result<I2, T2>() && { return {std::move(in), std::move(value)}; } }; } ``` ### Notes Each standard library algorithm that uses this family of return types declares a new [alias type](../../../language/type_alias "cpp/language/type alias"), e.g. `using merge_result = in_in_out_result<I1, I2, O>;`. The names for such aliases are formed by adding the suffix "*`_result`*" to the algorithm's name. So, the return type of `std::ranges::merge` can be named as `std::ranges::merge_result`. Unlike `[std::pair](../../../utility/pair "cpp/utility/pair")` and `[std::tuple](../../../utility/tuple "cpp/utility/tuple")`, this class template has data members of meaningful names. ### Example ### See also | | | | --- | --- | | [pair](../../../utility/pair "cpp/utility/pair") | implements binary tuple, i.e. a pair of values (class template) | | [tuple](../../../utility/tuple "cpp/utility/tuple") (C++11) | implements fixed size container, which holds elements of possibly different types (class template) | cpp std::ranges::in_out_out_result std::ranges::in\_out\_out\_result ================================= | Defined in header `[<algorithm>](../../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | ``` template <class I, class O1, class O2> struct in_out_out_result; ``` | | (since C++20) | `ranges::in_out_out_result` is a class template that provides a way to store three iterators as a single unit. This class template has no base classes or declared members other than those shown below. Thus it is suitable for use with [structured bindings](../../../language/structured_binding "cpp/language/structured binding"). All special member functions of this class template are implicitly declared, which makes specializations be [aggregate classes](../../../language/aggregate_initialization "cpp/language/aggregate initialization"), and propagate triviality, potentially-throwing-ness, and constexpr-ness of corresponding operations on data members. ### Template parameters | | | | | --- | --- | --- | | I, O1, O2 | - | the types of the objects that the `ranges::in_out_out_result` stores. | ### Data members std::ranges::in\_out\_out\_result::in -------------------------------------- | | | | | --- | --- | --- | | ``` [[no_unique_address]] I in; ``` | | | a value (that is supposed to be an iterator). std::ranges::in\_out\_out\_result::out1 ---------------------------------------- | | | | | --- | --- | --- | | ``` [[no_unique_address]] O1 out1; ``` | | | a value (that is supposed to be an iterator). std::ranges::in\_out\_out\_result::out2 ---------------------------------------- | | | | | --- | --- | --- | | ``` [[no_unique_address]] O2 out2; ``` | | | a value (that is supposed to be an iterator). ### Member functions std::ranges::in\_out\_out\_result::operator in\_out\_out\_result<II, OO1, OO2> ------------------------------------------------------------------------------- | | | | | --- | --- | --- | | ``` template<class II, class OO1, class OO2> requires std::convertible_to<const I&, II> && std::convertible_to<const O1&, OO1> && std::convertible_to<const O2&, OO2> constexpr operator in_out_out_result<II, OO1, OO2>() const &; ``` | (1) | | | ``` template<class II, class OO1, class OO2> requires std::convertible_to<I, II> && std::convertible_to<O1, OO1> && std::convertible_to<O2, OO2> constexpr operator in_out_out_result<II, OO1, OO2>() &&; ``` | (2) | | Converts `*this` to the result by constructing every data member of the result from the corresponding member of `*this`. 1) Equivalent to `return {in, out1, out2};`. 2) Equivalent to `return {std::move(in), std::move(out1), std::move(out2)};`. ### Standard library The following standard library functions use `ranges::in_out_out_result` as the return type: | | | --- | | Algorithm functions | | [ranges::partition\_copy](../partition_copy "cpp/algorithm/ranges/partition copy") (C++20) | copies a range dividing the elements into two groups (niebloid) | ### Synopsis ``` namespace std::ranges { template<class I, class O1, class O2> struct in_out_out_result { [[no_unique_address]] I in; [[no_unique_address]] O1 out1; [[no_unique_address]] O2 out2; template<class II, class OO1, class OO2> requires std::convertible_to<const I&, II> && std::convertible_to<const O1&, OO1> && std::convertible_to<const O2&, OO2> constexpr operator in_out_out_result<II, OO1, OO2>() const & { return {in, out1, out2}; } template<class II, class OO1, class OO2> requires std::convertible_to<I, II> && std::convertible_to<O1, OO1> && std::convertible_to<O2, OO2> constexpr operator in_out_out_result<II, OO1, OO2>() && { return {std::move(in), std::move(out1), std::move(out2)}; } }; } ``` ### Notes Each standard library algorithm that uses this family of return types declares a new [alias type](../../../language/type_alias "cpp/language/type alias"), e.g. `using merge_result = in_in_out_result<I1, I2, O>;`. The names for such aliases are formed by adding the suffix "*`_result`*" to the algorithm's name. So, the return type of `std::ranges::merge` can be named as `std::ranges::merge_result`. Unlike `[std::pair](../../../utility/pair "cpp/utility/pair")` and `[std::tuple](../../../utility/tuple "cpp/utility/tuple")`, this class template has data members of meaningful names. ### Example ``` #include <algorithm> #include <array> #include <cctype> #include <iostream> #include <iterator> #include <ranges> #include <string_view> void print(std::string_view rem, auto first, auto last) { for (std::cout << rem << ": { "; first != last; ++first) std::cout << *first << ' '; std::cout << "}\n"; } int main() { constexpr std::string_view in{"TvEeNcStOoRr"}; std::array<char, in.size()> o1, o2; const auto result = std::ranges::partition_copy(in, o1.begin(), o2.begin(), [](char c){ return std::isupper(c); }); print("in", in.begin(), result.in); print("o1", o1.begin(), result.out1); print("o2", o2.begin(), result.out2); } ``` Output: ``` in: { T v E e N c S t O o R r } o1: { T E N S O R } o2: { v e c t o r } ``` ### See also | | | | --- | --- | | [pair](../../../utility/pair "cpp/utility/pair") | implements binary tuple, i.e. a pair of values (class template) | | [tuple](../../../utility/tuple "cpp/utility/tuple") (C++11) | implements fixed size container, which holds elements of possibly different types (class template) |
programming_docs
cpp std::ranges::in_found_result std::ranges::in\_found\_result ============================== | Defined in header `[<algorithm>](../../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | ``` template <class I> struct in_found_result; ``` | | (since C++20) | `ranges::in_found_result` is a class template that provides a way to store an iterator and a boolean flag as a single unit. This class template has no base classes or declared members other than those shown below. Thus it is suitable for use with [structured bindings](../../../language/structured_binding "cpp/language/structured binding"). All special member functions of this class template are implicitly declared, which makes specializations be [aggregate classes](../../../language/aggregate_initialization "cpp/language/aggregate initialization"), and propagate triviality, potentially-throwing-ness, and constexpr-ness of corresponding operations on data members. ### Template parameters | | | | | --- | --- | --- | | I | - | the type of the iterator that the `ranges::in_found_result` stores. | ### Data members std::ranges::in\_found\_result::in ----------------------------------- | | | | | --- | --- | --- | | ``` [[no_unique_address]] I in; ``` | | | a value (that is supposed to be an iterator). std::ranges::in\_found\_result::found -------------------------------------- | | | | | --- | --- | --- | | ``` bool found; ``` | | | a boolean flag (that may show whether an appropriate range can be found). ### Member functions std::ranges::in\_found\_result::operator in\_found\_result<I2> --------------------------------------------------------------- | | | | | --- | --- | --- | | ``` template<class I2> requires std::convertible_to<const I&, I2> constexpr operator in_found_result<I2>() const &; ``` | (1) | | | ``` template<class I2> requires std::convertible_to<I, I2> constexpr operator in_found_result<I2>() &&; ``` | (2) | | Converts `*this` to the result by constructing every data member of the result from the corresponding member of `*this`. 1) Equivalent to `return {in, found};`. 2) Equivalent to `return {std::move(in), found};`. ### Standard library The following standard library functions use `ranges::in_found_result` as the return type: | | | --- | | Algorithm functions | | [ranges::next\_permutation](../next_permutation "cpp/algorithm/ranges/next permutation") (C++20) | generates the next greater lexicographic permutation of a range of elements (niebloid) | | [ranges::prev\_permutation](../prev_permutation "cpp/algorithm/ranges/prev permutation") (C++20) | generates the next smaller lexicographic permutation of a range of elements (niebloid) | ### Synopsis ``` namespace std::ranges { template<class I> struct in_found_result { [[no_unique_address]] I in; bool found; template<class I2> requires std::convertible_to<const I&, I2> constexpr operator in_found_result<I2>() const & { return {in, found}; } template<class I2> requires std::convertible_to<I, I2> constexpr operator in_found_result<I2>() && { return {std::move(in), found}; } }; } ``` ### Notes Each standard library algorithm that uses this family of return types declares a new [alias type](../../../language/type_alias "cpp/language/type alias"), e.g. `using merge_result = in_in_out_result<I1, I2, O>;`. The names for such aliases are formed by adding the suffix "*`_result`*" to the algorithm's name. So, the return type of `std::ranges::merge` can be named as `std::ranges::merge_result`. Unlike `[std::pair](../../../utility/pair "cpp/utility/pair")` and `[std::tuple](../../../utility/tuple "cpp/utility/tuple")`, this class template has data members of meaningful names. ### Example ``` #include <algorithm> #include <iostream> #include <iterator> #include <ranges> int main() { int v[] { 1, 2, 3 }; const auto result = std::ranges::next_permutation(v); std::ranges::for_each(std::cbegin(v), result.in, [](int e){std::cout << e << ' ';}); std::cout << std::boolalpha << "\n" "result.found: " << result.found << '\n'; } ``` Output: ``` 1 3 2 result.found = true ``` ### See also | | | | --- | --- | | [pair](../../../utility/pair "cpp/utility/pair") | implements binary tuple, i.e. a pair of values (class template) | | [tuple](../../../utility/tuple "cpp/utility/tuple") (C++11) | implements fixed size container, which holds elements of possibly different types (class template) | cpp std::ranges::in_out_result std::ranges::in\_out\_result ============================ | Defined in header `[<algorithm>](../../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | ``` template <class I, class O> struct in_out_result; ``` | | (since C++20) | `ranges::in_out_result` is a class template that provides a way to store two iterators as a single unit. This class template has no base classes or declared members other than those shown below. Thus it is suitable for use with [structured bindings](../../../language/structured_binding "cpp/language/structured binding"). All special member functions of this class template are implicitly declared, which makes specializations be [aggregate classes](../../../language/aggregate_initialization "cpp/language/aggregate initialization"), and propagate triviality, potentially-throwing-ness, and constexpr-ness of corresponding operations on data members. ### Template parameters | | | | | --- | --- | --- | | I, O | - | the types of the objects that the `ranges::in_out_result` stores. | ### Data members std::ranges::in\_out\_result::in --------------------------------- | | | | | --- | --- | --- | | ``` [[no_unique_address]] I in; ``` | | | a value (that is supposed to be an iterator). std::ranges::in\_out\_result::out ---------------------------------- | | | | | --- | --- | --- | | ``` [[no_unique_address]] O out; ``` | | | a value (that is supposed to be an iterator). ### Member functions std::ranges::in\_out\_result::operator in\_out\_result<I2, O2> --------------------------------------------------------------- | | | | | --- | --- | --- | | ``` template<class I2, class O2> requires std::convertible_to<const I&, I2> && std::convertible_to<const O&, O2> constexpr operator in_out_result<I2, O2>() const &; ``` | (1) | | | ``` template<class I2, class O2> requires std::convertible_to<I, I2> && std::convertible_to<O, O2> constexpr operator in_out_result<I2, O2>() &&; ``` | (2) | | Converts `*this` to the result by constructing every data member of the result from the corresponding member of `*this`. 1) Equivalent to `return {in, out};`. 2) Equivalent to `return {std::move(in), std::move(out)};`. ### Standard library The following standard library functions use `ranges::in_out_result` as the return type: | | | --- | | Algorithm functions | | [ranges::copyranges::copy\_if](../copy "cpp/algorithm/ranges/copy") (C++20)(C++20) | copies a range of elements to a new location (niebloid) | | [ranges::copy\_n](../copy_n "cpp/algorithm/ranges/copy n") (C++20) | copies a number of elements to a new location (niebloid) | | [ranges::copy\_backward](../copy_backward "cpp/algorithm/ranges/copy backward") (C++20) | copies a range of elements in backwards order (niebloid) | | [ranges::move](../move "cpp/algorithm/ranges/move") (C++20) | moves a range of elements to a new location (niebloid) | | [ranges::move\_backward](../move_backward "cpp/algorithm/ranges/move backward") (C++20) | moves a range of elements to a new location in backwards order (niebloid) | | [ranges::transform](../transform "cpp/algorithm/ranges/transform") (C++20) | applies a function to a range of elements (niebloid) | | [ranges::replace\_copyranges::replace\_copy\_if](../replace_copy "cpp/algorithm/ranges/replace copy") (C++20)(C++20) | copies a range, replacing elements satisfying specific criteria with another value (niebloid) | | [ranges::remove\_copyranges::remove\_copy\_if](../remove_copy "cpp/algorithm/ranges/remove copy") (C++20)(C++20) | copies a range of elements omitting those that satisfy specific criteria (niebloid) | | [ranges::unique\_copy](../unique_copy "cpp/algorithm/ranges/unique copy") (C++20) | creates a copy of some range of elements that contains no consecutive duplicates (niebloid) | | [ranges::reverse\_copy](../reverse_copy "cpp/algorithm/ranges/reverse copy") (C++20) | creates a copy of a range that is reversed (niebloid) | | [ranges::rotate\_copy](../rotate_copy "cpp/algorithm/ranges/rotate copy") (C++20) | copies and rotate a range of elements (niebloid) | | [ranges::partial\_sort\_copy](../partial_sort_copy "cpp/algorithm/ranges/partial sort copy") (C++20) | copies and partially sorts a range of elements (niebloid) | | [ranges::set\_difference](../set_difference "cpp/algorithm/ranges/set difference") (C++20) | computes the difference between two sets (niebloid) | | Memory functions | | [ranges::uninitialized\_copy](../../../memory/ranges/uninitialized_copy "cpp/memory/ranges/uninitialized copy") (C++20) | copies a range of objects to an uninitialized area of memory (niebloid) | | [ranges::uninitialized\_copy\_n](../../../memory/ranges/uninitialized_copy_n "cpp/memory/ranges/uninitialized copy n") (C++20) | copies a number of objects to an uninitialized area of memory (niebloid) | | [ranges::uninitialized\_move](../../../memory/ranges/uninitialized_move "cpp/memory/ranges/uninitialized move") (C++20) | moves a range of objects to an uninitialized area of memory (niebloid) | | [ranges::uninitialized\_move\_n](../../../memory/ranges/uninitialized_move_n "cpp/memory/ranges/uninitialized move n") (C++20) | moves a number of objects to an uninitialized area of memory (niebloid) | ### Synopsis ``` namespace std::ranges { template<class I, class O> struct in_out_result { [[no_unique_address]] I in; [[no_unique_address]] O out; template<class I2, class O2> requires std::convertible_to<const I&, I2> && std::convertible_to<const O&, O2> constexpr operator in_out_result<I2, O2>() const & { return {in, out}; } template<class I2, class O2> requires std::convertible_to<I, I2> && std::convertible_to<O, O2> constexpr operator in_out_result<I2, O2>() && { return {std::move(in), std::move(out)}; } }; } ``` ### Notes Each standard library algorithm that uses this family of return types declares a new [alias type](../../../language/type_alias "cpp/language/type alias"), e.g. `using merge_result = in_in_out_result<I1, I2, O>;`. The names for such aliases are formed by adding the suffix "*`_result`*" to the algorithm's name. So, the return type of `std::ranges::merge` can be named as `std::ranges::merge_result`. Unlike `[std::pair](../../../utility/pair "cpp/utility/pair")` and `[std::tuple](../../../utility/tuple "cpp/utility/tuple")`, this class template has data members of meaningful names. ### Example ``` #include <algorithm> #include <array> #include <cctype> #include <iostream> #include <ranges> int main() { constexpr char in[] = "transform" "\n"; std::array<char, sizeof(in)> out; const auto result = std::ranges::transform(in, out.begin(), [](char c) { return std::toupper(c); }); auto print = [](char c) { std::cout << c; }; std::ranges::for_each(std::cbegin(in), result.in, print); std::ranges::for_each(out.cbegin(), result.out, print); } ``` Output: ``` transform TRANSFORM ``` ### See also | | | | --- | --- | | [pair](../../../utility/pair "cpp/utility/pair") | implements binary tuple, i.e. a pair of values (class template) | | [tuple](../../../utility/tuple "cpp/utility/tuple") (C++11) | implements fixed size container, which holds elements of possibly different types (class template) | cpp std::ranges::in_in_out_result std::ranges::in\_in\_out\_result ================================ | Defined in header `[<algorithm>](../../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | ``` template <class I1, class I2, class O> struct in_in_out_result; ``` | | (since C++20) | `ranges::in_in_out_result` is a class template that provides a way to store three iterators as a single unit. This class template has no base classes or declared members other than those shown below. Thus it is suitable for use with [structured bindings](../../../language/structured_binding "cpp/language/structured binding"). All special member functions of this class template are implicitly declared, which makes specializations be [aggregate classes](../../../language/aggregate_initialization "cpp/language/aggregate initialization"), and propagate triviality, potentially-throwing-ness, and constexpr-ness of corresponding operations on data members. ### Template parameters | | | | | --- | --- | --- | | I1, I2, O | - | the types of the iterators that the `ranges::in_in_out_result` stores. | ### Data members std::ranges::in\_in\_out\_result::in1 -------------------------------------- | | | | | --- | --- | --- | | ``` [[no_unique_address]] I1 in1; ``` | | | a value (that is supposed to be an iterator). std::ranges::in\_in\_out\_result::in2 -------------------------------------- | | | | | --- | --- | --- | | ``` [[no_unique_address]] I2 in2; ``` | | | a value (that is supposed to be an iterator). std::ranges::in\_in\_out\_result::out -------------------------------------- | | | | | --- | --- | --- | | ``` [[no_unique_address]] O out; ``` | | | a value (that is supposed to be an iterator). ### Member functions std::ranges::in\_in\_out\_result::operator in\_in\_out\_result<II1, II2, OO> ----------------------------------------------------------------------------- | | | | | --- | --- | --- | | ``` template<class II1, class II2, class OO> requires std::convertible_to<const I1&, II1> && std::convertible_to<const I2&, II2> && std::convertible_to<const O&, OO> constexpr operator in_in_out_result<II1, II2, OO>() const &; ``` | (1) | | | ``` template<class II1, class II2, class OO> requires std::convertible_to<I1, II1> && std::convertible_to<I2, II2> && std::convertible_to<O, OO> constexpr operator in_in_out_result<II1, II2, OO>() &&; ``` | (2) | | Converts `*this` to the result by constructing every data member of the result from the corresponding member of `*this`. 1) Equivalent to `return {in1, in2, out};`. 2) Equivalent to `return {std::move(in1), std::move(in2), std::move(out)};`. ### Standard library The following standard library functions use `ranges::in_in_out_result` as the return type: | | | --- | | Algorithm functions | | [ranges::transform](../transform "cpp/algorithm/ranges/transform") (C++20) | applies a function to a range of elements (niebloid) | | [ranges::merge](../merge "cpp/algorithm/ranges/merge") (C++20) | merges two sorted ranges (niebloid) | | [ranges::set\_union](../set_union "cpp/algorithm/ranges/set union") (C++20) | computes the union of two sets (niebloid) | | [ranges::set\_intersection](../set_intersection "cpp/algorithm/ranges/set intersection") (C++20) | computes the intersection of two sets (niebloid) | | [ranges::set\_symmetric\_difference](../set_symmetric_difference "cpp/algorithm/ranges/set symmetric difference") (C++20) | computes the symmetric difference between two sets (niebloid) | ### Synopsis ``` namespace std::ranges { template<class I1, class I2, class O> struct in_in_out_result { [[no_unique_address]] I1 in1; [[no_unique_address]] I2 in2; [[no_unique_address]] O out; template<class II1, class II2, class OO> requires std::convertible_to<const I1&, II1> && std::convertible_to<const I2&, II2> && std::convertible_to<const O&, OO> constexpr operator in_in_out_result<II1, II2, OO>() const & { return {in1, in2, out}; } template<class II1, class II2, class OO> requires std::convertible_to<I1, II1> && std::convertible_to<I2, II2> && std::convertible_to<O, OO> constexpr operator in_in_out_result<II1, II2, OO>() && { return {std::move(in1), std::move(in2), std::move(out)}; } }; } ``` ### Notes Each standard library algorithm that uses this family of return types declares a new [alias type](../../../language/type_alias "cpp/language/type alias"), e.g. `using merge_result = in_in_out_result<I1, I2, O>;`. The names for such aliases are formed by adding the suffix "*`_result`*" to the algorithm's name. So, the return type of `std::ranges::merge` can be named as `std::ranges::merge_result`. Unlike `[std::pair](../../../utility/pair "cpp/utility/pair")` and `[std::tuple](../../../utility/tuple "cpp/utility/tuple")`, this class template has data members of meaningful names. ### Example ``` #include <algorithm> #include <array> #include <iostream> #include <iterator> #include <ranges> void print(auto rem, auto first, auto last) { for (std::cout << rem << ": "; first != last; ++first) std::cout << *first << ' '; std::cout << '\n'; } int main() { constexpr static auto in1 = {1, 2, 3, 4, 5, 5}; constexpr static auto in2 = {3, 4, 5, 6, 7}; std::array<int, std::size(in1) + std::size(in2)> out; const auto result = std::ranges::merge(in1, in2, out.begin()); print("in1", in1.begin(), result.in1); print("in2", in2.begin(), result.in2); print("out", out.begin(), result.out); } ``` Output: ``` in1: 1 2 3 4 5 5 in2: 3 4 5 6 7 out: 1 2 3 3 4 4 5 5 5 6 7 ``` ### See also | | | | --- | --- | | [pair](../../../utility/pair "cpp/utility/pair") | implements binary tuple, i.e. a pair of values (class template) | | [tuple](../../../utility/tuple "cpp/utility/tuple") (C++11) | implements fixed size container, which holds elements of possibly different types (class template) | cpp std::ranges::out_value_result std::ranges::out\_value\_result =============================== | Defined in header `[<algorithm>](../../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | ``` template<class O, class T> struct out_value_result; ``` | | (since C++23) | `ranges::out_value_result` is a class template that provides a way to store an iterator and a value as a single unit. This class template has no base classes or declared members other than those shown below. Thus it is suitable for use with [structured bindings](../../../language/structured_binding "cpp/language/structured binding"). All special member functions of this class template are implicitly declared, which makes specializations be [aggregate classes](../../../language/aggregate_initialization "cpp/language/aggregate initialization"), and propagate triviality, potentially-throwing-ness, and constexpr-ness of corresponding operations on data members. ### Template parameters | | | | | --- | --- | --- | | O, T | - | the types of the objects that the `ranges::out_value_result` stores. | ### Data members std::ranges::out\_value\_result::out ------------------------------------- | | | | | --- | --- | --- | | ``` [[no_unique_address]] O out; ``` | | | a value (that is supposed to be an iterator). std::ranges::out\_value\_result::value --------------------------------------- | | | | | --- | --- | --- | | ``` [[no_unique_address]] T value; ``` | | | a value (that is supposed to be a stored value). ### Member functions std::ranges::out\_value\_result::operator out\_value\_result<O2, T2> --------------------------------------------------------------------- | | | | | --- | --- | --- | | ``` template<class O2, class T2> requires convertible_to<const O&, O2> && convertible_to<const T&, T2> constexpr operator out_value_result<O2, T2>() const &; ``` | (1) | | | ``` template<class O2, class T2> requires convertible_to<O, O2> && convertible_to<T, T2> constexpr operator out_value_result<O2, T2>() &&; ``` | (2) | | Converts `*this` to the result by constructing every data member of the result from the corresponding member of `*this`. 1) Equivalent to `return {out, value};`. 2) Equivalent to `return {std::move(out), std::move(value)};`. ### Standard library The following standard library functions use `ranges::out_value_result` as the return type: | | | --- | | Algorithm functions | | [ranges::iota](../iota "cpp/algorithm/ranges/iota") (C++23) | fills a range with successive increments of the starting value (niebloid) | ### Synopsis ``` namespace std::ranges { template<class O, class T> struct out_value_result { [[no_unique_address]] O out; [[no_unique_address]] T value; template<class O2, class T2> requires convertible_to<const O&, O2> && convertible_to<const T&, T2> constexpr operator out_value_result<O2, T2>() const & { return {out, value}; } template<class O2, class T2> requires convertible_to<O, O2> && convertible_to<T, T2> constexpr operator out_value_result<O2, T2>() && { return {std::move(out), std::move(value)}; } }; } ``` ### Notes Each standard library algorithm that uses this family of return types declares a new [alias type](../../../language/type_alias "cpp/language/type alias"), e.g. `using merge_result = in_in_out_result<I1, I2, O>;`. The names for such aliases are formed by adding the suffix "*`_result`*" to the algorithm's name. So, the return type of `std::ranges::merge` can be named as `std::ranges::merge_result`. Unlike `[std::pair](../../../utility/pair "cpp/utility/pair")` and `[std::tuple](../../../utility/tuple "cpp/utility/tuple")`, this class template has data members of meaningful names. ### Example ``` #include <algorithm> #include <array> #include <cassert> #include <ranges> #include <numeric> int main() { std::array<int, 4> a; constexpr std::array expected{2,3,4,5}; const auto result = std::ranges::iota(a, 2); assert(std::ranges::distance(a.cbegin(), result.out) == 4); assert(result.value == 6); assert(a == expected); } ``` ### See also | | | | --- | --- | | [pair](../../../utility/pair "cpp/utility/pair") | implements binary tuple, i.e. a pair of values (class template) | | [tuple](../../../utility/tuple "cpp/utility/tuple") (C++11) | implements fixed size container, which holds elements of possibly different types (class template) |
programming_docs
cpp std::ranges::in_fun_result std::ranges::in\_fun\_result ============================ | Defined in header `[<algorithm>](../../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | ``` template <class I, class F> struct in_fun_result; ``` | | (since C++20) | `ranges::in_fun_result` is a class template that provides a way to store an iterator and a function object as a single unit. This class template has no base classes or declared members other than those shown below. Thus it is suitable for use with [structured bindings](../../../language/structured_binding "cpp/language/structured binding"). All special member functions of this class template are implicitly declared, which makes specializations be [aggregate classes](../../../language/aggregate_initialization "cpp/language/aggregate initialization"), and propagate triviality, potentially-throwing-ness, and constexpr-ness of corresponding operations on data members. ### Template parameters | | | | | --- | --- | --- | | I | - | the type of the iterator that the `ranges::in_fun_result` stores. | | F | - | the type of the function object that the `ranges::in_fun_result` stores. | ### Data members std::ranges::in\_fun\_result::in --------------------------------- | | | | | --- | --- | --- | | ``` [[no_unique_address]] I in; ``` | | | a value (that is supposed to be an iterator). std::ranges::in\_fun\_result::fun ---------------------------------- | | | | | --- | --- | --- | | ``` [[no_unique_address]] F fun; ``` | | | a value (that is supposed to be a function object). ### Member functions std::ranges::in\_fun\_result::operator in\_fun\_result<I2, F2> --------------------------------------------------------------- | | | | | --- | --- | --- | | ``` template<class I2, class F2> requires std::convertible_to<const I&, I2> && std::convertible_to<const F&, F2> constexpr operator in_fun_result<I2, F2>() const &; ``` | (1) | | | ``` template<class I2, class F2> requires std::convertible_to<I, I2> && std::convertible_to<F, F2> constexpr operator in_fun_result<I2, F2>() &&; ``` | (2) | | Converts `*this` to the result by constructing every data member of the result from the corresponding member of `*this`. 1) Equivalent to `return {in, fun};`. 2) Equivalent to `return {std::move(in), std::move(fun)};`. ### Standard library The following standard library functions use `ranges::in_fun_result` as the return type: | | | --- | | Algorithm functions | | [ranges::for\_each](../for_each "cpp/algorithm/ranges/for each") (C++20) | applies a function to a range of elements (niebloid) | | [ranges::for\_each\_n](../for_each_n "cpp/algorithm/ranges/for each n") (C++20) | applies a function object to the first n elements of a sequence (niebloid) | ### Synopsis ``` namespace std::ranges { template<class I, class F> struct in_fun_result { [[no_unique_address]] I in; [[no_unique_address]] F fun; template<class I2, class F2> requires std::convertible_to<const I&, I2> && std::convertible_to<const F&, F2> constexpr operator in_fun_result<I2, F2>() const & { return {in, fun}; } template<class I2, class F2> requires std::convertible_to<I, I2> && std::convertible_to<F, F2> constexpr operator in_fun_result<I2, F2>() && { return {std::move(in), std::move(fun)}; } }; } ``` ### Notes Each standard library algorithm that uses this family of return types declares a new [alias type](../../../language/type_alias "cpp/language/type alias"), e.g. `using merge_result = in_in_out_result<I1, I2, O>;`. The names for such aliases are formed by adding the suffix "*`_result`*" to the algorithm's name. So, the return type of `std::ranges::merge` can be named as `std::ranges::merge_result`. Unlike `[std::pair](../../../utility/pair "cpp/utility/pair")` and `[std::tuple](../../../utility/tuple "cpp/utility/tuple")`, this class template has data members of meaningful names. ### Example ``` #include <algorithm> #include <iostream> #include <iterator> #include <ranges> int main() { int v[] { 1, 2, 3 }; const auto [last, negate] = std::ranges::for_each_n(v, std::size(v), [](int& x) { return x = -x; }); const auto result = std::ranges::for_each(std::cbegin(v), last, [](int x) { std::cout << x << ' '; }); std::cout << "│ "; std::ranges::for_each(v, negate); std::ranges::for_each(v, result.fun); std::cout << '\n'; } ``` Output: ``` -1 -2 -3 │ 1 2 3 ``` ### See also | | | | --- | --- | | [pair](../../../utility/pair "cpp/utility/pair") | implements binary tuple, i.e. a pair of values (class template) | | [tuple](../../../utility/tuple "cpp/utility/tuple") (C++11) | implements fixed size container, which holds elements of possibly different types (class template) | cpp std::ranges::in_in_result std::ranges::in\_in\_result =========================== | Defined in header `[<algorithm>](../../../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | ``` template<class I1, class I2> struct in_in_result; ``` | | (since C++20) | `ranges::in_in_result` is a class template that provides a way to store two iterators as a single unit. This class template has no base classes or declared members other than those shown below. Thus it is suitable for use with [structured bindings](../../../language/structured_binding "cpp/language/structured binding"). All special member functions of this class template are implicitly declared, which makes specializations be [aggregate classes](../../../language/aggregate_initialization "cpp/language/aggregate initialization"), and propagate triviality, potentially-throwing-ness, and constexpr-ness of corresponding operations on data members. ### Template parameters | | | | | --- | --- | --- | | I1, I2 | - | the types of the iterators that the `ranges::in_in_result` stores. | ### Data members std::ranges::in\_in\_result::in1 --------------------------------- | | | | | --- | --- | --- | | ``` [[no_unique_address]] I1 in1; ``` | | | a value (that is supposed to be an iterator). std::ranges::in\_in\_result::in2 --------------------------------- | | | | | --- | --- | --- | | ``` [[no_unique_address]] I2 in2; ``` | | | a value (that is supposed to be an iterator). ### Member functions std::ranges::in\_in\_result::operator in\_in\_result<II1, II2> --------------------------------------------------------------- | | | | | --- | --- | --- | | ``` template<class II1, class II2> requires std::convertible_to<const I1&, II1> && std::convertible_to<const I2&, II2> constexpr operator in_in_result<II1, II2>() const &; ``` | (1) | | | ``` template<class II1, class II2> requires std::convertible_to<I1, II1> && std::convertible_to<I2, II2> constexpr operator in_in_result<II1, II2>() &&; ``` | (2) | | Converts `*this` to the result by constructing every data member of the result from the corresponding member of `*this`. 1) Equivalent to `return {in1, in2};`. 2) Equivalent to `return {std::move(in1), std::move(in2)};`. ### Standard library The following standard library functions use `ranges::in_in_result` as the return type: | | | --- | | Algorithm functions | | [ranges::mismatch](../mismatch "cpp/algorithm/ranges/mismatch") (C++20) | finds the first position where two ranges differ (niebloid) | | [ranges::swap\_ranges](../swap_ranges "cpp/algorithm/ranges/swap ranges") (C++20) | swaps two ranges of elements (niebloid) | ### Synopsis ``` namespace std::ranges { template<class I1, class I2> struct in_in_result { [[no_unique_address]] I1 in1; [[no_unique_address]] I2 in2; template<class II1, class II2> requires std::convertible_to<const I1&, II1> && std::convertible_to<const I2&, II2> constexpr operator in_in_result<II1, II2>() const & { return {in1, in2}; } template<class II1, class II2> requires std::convertible_to<I1, II1> && std::convertible_to<I2, II2> constexpr operator in_in_result<II1, II2>() && { return {std::move(in1), std::move(in2)}; } }; } ``` ### Notes Each standard library algorithm that uses this family of return types declares a new [alias type](../../../language/type_alias "cpp/language/type alias"), e.g. `using merge_result = in_in_out_result<I1, I2, O>;`. The names for such aliases are formed by adding the suffix "*`_result`*" to the algorithm's name. So, the return type of `std::ranges::merge` can be named as `std::ranges::merge_result`. Unlike `[std::pair](../../../utility/pair "cpp/utility/pair")` and `[std::tuple](../../../utility/tuple "cpp/utility/tuple")`, this class template has data members of meaningful names. ### Example ``` #include <algorithm> #include <iostream> #include <ranges> int main() { constexpr static auto in1 = {1, 2, 3, 4}; constexpr static auto in2 = {1, 2, 4, 5}; constexpr auto result { std::ranges::mismatch(in1, in2) }; static_assert(2 == std::ranges::distance(in1.begin(), result.in1)); static_assert(2 == std::ranges::distance(in2.begin(), result.in2)); } ``` ### See also | | | | --- | --- | | [pair](../../../utility/pair "cpp/utility/pair") | implements binary tuple, i.e. a pair of values (class template) | | [tuple](../../../utility/tuple "cpp/utility/tuple") (C++11) | implements fixed size container, which holds elements of possibly different types (class template) | cpp std::regex_replace std::regex\_replace =================== | Defined in header `[<regex>](../header/regex "cpp/header/regex")` | | | | --- | --- | --- | | ``` template< class OutputIt, class BidirIt, class Traits, class CharT, class STraits, class SAlloc > OutputIt regex_replace( OutputIt out, BidirIt first, BidirIt last, const std::basic_regex<CharT,Traits>& re, const std::basic_string<CharT,STraits,SAlloc>& fmt, std::regex_constants::match_flag_type flags = std::regex_constants::match_default ); ``` | (1) | (since C++11) | | ``` template< class OutputIt, class BidirIt, class Traits, class CharT > OutputIt regex_replace( OutputIt out, BidirIt first, BidirIt last, const std::basic_regex<CharT,Traits>& re, const CharT* fmt, std::regex_constants::match_flag_type flags = std::regex_constants::match_default ); ``` | (2) | (since C++11) | | ``` template< class Traits, class CharT, class STraits, class SAlloc, class FTraits, class FAlloc > std::basic_string<CharT,STraits,SAlloc> regex_replace( const std::basic_string<CharT,STraits,SAlloc>& s, const std::basic_regex<CharT,Traits>& re, const std::basic_string<CharT,FTraits,FAlloc>& fmt, std::regex_constants::match_flag_type flags = std::regex_constants::match_default ); ``` | (3) | (since C++11) | | ``` template< class Traits, class CharT, class STraits, class SAlloc > std::basic_string<CharT,STraits,SAlloc> regex_replace( const std::basic_string<CharT,STraits,SAlloc>& s, const std::basic_regex<CharT,Traits>& re, const CharT* fmt, std::regex_constants::match_flag_type flags = std::regex_constants::match_default ); ``` | (4) | (since C++11) | | ``` template< class Traits, class CharT, class STraits, class SAlloc > std::basic_string<CharT> regex_replace( const CharT* s, const std::basic_regex<CharT,Traits>& re, const std::basic_string<CharT,STraits,SAlloc>& fmt, std::regex_constants::match_flag_type flags = std::regex_constants::match_default ); ``` | (5) | (since C++11) | | ``` template< class Traits, class CharT > std::basic_string<CharT> regex_replace( const CharT* s, const std::basic_regex<CharT,Traits>& re, const CharT* fmt, std::regex_constants::match_flag_type flags = std::regex_constants::match_default ); ``` | (6) | (since C++11) | `regex_replace` uses a regular expression to perform substitution on a sequence of characters: 1) Copies characters in the range `[first,last)` to `out`, replacing any sequences that match `re` with characters formatted by `fmt`. In other words: * Constructs a `[std::regex\_iterator](regex_iterator "cpp/regex/regex iterator")` object `i` as if by `[std::regex\_iterator](http://en.cppreference.com/w/cpp/regex/regex_iterator)<BidirIt, CharT, traits> i(first, last, re, flags)`, and uses it to step through every match of `re` within the sequence `[first,last)`. * For each such match `m`, copies the non-matched subsequence ([`m.prefix()`](match_results/prefix "cpp/regex/match results/prefix")) into `out` as if by `out = [std::copy](http://en.cppreference.com/w/cpp/algorithm/copy)(m.prefix().first, m.prefix().second, out)` and then replaces the matched subsequence with the formatted replacement string as if by calling [`out = m.format(out, fmt, flags)`](match_results/format "cpp/regex/match results/format"). * When no more matches are found, copies the remaining non-matched characters to `out` as if by `out = [std::copy](http://en.cppreference.com/w/cpp/algorithm/copy)(last_m.suffix().first, last_m.suffix().second, out)` where `last_m` is a copy of the last match found. * If there are no matches, copies the entire sequence into `out` as-is, by `out = [std::copy](http://en.cppreference.com/w/cpp/algorithm/copy)(first, last, out)` * If `flags` contains `[std::regex\_constants::format\_no\_copy](match_flag_type "cpp/regex/match flag type")`, the non-matched subsequences are not copied into `out`. * If `flags` contains `[std::regex\_constants::format\_first\_only](match_flag_type "cpp/regex/match flag type")`, only the first match is replaced. 2) same as 1), but the formatted replacement is performed as if by calling [`out = m.format(out, fmt, fmt + char_traits<charT>::length(fmt), flags)`](match_results/format "cpp/regex/match results/format") 3-4) Constructs an empty string `result` of type `[std::basic\_string](http://en.cppreference.com/w/cpp/string/basic_string)<CharT, ST, SA>` and calls `std::regex\_replace([std::back\_inserter](http://en.cppreference.com/w/cpp/iterator/back_inserter)(result), s.begin(), s.end(), re, fmt, flags)`. 5-6) Constructs an empty string `result` of type `[std::basic\_string](http://en.cppreference.com/w/cpp/string/basic_string)<CharT>` and calls `std::regex\_replace([std::back\_inserter](http://en.cppreference.com/w/cpp/iterator/back_inserter)(result), s, s + [std::char\_traits](http://en.cppreference.com/w/cpp/string/char_traits)<CharT>::length(s), re, fmt, flags)`. ### Parameters | | | | | --- | --- | --- | | first, last | - | the input character sequence, represented as a pair of iterators | | s | - | the input character sequence, represented as `[std::basic\_string](../string/basic_string "cpp/string/basic string")` or character array | | re | - | the `[std::basic\_regex](basic_regex "cpp/regex/basic regex")` that will be matched against the input sequence | | flags | - | the match flags of type `[std::regex\_constants::match\_flag\_type](match_flag_type "cpp/regex/match flag type")` | | fmt | - | the regex replacement format string, exact syntax depends on the value of `flags` | | out | - | output iterator to store the result of the replacement | | Type requirements | | -`OutputIt` must meet the requirements of [LegacyOutputIterator](../named_req/outputiterator "cpp/named req/OutputIterator"). | | -`BidirIt` must meet the requirements of [LegacyBidirectionalIterator](../named_req/bidirectionaliterator "cpp/named req/BidirectionalIterator"). | ### Return value 1-2) Returns a copy of the output iterator `out` after all the insertions. 3-6) Returns the string `result` which contains the output. ### Exceptions May throw `[std::regex\_error](regex_error "cpp/regex/regex error")` to indicate an [error condition](error_type "cpp/regex/error type"). ### Example ``` #include <iostream> #include <iterator> #include <regex> #include <string> int main() { std::string text = "Quick brown fox"; std::regex vowel_re("a|e|i|o|u"); // write the results to an output iterator std::regex_replace(std::ostreambuf_iterator<char>(std::cout), text.begin(), text.end(), vowel_re, "*"); // construct a string holding the results std::cout << '\n' << std::regex_replace(text, vowel_re, "[$&]") << '\n'; } ``` Output: ``` Q**ck br*wn f*x Q[u][i]ck br[o]wn f[o]x ``` ### See also | | | | --- | --- | | [regex\_search](regex_search "cpp/regex/regex search") (C++11) | attempts to match a regular expression to any part of a character sequence (function template) | | [match\_flag\_type](match_flag_type "cpp/regex/match flag type") (C++11) | options specific to matching (typedef) | | [replace](../string/basic_string/replace "cpp/string/basic string/replace") | replaces specified portion of a string (public member function of `std::basic_string<CharT,Traits,Allocator>`) | cpp std::regex_token_iterator std::regex\_token\_iterator =========================== | Defined in header `[<regex>](../header/regex "cpp/header/regex")` | | | | --- | --- | --- | | ``` template< class BidirIt, class CharT = typename std::iterator_traits<BidirIt>::value_type, class Traits = std::regex_traits<CharT> > class regex_token_iterator ``` | | (since C++11) | `std::regex_token_iterator` is a read-only [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator") that accesses the individual sub-matches of every match of a regular expression within the underlying character sequence. It can also be used to access the parts of the sequence that were not matched by the given regular expression (e.g. as a tokenizer). On construction, it constructs an `[std::regex\_iterator](regex_iterator "cpp/regex/regex iterator")` and on every increment it steps through the requested sub-matches from the current match\_results, incrementing the underlying `regex_iterator` when incrementing away from the last submatch. The default-constructed `std::regex_token_iterator` is the end-of-sequence iterator. When a valid `std::regex_token_iterator` is incremented after reaching the last submatch of the last match, it becomes equal to the end-of-sequence iterator. Dereferencing or incrementing it further invokes undefined behavior. Just before becoming the end-of-sequence iterator, a `std::regex_token_iterator` may become a *suffix iterator*, if the index `-1` (non-matched fragment) appears in the list of the requested submatch indexes. Such iterator, if dereferenced, returns a match\_results corresponding to the sequence of characters between the last match and the end of sequence. A typical implementation of `std::regex_token_iterator` holds the underlying `[std::regex\_iterator](regex_iterator "cpp/regex/regex iterator")`, a container (e.g. `[std::vector](http://en.cppreference.com/w/cpp/container/vector)<int>`) of the requested submatch indexes, the internal counter equal to the index of the submatch, a pointer to `[std::sub\_match](sub_match "cpp/regex/sub match")`, pointing at the current submatch of the current match, and a `[std::match\_results](match_results "cpp/regex/match results")` object containing the last non-matched character sequence (used in tokenizer mode). ### Type requirements | | | --- | | -`BidirIt` must meet the requirements of [LegacyBidirectionalIterator](../named_req/bidirectionaliterator "cpp/named req/BidirectionalIterator"). | ### Specializations Several specializations for common character sequence types are defined: | Defined in header `[<regex>](../header/regex "cpp/header/regex")` | | --- | | Type | Definition | | `cregex_token_iterator` | `regex_token_iterator<const char*>` | | `wcregex_token_iterator` | `regex_token_iterator<const wchar_t*>` | | `sregex_token_iterator` | `regex_token_iterator<std::string::const_iterator>` | | `wsregex_token_iterator` | `regex_token_iterator<std::wstring::const_iterator>` | ### Member types | Member type | Definition | | --- | --- | | `value_type` | `[std::sub\_match](http://en.cppreference.com/w/cpp/regex/sub_match)<BidirIt>` | | `difference_type` | `[std::ptrdiff\_t](../types/ptrdiff_t "cpp/types/ptrdiff t")` | | `pointer` | `const value_type*` | | `reference` | `const value_type&` | | `iterator_category` | `[std::forward\_iterator\_tag](../iterator/iterator_tags "cpp/iterator/iterator tags")` | | `regex_type` | `basic_regex<CharT, Traits>` | ### Member functions | | | | --- | --- | | [(constructor)](regex_token_iterator/regex_token_iterator "cpp/regex/regex token iterator/regex token iterator") | constructs a new `regex_token_iterator` (public member function) | | (destructor) (implicitly declared) | destructs a `regex_token_iterator`, including the cached value (public member function) | | [operator=](regex_token_iterator/operator= "cpp/regex/regex token iterator/operator=") | assigns contents (public member function) | | [operator==operator!=](regex_token_iterator/operator_cmp "cpp/regex/regex token iterator/operator cmp") (removed in C++20) | compares two `regex_token_iterator`s (public member function) | | [operator\*operator->](regex_token_iterator/operator* "cpp/regex/regex token iterator/operator*") | accesses current submatch (public member function) | | [operator++operator++(int)](regex_token_iterator/operator_arith "cpp/regex/regex token iterator/operator arith") | advances the iterator to the next submatch (public member function) | ### Notes It is the programmer's responsibility to ensure that the `[std::basic\_regex](basic_regex "cpp/regex/basic regex")` object passed to the iterator's constructor outlives the iterator. Because the iterator stores a `[std::regex\_iterator](regex_iterator "cpp/regex/regex iterator")` which stores a pointer to the regex, incrementing the iterator after the regex was destroyed results in undefined behavior. ### Example ``` #include <fstream> #include <iostream> #include <algorithm> #include <iterator> #include <regex> int main() { // Tokenization (non-matched fragments) // Note that regex is matched only two times; when the third value is obtained // the iterator is a suffix iterator. const std::string text = "Quick brown fox."; const std::regex ws_re("\\s+"); // whitespace std::copy( std::sregex_token_iterator(text.begin(), text.end(), ws_re, -1), std::sregex_token_iterator(), std::ostream_iterator<std::string>(std::cout, "\n")); std::cout << '\n'; // Iterating the first submatches const std::string html = R"(<p><a href="http://google.com">google</a> )" R"(< a HREF ="http://cppreference.com">cppreference</a>\n</p>)"; const std::regex url_re(R"!!(<\s*A\s+[^>]*href\s*=\s*"([^"]*)")!!", std::regex::icase); std::copy( std::sregex_token_iterator(html.begin(), html.end(), url_re, 1), std::sregex_token_iterator(), std::ostream_iterator<std::string>(std::cout, "\n")); } ``` Output: ``` Quick brown fox. http://google.com http://cppreference.com ```
programming_docs
cpp std::basic_regex std::basic\_regex ================= | Defined in header `[<regex>](../header/regex "cpp/header/regex")` | | | | --- | --- | --- | | ``` template < class CharT, class Traits = std::regex_traits<CharT> > class basic_regex; ``` | | (since C++11) | The class template `basic_regex` provides a general framework for holding regular expressions. Several specializations for common character types are provided: | Defined in header `[<regex>](../header/regex "cpp/header/regex")` | | --- | | Type | Definition | | `regex` | `basic_regex<char>` | | `wregex` | `basic_regex<wchar_t>` | ### Member types | Member type | Definition | | --- | --- | | `value_type` | `CharT` | | `traits_type` | `Traits` | | `string_type` | `Traits::string_type` | | `locale_type` | `Traits::locale_type` | | `flag_type` | `[std::regex\_constants::syntax\_option\_type](syntax_option_type "cpp/regex/syntax option type")` | ### Member functions | | | | --- | --- | | [(constructor)](basic_regex/basic_regex "cpp/regex/basic regex/basic regex") | constructs the regex object (public member function) | | [(destructor)](basic_regex/~basic_regex "cpp/regex/basic regex/~basic regex") | destructs the regex object (public member function) | | [operator=](basic_regex/operator= "cpp/regex/basic regex/operator=") | assigns the contents (public member function) | | [assign](basic_regex/assign "cpp/regex/basic regex/assign") | assigns the contents (public member function) | | Observers | | [mark\_count](basic_regex/mark_count "cpp/regex/basic regex/mark count") | returns the number of marked sub-expressions within the regular expression (public member function) | | [flags](basic_regex/flags "cpp/regex/basic regex/flags") | returns the syntax flags (public member function) | | Locale | | [getloc](basic_regex/getloc "cpp/regex/basic regex/getloc") | get locale information (public member function) | | [imbue](basic_regex/imbue "cpp/regex/basic regex/imbue") | set locale information (public member function) | | Modifiers | | [swap](basic_regex/swap "cpp/regex/basic regex/swap") | swaps the contents (public member function) | | Constants | | Value | Effect(s) | | --- | --- | | `icase` | Character matching should be performed without regard to case. | | `nosubs` | When performing matches, all marked sub-expressions `(expr)` are treated as non-marking sub-expressions `(?:expr)`. No matches are stored in the supplied `[std::regex\_match](regex_match "cpp/regex/regex match")` structure and `[mark\_count()](basic_regex/mark_count "cpp/regex/basic regex/mark count")` is zero. | | `optimize` | Instructs the regular expression engine to make matching faster, with the potential cost of making construction slower. For example, this might mean converting a non-deterministic FSA to a deterministic FSA. | | `collate` | Character ranges of the form *"[a-b]"* will be locale sensitive. | | `multiline` (C++17) | Specifies that `^` shall match the beginning of a line and `$` shall match the end of a line, if the ECMAScript engine is selected. | | `ECMAScript` | Use the [Modified ECMAScript regular expression grammar](ecmascript "cpp/regex/ecmascript"). | | `basic` | Use the basic POSIX regular expression grammar ([grammar documentation](http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap09.html#tag_09_03)). | | `extended` | Use the extended POSIX regular expression grammar ([grammar documentation](http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap09.html#tag_09_04)). | | `awk` | Use the regular expression grammar used by the *awk* utility in POSIX ([grammar documentation](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/awk.html#tag_20_06_13_04)). | | `grep` | Use the regular expression grammar used by the *grep* utility in POSIX. This is effectively the same as the `basic` option with the addition of newline `'\n'` as an alternation separator. | | `egrep` | Use the regular expression grammar used by the *grep* utility, with the *-E* option, in POSIX. This is effectively the same as the `extended` option with the addition of newline `'\n'` as an alternation separator in addition to `'|'`. | At most one grammar option must be chosen out of `ECMAScript`, `basic`, `extended`, `awk`, `grep`, `egrep`. If no grammar is chosen, `ECMAScript` is assumed to be selected. The other options serve as modifiers, such that `std::regex("meow", std::regex::icase)` is equivalent to `std::regex("meow", std::regex::ECMAScript|std::regex::icase)`. The member constants in `basic_regex` are duplicates of the [`syntax_option_type`](syntax_option_type "cpp/regex/syntax option type") constants defined in the namespace `std::regex_constants`. ### Non-member functions | | | | --- | --- | | [std::swap(std::basic\_regex)](basic_regex/swap2 "cpp/regex/basic regex/swap2") (C++11) | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | ### [Deduction guides](basic_regex/deduction_guides "cpp/regex/basic regex/deduction guides")(since C++17) cpp std::regex_search std::regex\_search ================== | Defined in header `[<regex>](../header/regex "cpp/header/regex")` | | | | --- | --- | --- | | ``` template< class BidirIt, class Alloc, class CharT, class Traits > bool regex_search( BidirIt first, BidirIt last, std::match_results<BidirIt,Alloc>& m, const std::basic_regex<CharT,Traits>& e, std::regex_constants::match_flag_type flags = std::regex_constants::match_default ); ``` | (1) | (since C++11) | | ``` template< class CharT, class Alloc, class Traits > bool regex_search( const CharT* str, std::match_results<const CharT*,Alloc>& m, const std::basic_regex<CharT,Traits>& e, std::regex_constants::match_flag_type flags = std::regex_constants::match_default ); ``` | (2) | (since C++11) | | ``` template< class STraits, class SAlloc, class Alloc, class CharT, class Traits > bool regex_search( const std::basic_string<CharT,STraits,SAlloc>& s, std::match_results< typename std::basic_string<CharT,STraits,SAlloc>::const_iterator, Alloc >& m, const std::basic_regex<CharT, Traits>& e, std::regex_constants::match_flag_type flags = std::regex_constants::match_default ); ``` | (3) | (since C++11) | | ``` template< class BidirIt, class CharT, class Traits > bool regex_search( BidirIt first, BidirIt last, const std::basic_regex<CharT,Traits>& e, std::regex_constants::match_flag_type flags = std::regex_constants::match_default ); ``` | (4) | (since C++11) | | ``` template< class CharT, class Traits > bool regex_search( const CharT* str, const std::basic_regex<CharT,Traits>& e, std::regex_constants::match_flag_type flags = std::regex_constants::match_default ); ``` | (5) | (since C++11) | | ``` template< class STraits, class SAlloc, class CharT, class Traits > bool regex_search( const std::basic_string<CharT,STraits,SAlloc>& s, const std::basic_regex<CharT,Traits>& e, std::regex_constants::match_flag_type flags = std::regex_constants::match_default ); ``` | (6) | (since C++11) | | ``` template< class STraits, class SAlloc, class Alloc, class CharT, class Traits > bool regex_search( const std::basic_string<CharT,STraits,SAlloc>&&, std::match_results< typename std::basic_string<CharT,STraits,SAlloc>::const_iterator, Alloc >&, const std::basic_regex<CharT, Traits>&, std::regex_constants::match_flag_type flags = std::regex_constants::match_default ) = delete; ``` | (7) | (since C++11) | Determines if there is a match between the regular expression `e` and some subsequence in the target character sequence. 1) Analyzes generic range `[first,last)`. Match results are returned in `m`. 2) Analyzes a null-terminated string pointed to by `str`. Match results are returned in `m`. 3) Analyzes a string `s`. Match results are returned in `m`. 4-6) Equivalent to (1-3), just omits the match results. 7) The overload (3) is prohibited from accepting temporary strings, otherwise this function populates `match_results` `m` with string iterators that become invalid immediately. `regex_search` will successfully match any subsequence of the given sequence, whereas `[std::regex\_match](regex_match "cpp/regex/regex match")` will only return `true` if the regular expression matches the *entire* sequence. ### Parameters | | | | | --- | --- | --- | | first, last | - | a range identifying the target character sequence | | str | - | a pointer to a null-terminated target character sequence | | s | - | a string identifying target character sequence | | e | - | the `[std::regex](basic_regex "cpp/regex/basic regex")` that should be applied to the target character sequence | | m | - | the match results | | flags | - | `[std::regex\_constants::match\_flag\_type](match_flag_type "cpp/regex/match flag type")` governing search behavior | | Type requirements | | -`BidirIt` must meet the requirements of [LegacyBidirectionalIterator](../named_req/bidirectionaliterator "cpp/named req/BidirectionalIterator"). | | -`Alloc` must meet the requirements of [Allocator](../named_req/allocator "cpp/named req/Allocator"). | ### Return value Returns `true` if a match exists, `false` otherwise. In either case, the object `m` is updated, as follows: If the match does not exist: | | | --- | | `m.ready() == true` | | `m.empty() == true` | | `m.size() == 0` | If the match exists: | | | | --- | --- | | `m.ready()` | `true` | | `m.empty()` | `false` | | `m.size()` | number of [marked subexpressions](ecmascript#Sub-expressions "cpp/regex/ecmascript") plus 1, that is, `1+e.mark_count()` | | `m.prefix().first` | `first` | | `m.prefix().second` | `m[0].first` | | `m.prefix().matched` | `m.prefix().first != m.prefix().second` | | `m.suffix().first` | `m[0].second` | | `m.suffix().second` | `last` | | `m.suffix().matched` | `m.suffix().first != m.suffix().second` | | `m[0].first` | the start of the matching sequence | | `m[0].second` | the end of the matching sequence | | `m[0].matched` | `true` | | `m[n].first` | the start of the sequence that matched [marked sub-expression](ecmascript#Sub-expressions "cpp/regex/ecmascript") n, or `last` if the subexpression did not participate in the match | | `m[n].second` | the end of the sequence that matched [marked sub-expression](ecmascript#Sub-expressions "cpp/regex/ecmascript") n, or `last` if the subexpression did not participate in the match | | `m[n].matched` | `true` if sub-expression n participated in the match, `false` otherwise | ### Notes In order to examine all matches within the target sequence, `std::regex_search` may be called in a loop, restarting each time from `m[0].second` of the previous call. `[std::regex\_iterator](regex_iterator "cpp/regex/regex iterator")` offers an easy interface to this iteration. ### Example ``` #include <iostream> #include <string> #include <regex> int main() { std::string lines[] = {"Roses are #ff0000", "violets are #0000ff", "all of my base are belong to you"}; std::regex color_regex("#([a-f0-9]{2})" "([a-f0-9]{2})" "([a-f0-9]{2})"); // simple match for (const auto &line : lines) { std::cout << line << ": " << std::boolalpha << std::regex_search(line, color_regex) << '\n'; } std::cout << '\n'; // show contents of marked subexpressions within each match std::smatch color_match; for (const auto& line : lines) { if(std::regex_search(line, color_match, color_regex)) { std::cout << "matches for '" << line << "'\n"; std::cout << "Prefix: '" << color_match.prefix() << "'\n"; for (size_t i = 0; i < color_match.size(); ++i) std::cout << i << ": " << color_match[i] << '\n'; std::cout << "Suffix: '" << color_match.suffix() << "\'\n\n"; } } // repeated search (see also std::regex_iterator) std::string log(R"( Speed: 366 Mass: 35 Speed: 378 Mass: 32 Speed: 400 Mass: 30)"); std::regex r(R"(Speed:\t\d*)"); std::smatch sm; while(regex_search(log, sm, r)) { std::cout << sm.str() << '\n'; log = sm.suffix(); } // C-style string demo std::cmatch cm; if(std::regex_search("this is a test", cm, std::regex("test"))) std::cout << "\nFound " << cm[0] << " at position " << cm.prefix().length(); } ``` Output: ``` Roses are #ff0000: true violets are #0000ff: true all of my base are belong to you: false matches for 'Roses are #ff0000' Prefix: 'Roses are ' 0: #ff0000 1: ff 2: 00 3: 00 Suffix: '' matches for 'violets are #0000ff' Prefix: 'violets are ' 0: #0000ff 1: 00 2: 00 3: ff Suffix: '' Speed: 366 Speed: 378 Speed: 400 Found test at position 10 ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 2329](https://cplusplus.github.io/LWG/issue2329) | C++11 | `basic_string` rvalues were accepted, which was likely to result in dangling iterators | rejected via a deleted overload | ### See also | | | | --- | --- | | [basic\_regex](basic_regex "cpp/regex/basic regex") (C++11) | regular expression object (class template) | | [match\_results](match_results "cpp/regex/match results") (C++11) | identifies one regular expression match, including all sub-expression matches (class template) | | [regex\_match](regex_match "cpp/regex/regex match") (C++11) | attempts to match a regular expression to an entire character sequence (function template) | cpp std::regex_error std::regex\_error ================= | Defined in header `[<regex>](../header/regex "cpp/header/regex")` | | | | --- | --- | --- | | ``` class regex_error; ``` | | (since C++11) | Defines the type of exception object thrown to report errors in the regular expressions library. ![std-regex error-inheritance.svg]() Inheritance diagram. ### Member functions | | | | --- | --- | | [(constructor)](regex_error/regex_error "cpp/regex/regex error/regex error") | constructs a `regex_error` object (public member function) | | [operator=](regex_error/operator= "cpp/regex/regex error/operator=") | replaces the `regex_error` object (public member function) | | [code](regex_error/code "cpp/regex/regex error/code") | gets the `[std::regex\_constants::error\_type](error_type "cpp/regex/error type")` for a `regex_error` (public member function) | Inherited from [std::runtime\_error](../error/runtime_error "cpp/error/runtime error") ---------------------------------------------------------------------------------------- Inherited from [std::exception](../error/exception "cpp/error/exception") --------------------------------------------------------------------------- ### Member functions | | | | --- | --- | | [(destructor)](../error/exception/~exception "cpp/error/exception/~exception") [virtual] | destroys the exception object (virtual public member function of `std::exception`) | | [what](../error/exception/what "cpp/error/exception/what") [virtual] | returns an explanatory string (virtual public member function of `std::exception`) | ### Example ``` #include <regex> #include <iostream> int main() { try { std::regex re("[a-b][a"); } catch (const std::regex_error& e) { std::cout << "regex_error caught: " << e.what() << '\n'; if (e.code() == std::regex_constants::error_brack) { std::cout << "The code was error_brack\n"; } } } ``` Possible output: ``` regex_error caught: The expression contained mismatched [ and ]. The code was error_brack ``` cpp std::regex_constants::error_type std::regex\_constants::error\_type ================================== | Defined in header `[<regex>](../header/regex "cpp/header/regex")` | | | | --- | --- | --- | | ``` typedef /*implementation defined*/ error_type; ``` | | (since C++11) | | ``` constexpr error_type error_collate = /*unspecified*/; constexpr error_type error_ctype = /*unspecified*/; constexpr error_type error_escape = /*unspecified*/; constexpr error_type error_backref = /*unspecified*/; constexpr error_type error_brack = /*unspecified*/; constexpr error_type error_paren = /*unspecified*/; constexpr error_type error_brace = /*unspecified*/; constexpr error_type error_badbrace = /*unspecified*/; constexpr error_type error_range = /*unspecified*/; constexpr error_type error_space = /*unspecified*/; constexpr error_type error_badrepeat = /*unspecified*/; constexpr error_type error_complexity = /*unspecified*/; constexpr error_type error_stack = /*unspecified*/; ``` | | (since C++11) (until C++17) | | ``` inline constexpr error_type error_collate = /*unspecified*/; inline constexpr error_type error_ctype = /*unspecified*/; inline constexpr error_type error_escape = /*unspecified*/; inline constexpr error_type error_backref = /*unspecified*/; inline constexpr error_type error_brack = /*unspecified*/; inline constexpr error_type error_paren = /*unspecified*/; inline constexpr error_type error_brace = /*unspecified*/; inline constexpr error_type error_badbrace = /*unspecified*/; inline constexpr error_type error_range = /*unspecified*/; inline constexpr error_type error_space = /*unspecified*/; inline constexpr error_type error_badrepeat = /*unspecified*/; inline constexpr error_type error_complexity = /*unspecified*/; inline constexpr error_type error_stack = /*unspecified*/; ``` | | (since C++17) | The `error_type` is a type that describes errors that may occur during regular expression parsing. ### Constants | Constant | Explanation | | --- | --- | | `error_collate` | the expression contains an invalid collating element name | | `error_ctype` | the expression contains an invalid character class name | | `error_escape` | the expression contains an invalid escaped character or a trailing escape | | `error_backref` | the expression contains an invalid back reference | | `error_brack` | the expression contains mismatched square brackets ('[' and ']') | | `error_paren` | the expression contains mismatched parentheses ('(' and ')') | | `error_brace` | the expression contains mismatched curly braces ('{' and '}') | | `error_badbrace` | the expression contains an invalid range in a {} expression | | `error_range` | the expression contains an invalid character range (e.g. [b-a]) | | `error_space` | there was not enough memory to convert the expression into a finite state machine | | `error_badrepeat` | one of \*?+{ was not preceded by a valid regular expression | | `error_complexity` | the complexity of an attempted match exceeded a predefined level | | `error_stack` | there was not enough memory to perform a match | ### Notes In C++11, these constants were specified with redundant keyword `static`, which was removed by C++14 via [LWG issue 2053](http://www.open-std.org/jtc1/sc22/wg21/docs/lwg-defects.html#2053). ### Example Implements regular expressions checker. ``` #include <iomanip> #include <iostream> #include <regex> #include <sstream> #include <string> using namespace std::string_literals; void show_regex_error(const std::regex_error& e) { std::string err_message = e.what(); # define CASE(type, msg) \ case std::regex_constants::type: err_message += " ("s + #type "):\n "s + msg; \ break switch (e.code()) { CASE(error_collate, "The expression contains an invalid collating element name"); CASE(error_ctype, "The expression contains an invalid character class name"); CASE(error_escape, "The expression contains an invalid escaped character or a trailing escape"); CASE(error_backref, "The expression contains an invalid back reference"); CASE(error_brack, "The expression contains mismatched square brackets ('[' and ']')"); CASE(error_paren, "The expression contains mismatched parentheses ('(' and ')')"); CASE(error_brace, "The expression contains mismatched curly braces ('{' and '}')"); CASE(error_badbrace, "The expression contains an invalid range in a {} expression"); CASE(error_range, "The expression contains an invalid character range (e.g. [b-a])"); CASE(error_space, "There was not enough memory to convert the expression into a finite state machine"); CASE(error_badrepeat, "one of *?+{ was not preceded by a valid regular expression"); CASE(error_complexity, "The complexity of an attempted match exceeded a predefined level"); CASE(error_stack, "There was not enough memory to perform a match"); } # undef CASE /* std::cerr */ std::cout << err_message << ". \n\n"; } void regular_expression_checker(const std::string& text, const std::string& regex, const std::regex::flag_type flags) { std::cout << "Text: " << quoted(text) << "\nRegex: " << quoted(regex) << '\n'; try { const std::regex re{regex, flags}; const bool matched = std::regex_match(text, re); std::stringstream out; out << (matched ? "MATCH!\n" : "DOES NOT MATCH!\n"); std::smatch m; if (std::regex_search(text, m, re); !m.empty()) { out << "prefix = [" << m.prefix().str().data() << "]\n"; for (std::size_t i{}; i != m.size(); ++i) out << " m[" << i << "] = [" << m[i].str().data() << "]\n"; out << "suffix = [" << m.suffix().str().data() << "]\n"; } std::cout << out.str() << '\n'; } catch (std::regex_error& ex) { show_regex_error(ex); } } int main() { constexpr std::regex::flag_type your_flags = std::regex::flag_type{0} // Choose one of the supported grammars: | std::regex::ECMAScript // | std::regex::basic // | std::regex::extended // | std::regex::awk // | std::regex::grep // | std::regex::egrep // Choose any of the next options: // | std::regex::icase // | std::regex::nosubs // | std::regex::optimize // | std::regex::collate // | std::regex::multiline ; const auto your_text = "Hello regular expressions."s; const auto your_regex = R"(([a-zA-Z]+) ([a-z]+) ([a-z]+)\.)"s; regular_expression_checker(your_text, your_regex, your_flags); regular_expression_checker("Invalid!", R"(((.)(.))", your_flags); regular_expression_checker("Invalid!", R"([.)", your_flags); regular_expression_checker("Invalid!", R"([.]{})", your_flags); regular_expression_checker("Invalid!", R"([1-0])", your_flags); } ``` Possible output: ``` Text: "Hello regular expressions." Regex: "([a-zA-Z]+) ([a-z]+) ([a-z]+)\\." MATCH! prefix = [] m[0] = [Hello regular expressions.] m[1] = [Hello] m[2] = [regular] m[3] = [expressions] suffix = [] Text: "Invalid!" Regex: "((.)(.)" Parenthesis is not closed. (error_paren): The expression contains mismatched parentheses ('(' and ')'). Text: "Invalid!" Regex: "[." Unexpected character in bracket expression. (error_brack): The expression contains mismatched square brackets ('[' and ']'). Text: "Invalid!" Regex: "[.]{}" Unexpected token in brace expression. (error_badbrace): The expression contains an invalid range in a {} expression. Text: "Invalid!" Regex: "[1-0]" Invalid range in bracket expression. (error_range): The expression contains an invalid character range (e.g. [b-a]). ``` ### See also | | | | --- | --- | | [regex\_error](regex_error "cpp/regex/regex error") (C++11) | reports errors generated by the regular expressions library (class) |
programming_docs
cpp std::sub_match std::sub\_match =============== | Defined in header `[<regex>](../header/regex "cpp/header/regex")` | | | | --- | --- | --- | | ``` template<class BidirIt> class sub_match; ``` | | (since C++11) | The class template `sub_match` is used by the regular expression engine to denote sequences of characters matched by marked sub-expressions. A match is a `[begin, end)` pair within the target range matched by the regular expression, but with additional observer functions to enhance code clarity. Only the default constructor is publicly accessible. Instances of `sub_match` are normally constructed and populated as a part of a `[std::match\_results](match_results "cpp/regex/match results")` container during the processing of one of the regex algorithms. The member functions return defined default values unless the `matched` member is `true`. `sub_match` inherits from `[std::pair](http://en.cppreference.com/w/cpp/utility/pair)<BidirIt, BidirIt>`, although it cannot be treated as a `[std::pair](../utility/pair "cpp/utility/pair")` object because member functions such as swap and assignment will not work as expected. ### Type requirements | | | --- | | -`BidirIt` must meet the requirements of [LegacyBidirectionalIterator](../named_req/bidirectionaliterator "cpp/named req/BidirectionalIterator"). | ### Specializations Several specializations for common character sequence types are provided: | Defined in header `[<regex>](../header/regex "cpp/header/regex")` | | --- | | Type | Definition | | `csub_match` | `sub_match<const char*>` | | `wcsub_match` | `sub_match<const wchar_t*>` | | `ssub_match` | `sub_match<std::string::const_iterator>` | | `wssub_match` | `sub_match<std::wstring::const_iterator>` | ### Member types | Member type | Definition | | --- | --- | | `iterator` | `BidirIt` | | `value_type` | `[std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<BidirIt>::value\_type` | | `difference_type` | `[std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<BidirIt>::difference\_type` | | `string_type` | `[std::basic\_string](http://en.cppreference.com/w/cpp/string/basic_string)<value_type>` | ### Member objects | | | | --- | --- | | bool matched | Indicates if this match was successful (public member object) | Inherited from [std::pair](../utility/pair "cpp/utility/pair") ---------------------------------------------------------------- | | | | --- | --- | | BidirIt first | Start of the match sequence. (public member object) | | BidirIt second | One-past-the-end of the match sequence. (public member object) | ### Member functions | | | | --- | --- | | [(constructor)](sub_match/sub_match "cpp/regex/sub match/sub match") | constructs the match object (public member function) | | Observers | | [length](sub_match/length "cpp/regex/sub match/length") | returns the length of the match (if any) (public member function) | | [stroperator string\_type](sub_match/str "cpp/regex/sub match/str") | converts to the underlying string type (public member function) | | [compare](sub_match/compare "cpp/regex/sub match/compare") | compares matched subsequence (if any) (public member function) | ### Non-member functions | | | | --- | --- | | [operator==operator!=operator<operator<=operator>operator>=operator<=>](sub_match/operator_cmp "cpp/regex/sub match/operator cmp") (removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(C++20) | compares a `sub_match` with another `sub_match`, a string, or a character (function template) | | [operator<<](sub_match/operator_ltlt "cpp/regex/sub match/operator ltlt") | outputs the matched character subsequence (function template) | ### See also | | | | --- | --- | | [regex\_token\_iterator](regex_token_iterator "cpp/regex/regex token iterator") (C++11) | iterates through the specified sub-expressions within all regex matches in a given string or through unmatched substrings (class template) | cpp std::regex_constants::match_flag_type std::regex\_constants::match\_flag\_type ======================================== | Defined in header `[<regex>](../header/regex "cpp/header/regex")` | | | | --- | --- | --- | | ``` typedef /*unspecified*/ match_flag_type; ``` | | (since C++11) | | ``` constexpr match_flag_type match_default = {}; constexpr match_flag_type match_not_bol = /*unspecified*/; constexpr match_flag_type match_not_eol = /*unspecified*/; constexpr match_flag_type match_not_bow = /*unspecified*/; constexpr match_flag_type match_not_eow = /*unspecified*/; constexpr match_flag_type match_any = /*unspecified*/; constexpr match_flag_type match_not_null = /*unspecified*/; constexpr match_flag_type match_continuous = /*unspecified*/; constexpr match_flag_type match_prev_avail = /*unspecified*/; constexpr match_flag_type format_default = {}; constexpr match_flag_type format_sed = /*unspecified*/; constexpr match_flag_type format_no_copy = /*unspecified*/; constexpr match_flag_type format_first_only = /*unspecified*/; ``` | | (since C++11) (until C++17) | | ``` inline constexpr match_flag_type match_default = {}; inline constexpr match_flag_type match_not_bol = /*unspecified*/; inline constexpr match_flag_type match_not_eol = /*unspecified*/; inline constexpr match_flag_type match_not_bow = /*unspecified*/; inline constexpr match_flag_type match_not_eow = /*unspecified*/; inline constexpr match_flag_type match_any = /*unspecified*/; inline constexpr match_flag_type match_not_null = /*unspecified*/; inline constexpr match_flag_type match_continuous = /*unspecified*/; inline constexpr match_flag_type match_prev_avail = /*unspecified*/; inline constexpr match_flag_type format_default = {}; inline constexpr match_flag_type format_sed = /*unspecified*/; inline constexpr match_flag_type format_no_copy = /*unspecified*/; inline constexpr match_flag_type format_first_only = /*unspecified*/; ``` | | (since C++17) | `match_flag_type` is a [BitmaskType](../named_req/bitmasktype "cpp/named req/BitmaskType") that specifies additional regular expression matching options. ### Constants Note: `[first, last)` refers to the character sequence being matched. | Constant | Explanation | | --- | --- | | `match_not_bol` | The first character in *[first,last)* will be treated as if it is **not** at the beginning of a line (i.e. *^* will not match *[first,first)* | | `match_not_eol` | The last character in *[first,last)* will be treated as if it is **not** at the end of a line (i.e. *$* will not match *[last,last)* | | `match_not_bow` | *"\b"* will not match *[first,first)* | | `match_not_eow` | *"\b"* will not match *[last,last)* | | `match_any` | If more than one match is possible, then any match is an acceptable result | | `match_not_null` | Do not match empty sequences | | `match_continuous` | Only match a sub-sequence that begins at *first* | | `match_prev_avail` | *--first* is a valid iterator position. When set, causes *match\_not\_bol* and *match\_not\_bow* to be ignored | | `format_default` | Use ECMAScript rules to construct strings in `[std::regex\_replace](regex_replace "cpp/regex/regex replace")` ([syntax documentation](http://ecma-international.org/ecma-262/5.1/#sec-15.5.4.11)) | | `format_sed` | Use POSIX *sed* utility rules in `[std::regex\_replace](regex_replace "cpp/regex/regex replace")`. ([syntax documentation](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/sed.html#tag_20_116_13_03)) | | `format_no_copy` | Do not copy un-matched strings to the output in `[std::regex\_replace](regex_replace "cpp/regex/regex replace")` | | `format_first_only` | Only replace the first match in `[std::regex\_replace](regex_replace "cpp/regex/regex replace")` | All constants, except for `match_default` and `format_default`, are bitmask elements. The `match_default` and `format_default` constants are empty bitmasks. ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 2053](https://cplusplus.github.io/LWG/issue2053) | C++11 | `match_flag_type` could not be a scoped enumeration because`match_default` and `format_default` was required to be initialized from `​0​` | made initialized from empty braces | ### See also | | | | --- | --- | | [regex\_match](regex_match "cpp/regex/regex match") (C++11) | attempts to match a regular expression to an entire character sequence (function template) | | [syntax\_option\_type](syntax_option_type "cpp/regex/syntax option type") (C++11) | general options controlling regex behavior (typedef) | | [error\_type](error_type "cpp/regex/error type") (C++11) | describes different types of matching errors (typedef) | cpp std::regex_match std::regex\_match ================= | Defined in header `[<regex>](../header/regex "cpp/header/regex")` | | | | --- | --- | --- | | ``` template< class BidirIt, class Alloc, class CharT, class Traits > bool regex_match( BidirIt first, BidirIt last, std::match_results<BidirIt,Alloc>& m, const std::basic_regex<CharT,Traits>& e, std::regex_constants::match_flag_type flags = std::regex_constants::match_default ); ``` | (1) | (since C++11) | | ``` template< class BidirIt, class CharT, class Traits > bool regex_match( BidirIt first, BidirIt last, const std::basic_regex<CharT,Traits>& e, std::regex_constants::match_flag_type flags = std::regex_constants::match_default ); ``` | (2) | (since C++11) | | ``` template< class CharT, class Alloc, class Traits > bool regex_match( const CharT* str, std::match_results<const CharT*,Alloc>& m, const std::basic_regex<CharT,Traits>& e, std::regex_constants::match_flag_type flags = std::regex_constants::match_default ); ``` | (3) | (since C++11) | | ``` template< class STraits, class SAlloc, class Alloc, class CharT, class Traits > bool regex_match( const std::basic_string<CharT,STraits,SAlloc>& s, std::match_results< typename std::basic_string<CharT,STraits,SAlloc>::const_iterator, Alloc >& m, const std::basic_regex<CharT,Traits>& e, std::regex_constants::match_flag_type flags = std::regex_constants::match_default ); ``` | (4) | (since C++11) | | ``` template< class CharT, class Traits > bool regex_match( const CharT* str, const std::basic_regex<CharT,Traits>& e, std::regex_constants::match_flag_type flags = std::regex_constants::match_default ); ``` | (5) | (since C++11) | | ``` template< class STraits, class SAlloc, class CharT, class Traits > bool regex_match( const std::basic_string<CharT, STraits, SAlloc>& s, const std::basic_regex<CharT,Traits>& e, std::regex_constants::match_flag_type flags = std::regex_constants::match_default ); ``` | (6) | (since C++11) | | ``` template< class STraits, class SAlloc, class Alloc, class CharT, class Traits > bool regex_match( const std::basic_string<CharT,STraits,SAlloc>&&, std::match_results< typename std::basic_string<CharT,STraits,SAlloc>::const_iterator, Alloc >&, const std::basic_regex<CharT,Traits>&, std::regex_constants::match_flag_type flags = std::regex_constants::match_default ) = delete; ``` | (7) | (since C++11) | Determines if the regular expression `e` matches the entire target character sequence, which may be specified as `[std::string](../string/basic_string "cpp/string/basic string")`, a C-string, or an iterator pair. 1) Determines if there is a match between the regular expression `e` and the entire target character sequence `[first,last)`, taking into account the effect of `flags`. When determining if there is a match, only potential matches that match the entire character sequence are considered. Match results are returned in `m`. 2) Behaves as (1) above, omitting the match results. 3) Returns `std::regex\_match(str, str + [std::char\_traits](http://en.cppreference.com/w/cpp/string/char_traits)<charT>::length(str), m, e, flags)`. 4) Returns `std::regex_match(s.begin(), s.end(), m, e, flags)`. 5) Returns `std::regex\_match(str, str + [std::char\_traits](http://en.cppreference.com/w/cpp/string/char_traits)<charT>::length(str), e, flags)`. 6) Returns `std::regex_match(s.begin(), s.end(), e, flags)`. 7) The overload (4) is prohibited from accepting temporary strings, otherwise this function populates `match_results` `m` with string iterators that become invalid immediately. Note that `regex_match` will only successfully match a regular expression to an *entire* character sequence, whereas `[std::regex\_search](regex_search "cpp/regex/regex search")` will successfully match subsequences. ### Parameters | | | | | --- | --- | --- | | first, last | - | the target character range to apply the regex to, given as iterators | | m | - | the match results | | str | - | the target string, given as a null-terminated C-style string | | s | - | the target string, given as a `[std::basic\_string](../string/basic_string "cpp/string/basic string")` | | e | - | the regular expression | | flags | - | flags used to determine how the match will be performed | | Type requirements | | -`BidirIt` must meet the requirements of [LegacyBidirectionalIterator](../named_req/bidirectionaliterator "cpp/named req/BidirectionalIterator"). | ### Return value Returns `true` if a match exists, `false` otherwise. In either case, the object `m` is updated, as follows: If the match does not exist: | | | --- | | `m.ready() == true` | | `m.empty() == true` | | `m.size() == 0` | If the match exists: | | | | --- | --- | | `m.ready()` | `true` | | `m.empty()` | `false` | | `m.size()` | [number of marked subexpressions](ecmascript#Sub-expressions "cpp/regex/ecmascript") plus 1, that is, `1+e.mark_count()` | | `m.prefix().first` | `first` | | `m.prefix().second` | `first` | | `m.prefix().matched` | `false` (the match prefix is empty) | | `m.suffix().first` | `last` | | `m.suffix().second` | `last` | | `m.suffix().matched` | `false` (the match suffix is empty) | | `m[0].first` | `first` | | `m[0].second` | `last` | | `m[0].matched` | `true` (the entire sequence is matched) | | `m[n].first` | the start of the sequence that matched [marked sub-expression](ecmascript#Sub-expressions "cpp/regex/ecmascript") n, or `last` if the subexpression did not participate in the match | | `m[n].second` | the end of the sequence that matched [marked sub-expression](ecmascript#Sub-expressions "cpp/regex/ecmascript") n, or `last` if the subexpression did not participate in the match | | `m[n].matched` | `true` if sub-expression n participated in the match, `false` otherwise | ### Notes Because `regex_match` only considers full matches, the same regex may give different matches between `regex_match` and `[std::regex\_search](regex_search "cpp/regex/regex search")`: ``` std::regex re("Get|GetValue"); std::cmatch m; std::regex_search("GetValue", m, re); // returns true, and m[0] contains "Get" std::regex_match ("GetValue", m, re); // returns true, and m[0] contains "GetValue" std::regex_search("GetValues", m, re); // returns true, and m[0] contains "Get" std::regex_match ("GetValues", m, re); // returns false ``` ### Example ``` #include <iostream> #include <string> #include <regex> int main() { // Simple regular expression matching const std::string fnames[] = {"foo.txt", "bar.txt", "baz.dat", "zoidberg"}; const std::regex txt_regex("[a-z]+\\.txt"); for (const auto &fname : fnames) { std::cout << fname << ": " << std::regex_match(fname, txt_regex) << '\n'; } // Extraction of a sub-match const std::regex base_regex("([a-z]+)\\.txt"); std::smatch base_match; for (const auto &fname : fnames) { if (std::regex_match(fname, base_match, base_regex)) { // The first sub_match is the whole string; the next // sub_match is the first parenthesized expression. if (base_match.size() == 2) { std::ssub_match base_sub_match = base_match[1]; std::string base = base_sub_match.str(); std::cout << fname << " has a base of " << base << '\n'; } } } // Extraction of several sub-matches const std::regex pieces_regex("([a-z]+)\\.([a-z]+)"); std::smatch pieces_match; for (const auto &fname : fnames) { if (std::regex_match(fname, pieces_match, pieces_regex)) { std::cout << fname << '\n'; for (size_t i = 0; i < pieces_match.size(); ++i) { std::ssub_match sub_match = pieces_match[i]; std::string piece = sub_match.str(); std::cout << " submatch " << i << ": " << piece << '\n'; } } } } ``` Output: ``` foo.txt: 1 bar.txt: 1 baz.dat: 0 zoidberg: 0 foo.txt has a base of foo bar.txt has a base of bar foo.txt submatch 0: foo.txt submatch 1: foo submatch 2: txt bar.txt submatch 0: bar.txt submatch 1: bar submatch 2: txt baz.dat submatch 0: baz.dat submatch 1: baz submatch 2: dat ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 2329](https://cplusplus.github.io/LWG/issue2329) | C++11 | `basic_string` rvalues were accepted, which was likely to result in dangling iterators | rejected via a deleted overload | ### See also | | | | --- | --- | | [basic\_regex](basic_regex "cpp/regex/basic regex") (C++11) | regular expression object (class template) | | [match\_results](match_results "cpp/regex/match results") (C++11) | identifies one regular expression match, including all sub-expression matches (class template) | | [regex\_search](regex_search "cpp/regex/regex search") (C++11) | attempts to match a regular expression to any part of a character sequence (function template) | cpp std::regex_traits std::regex\_traits ================== | Defined in header `[<regex>](../header/regex "cpp/header/regex")` | | | | --- | --- | --- | | ``` template< class CharT > class regex_traits; ``` | | (since C++11) | The type trait template `regex_traits` supplies `[std::basic\_regex](basic_regex "cpp/regex/basic regex")` with the set of types and functions necessary to operate on the type `CharT`. Since many of regex operations are locale-sensitive (when `[std::regex\_constants::collate](syntax_option_type "cpp/regex/syntax option type")` flag is set), the regex\_traits class typically holds an instance of a `[std::locale](../locale/locale "cpp/locale/locale")` as a private member. ### Standard specializations Two specializations of `std::regex_traits` are defined by the standard library: | | | --- | | `std::regex_traits<char>` | | `std::regex_traits<wchar_t>` | These specializations make it possible to use `[std::basic\_regex](http://en.cppreference.com/w/cpp/regex/basic_regex)<char>` (aka `[std::regex](basic_regex "cpp/regex/basic regex")`) and `[std::basic\_regex](http://en.cppreference.com/w/cpp/regex/basic_regex)<wchar\_t>` (aka `[std::wregex](basic_regex "cpp/regex/basic regex")`). To use `[std::basic\_regex](basic_regex "cpp/regex/basic regex")` with other character types (for example, `char32_t`), a user-provided trait class must be used. ### Member types | Type | Definition | | --- | --- | | `char_type` | `CharT` | | `string_type` | `[std::basic\_string](http://en.cppreference.com/w/cpp/string/basic_string)<CharT>` | | `locale_type` | The locale used for localized behavior in the regular expression. Must be [CopyConstructible](../named_req/copyconstructible "cpp/named req/CopyConstructible") | | `char_class_type` | Represents a character classification and is capable of holding an implementation specific set returned by `lookup_classname`. Must be a [BitmaskType](../named_req/bitmasktype "cpp/named req/BitmaskType"). | ### Member functions | | | | --- | --- | | [(constructor)](regex_traits/regex_traits "cpp/regex/regex traits/regex traits") | constructs the regex\_traits object (public member function) | | [length](regex_traits/length "cpp/regex/regex traits/length") [static] | calculates the length of a null-terminated character string (public static member function) | | [translate](regex_traits/translate "cpp/regex/regex traits/translate") | determines the equivalence key for a character (public member function) | | [translate\_nocase](regex_traits/translate_nocase "cpp/regex/regex traits/translate nocase") | determines the case-insensitive equivalence key for a character (public member function) | | [transform](regex_traits/transform "cpp/regex/regex traits/transform") | determines the sort key for the given string, used to provide collation order (public member function) | | [transform\_primary](regex_traits/transform_primary "cpp/regex/regex traits/transform primary") | determines the primary sort key for the character sequence, used to determine equivalence class (public member function) | | [lookup\_collatename](regex_traits/lookup_collatename "cpp/regex/regex traits/lookup collatename") | gets a collation element by name (public member function) | | [lookup\_classname](regex_traits/lookup_classname "cpp/regex/regex traits/lookup classname") | gets a character class by name (public member function) | | [isctype](regex_traits/isctype "cpp/regex/regex traits/isctype") | indicates membership in a localized character class (public member function) | | [value](regex_traits/value "cpp/regex/regex traits/value") | translates the character representing a numeric digit into an integral value (public member function) | | [imbue](regex_traits/imbue "cpp/regex/regex traits/imbue") | sets the locale (public member function) | | [getloc](regex_traits/getloc "cpp/regex/regex traits/getloc") | gets the locale (public member function) |
programming_docs
cpp Modified ECMAScript regular expression grammar Modified ECMAScript regular expression grammar ============================================== This page describes the regular expression grammar that is used when `[std::basic\_regex](basic_regex "cpp/regex/basic regex")` is constructed with [`syntax_option_type`](syntax_option_type "cpp/regex/syntax option type") set to `ECMAScript` (the default). See [`syntax_option_type`](syntax_option_type "cpp/regex/syntax option type") for the other supported regular expression grammars. The `ECMAScript` 3 regular expression grammar in C++ is [ECMA-262 grammar](http://ecma-international.org/ecma-262/5.1/#sec-15.10) with modifications marked with (C++ only) below. ### Overview The [modified regular expression grammar](https://eel.is/c++draft/re.grammar) is mostly ECMAScript RegExp grammar with a POSIX-type expansion on locales under *ClassAtom*. Some clarifications on equality checks and number parsing is made. For many of the examples here, you can try this equivalent in your browser console: ``` function match(s, re) { return s.match(new RegExp(re)); } ``` The "normative references" in the standard specifies ECMAScript 3. We link to the ECMAScript 5.1 spec here because it is a version with only minor changes from ECMAScript 3, and it also has an HTML version. See the [MDN Guide on JavaScript RegExp](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions) for an overview on the dialect features. ### Alternatives A regular expression pattern is sequence of one or more *Alternative*s, separated by the disjunction operator `|` (in other words, the disjunction operator has the lowest precedence). *Pattern* :: *Disjunction* *Disjunction* :: *Alternative* *Alternative* `|` *Disjunction* The pattern first tries to skip the *Disjunction* and match the left *Alternative* followed by the rest of the regular expression (after the Disjunction). If it fails, it tries to skip the left *Alternative* and match the right *Disjunction* (followed by the rest of the regular expression). If the left *Alternative*, the right *Disjunction*, and the remainder of the regular expression all have choice points, all choices in the remainder of the expression are tried before moving on to the next choice in the left *Alternative*. If choices in the left *Alternative* are exhausted, the right *Disjunction* is tried instead of the left *Alternative*. Any capturing parentheses inside a skipped *Alternative* produce empty submatches. ``` #include <iostream> #include <string> #include <regex> void show_matches(const std::string& in, const std::string& re) { std::smatch m; std::regex_search(in, m, std::regex(re)); if(!m.empty()) { std::cout << "input=[" << in << "], regex=[" << re << "]\n " "prefix=[" << m.prefix() << "]\n smatch: "; for(std::size_t n = 0; n < m.size(); ++n) std::cout << "m[" << n << "]=[" << m[n] << "] "; std::cout << "\n suffix=[" << m.suffix() << "]\n"; } else { std::cout << "input=[" << in << "], regex=[" << re << "]: NO MATCH\n"; } } int main() { show_matches("abcdef", "abc|def"); show_matches("abc", "ab|abc"); // left Alernative matched first // Match of the input against the left Alternative (a) followed // by the remained of the regex (c|bc) succeeds, which results // in m[1]="a" and m[4]="bc". // The skipped Alternatives (ab) and (c) leave their submatches // m[3] and m[5] empty. show_matches("abc", "((a)|(ab))((c)|(bc))"); } ``` Output: ``` input=[abcdef], regex=[abc|def] prefix=[] smatch: m[0]=[abc] suffix=[def] input=[abc], regex=[ab|abc] prefix=[] smatch: m[0]=[ab] suffix=[c] input=[abc], regex=[((a)|(ab))((c)|(bc))] prefix=[] smatch: m[0]=[abc] m[1]=[a] m[2]=[a] m[3]=[] m[4]=[bc] m[5]=[] m[6]=[bc] suffix=[] ``` ### Terms Each *Alternative* is either empty or is a sequence of *Term*s (with no separators between the *Term*s). *Alternative* :: *[empty]* *Alternative* *Term* Empty *Alternative* always matches and does not consume any input. Consecutive *Term*s try to simultaneously match consecutive portions of the input. If the left *Alternative*, the right *Term*, and the remainder of the regular expression all have choice points, all choices in the remained of the expression are tried before moving on to the next choice in the right *Term*, and all choices in the right *Term* are tried before moving on to the next choice in the left *Alternative*. ``` #include <iostream> #include <string> #include <regex> void show_matches(const std::string& in, const std::string& re) { std::smatch m; std::regex_search(in, m, std::regex(re)); if(!m.empty()) { std::cout << "input=[" << in << "], regex=[" << re << "]\n " "prefix=[" << m.prefix() << "]\n smatch: "; for(std::size_t n = 0; n < m.size(); ++n) std::cout << "m[" << n << "]=[" << m[n] << "] "; std::cout << "\n suffix=[" << m.suffix() << "]\n"; } else { std::cout << "input=[" << in << "], regex=[" << re << "]: NO MATCH\n"; } } int main() { show_matches("abcdef", ""); // empty regex is a single empty Alternative show_matches("abc", "abc|"); // left Alernative matched first show_matches("abc", "|abc"); // left Alernative matched first, leaving abc unmatched } ``` Output: ``` input=[abcdef], regex=[] prefix=[] smatch: m[0]=[] suffix=[abcdef] input=[abc], regex=[abc|] prefix=[] smatch: m[0]=[abc] suffix=[] input=[abc], regex=[|abc] prefix=[] smatch: m[0]=[] suffix=[abc] ``` ### Quantifiers * Each *Term* is either an *Assertion* (see below), or an *Atom* (see below), or an *Atom* immediately followed by a *Quantifier* *Term* :: *Assertion* *Atom* *Atom* *Quantifier* Each *Quantifier* is either a *greedy* quantifier (which consists of just one *QuantifierPrefix*) or a *non-greedy* quantifier (which consists of one *QuantifierPrefix* followed by the question mark `?`). *Quantifier* :: *QuantifierPrefix* *QuantifierPrefix* `?` Each *QuantifierPrefix* determines two numbers: the minimum number of repetitions and the maximum number of repetitions, as follows: | QuantifierPrefix | Minimum | Maximum | | --- | --- | --- | | `*` | zero | infinity | | `+` | one | infinity | | `?` | zero | one | | `{` *DecimalDigits* `}` | value of DecimalDigits | value of DecimalDigits | | `{` *DecimalDigits* `,` `}` | value of DecimalDigits | infinity | | `{` *DecimalDigits* `,` *DecimalDigits* `}` | value of DecimalDigits before the comma | value of DecimalDigits after the comma | The values of the individual *DecimalDigits* are obtained by calling `[std::regex\_traits::value](regex_traits/value "cpp/regex/regex traits/value")`(C++ only) on each of the digits. An *Atom* followed by a *Quantifier* is repeated the number of times specified by the *Quantifier*. A *Quantifier* can be *non-greedy*, in which case the *Atom* pattern is repeated as few times as possible while still matching the remainder of the regular expression, or it can be *greedy*, in which case the *Atom* pattern is repeated as many times as possible while still matching the remainder of the regular expression. The *Atom* pattern is what is repeated, not the input that it matches, so different repetitions of the *Atom* can match different input substrings. If the *Atom* and the remainder of the regular expression all have choice points, the *Atom* is first matched as many (or as few, if *non-greedy*) times as possible. All choices in the remainder of the regular expression are tried before moving on to the next choice in the last repetition of *Atom*. All choices in the last (nth) repetition of *Atom* are tried before moving on to the next choice in the next-to-last (n–1)st repetition of *Atom*; at which point it may turn out that more or fewer repetitions of *Atom* are now possible; these are exhausted (again, starting with either as few or as many as possible) before moving on to the next choice in the (n-1)st repetition of *Atom* and so on. The *Atom'*s captures are cleared each time it is repeated (see the `"(z)((a+)?(b+)?(c))*"` example below). ``` #include <iostream> #include <string> #include <regex> void show_matches(const std::string& in, const std::string& re) { std::smatch m; std::regex_search(in, m, std::regex(re)); if(!m.empty()) { std::cout << "input=[" << in << "], regex=[" << re << "]\n " "prefix=[" << m.prefix() << "]\n smatch: "; for(std::size_t n = 0; n < m.size(); ++n) std::cout << "m[" << n << "]=[" << m[n] << "] "; std::cout << "\n suffix=[" << m.suffix() << "]\n"; } else { std::cout << "input=[" << in << "], regex=[" << re << "]: NO MATCH\n"; } } int main() { // greedy match, repeats [a-z] 4 times show_matches("abcdefghi", "a[a-z]{2,4}"); // non-greedy match, repeats [a-z] 2 times show_matches("abcdefghi", "a[a-z]{2,4}?"); // Choice point ordering for quantifiers results in a match // with two repetitions, first matching the substring "aa", // second matching the substring "ba", leaving "ac" not matched // ("ba" appears in the capture clause m[1]) show_matches("aabaac", "(aa|aabaac|ba|b|c)*"); // Choice point ordering for quantifiers makes this regex // calculate the greatest common divisor between 10 and 15 // (the answer is 5, and it populates m[1] with "aaaaa") show_matches("aaaaaaaaaa,aaaaaaaaaaaaaaa", "^(a+)\\1*,\\1+$"); // the substring "bbb" does not appear in the capture clause m[4] // because it is cleared when the second repetition of the atom // (a+)?(b+)?(c) is matching the substring "ac" // NOTE: gcc gets this wrong - it does not correctly clear the // matches[4] capture group as required by ECMA-262 21.2.2.5.1, // and thus incorrectly captures "bbb" for that group. show_matches("zaacbbbcac", "(z)((a+)?(b+)?(c))*"); } ``` Output: ``` input=[abcdefghi], regex=[a[a-z]{2,4}] prefix=[] smatch: m[0]=[abcde] suffix=[fghi] input=[abcdefghi], regex=[a[a-z]{2,4}?] prefix=[] smatch: m[0]=[abc] suffix=[defghi] input=[aabaac], regex=[(aa|aabaac|ba|b|c)*] prefix=[] smatch: m[0]=[aaba] m[1]=[ba] suffix=[ac] input=[aaaaaaaaaa,aaaaaaaaaaaaaaa], regex=[^(a+)\1*,\1+$] prefix=[] smatch: m[0]=[aaaaaaaaaa,aaaaaaaaaaaaaaa] m[1]=[aaaaa] suffix=[] input=[zaacbbbcac], regex=[(z)((a+)?(b+)?(c))*] prefix=[] smatch: m[0]=[zaacbbbcac] m[1]=[z] m[2]=[ac] m[3]=[a] m[4]=[] m[5]=[c] suffix=[] ``` ### Assertions *Assertion*s match conditions, rather than substrings of the input string. They never consume any characters from the input. Each *Assertion* is one of the following. *Assertion* :: `^` `$` `\` `b` `\` `B` `(` `?` `=` *Disjunction* `)` `(` `?` `!` *Disjunction* `)` The assertion `^` (beginning of line) matches. 1) The position that immediately follows a *LineTerminator* character (this may not be supported) (until C++17) (this is only guaranteed if [`std::regex_constants::multiline`](syntax_option_type "cpp/regex/syntax option type")(C++ only) is enabled) (since C++17) 2) The beginning of the input (unless `[std::regex\_constants::match\_not\_bol](match_flag_type "cpp/regex/match flag type")`(C++ only) is enabled) The assertion `$` (end of line) matches. 1) The position of a *LineTerminator* character (this may not be supported) (until C++17)(this is only guaranteed if [`std::regex_constants::multiline`](syntax_option_type "cpp/regex/syntax option type")(C++ only) is enabled) (since C++17) 2) The end of the input (unless `[std::regex\_constants::match\_not\_eol](match_flag_type "cpp/regex/match flag type")`(C++ only) is enabled) In the two assertions above and in the Atom `.` below, *LineTerminator* is one of the following four characters: `U+000A` (`\n` or line feed), `U+000D` (`\r` or carriage return), `U+2028` (line separator), or `U+2029` (paragraph separator). The assertion `\b` (word boundary) matches. 1) The beginning of a word (current character is a letter, digit, or underscore, and the previous character is not) 2) The end of a word (current character is not a letter, digit, or underscore, and the previous character is one of those) 3) The beginning of input if the first character is a letter, digit, or underscore (unless `[std::regex\_constants::match\_not\_bow](match_flag_type "cpp/regex/match flag type")`(C++ only) is enabled) 4) The end of input if the last character is a letter, digit, or underscore (unless `[std::regex\_constants::match\_not\_eow](match_flag_type "cpp/regex/match flag type")`(C++ only) is enabled) The assertion `\B` (negative word boundary) matches everything EXCEPT the following. 1) The beginning of a word (current character is a letter, digit, or underscore, and the previous character is not one of those or does not exist) 2) The end of a word (current character is not a letter, digit, or underscore (or the matcher is at the end of input), and the previous character is one of those) The assertion `(` `?` `=` *Disjunction* `)` (zero-width positive lookahead) matches if *Disjunction* would match the input at the current position. The assertion `(` `?` `!` *Disjunction* `)` (zero-width negative lookahead) matches if *Disjunction* would NOT match the input at the current position. For both Lookahead assertions, when matching the *Disjunction*, the position is not advanced before matching the remainder of the regular expression. Also, if *Disjunction* can match at the current position in several ways, only the first one is tried. ECMAScript forbids backtracking into the lookahead Disjunctions, which affects the behavior of backreferences into a positive lookahead from the remainder of the regular expression (see example below). Backreferences into the negative lookahead from the rest of the regular expression are always undefined (since the lookahead Disjunction must fail to proceed). Note: Lookahead assertions may be used to create logical AND between multiple regular expressions (see example below). ``` #include <iostream> #include <string> #include <regex> void show_matches(const std::string& in, const std::string& re) { std::smatch m; std::regex_search(in, m, std::regex(re)); if(!m.empty()) { std::cout << "input=[" << in << "], regex=[" << re << "]\n " "prefix=[" << m.prefix() << "]\n smatch: "; for(std::size_t n = 0; n < m.size(); ++n) std::cout << "m[" << n << "]=[" << m[n] << "] "; std::cout << "\n suffix=[" << m.suffix() << "]\n"; } else { std::cout << "input=[" << in << "], regex=[" << re << "]: NO MATCH\n"; } } int main() { // matches the a at the end of input show_matches("aaa", "a$"); // matches the o at the end of the first word show_matches("moo goo gai pan", "o\\b"); // the lookahead matches the empty string immediately after the first b // this populates m[1] with "aaa" although m[0] is empty show_matches("baaabac", "(?=(a+))"); // because backtracking into lookaheads is prohibited, // this matches aba rather than aaaba show_matches("baaabac", "(?=(a+))a*b\\1"); // logical AND via lookahead: this password matches IF it contains // at least one lowercase letter // AND at least one uppercase letter // AND at least one punctuation character // AND be at least 6 characters long show_matches("abcdef", "(?=.*[[:lower:]])(?=.*[[:upper:]])(?=.*[[:punct:]]).{6,}"); show_matches("aB,def", "(?=.*[[:lower:]])(?=.*[[:upper:]])(?=.*[[:punct:]]).{6,}"); } ``` Output: ``` input=[aaa], regex=[a$] prefix=[aa] smatch: m[0]=[a] suffix=[] input=[moo goo gai pan], regex=[o\b] prefix=[mo] smatch: m[0]=[o] suffix=[ goo gai pan] input=[baaabac], regex=[(?=(a+))] prefix=[b] smatch: m[0]=[] m[1]=[aaa] suffix=[aaabac] input=[baaabac], regex=[(?=(a+))a*b\1] prefix=[baa] smatch: m[0]=[aba] m[1]=[a] suffix=[c] input=[abcdef], regex=[(?=.*[[:lower:]])(?=.*[[:upper:]])(?=.*[[:punct:]]).{6,}]: NO MATCH input=[aB,def], regex=[(?=.*[[:lower:]])(?=.*[[:upper:]])(?=.*[[:punct:]]).{6,}] prefix=[] smatch: m[0]=[aB,def] suffix=[] ``` ### Atoms An *Atom* can be one of the following: *Atom* :: *PatternCharacter* `.` `\` *AtomEscape* *CharacterClass* `(` *Disjunction* `)` `(` `?` `:` *Disjunction* `)` where *AtomEscape* :: *DecimalEscape* *CharacterEscape* *CharacterClassEscape* Different kinds of atoms evaluate differently. ### Sub-expressions The *Atom* `(` *Disjunction* `)` is a marked subexpression: it executes the *Disjunction* and stores the copy of the input substring that was consumed by *Disjunction* in the submatch array at the index that corresponds to the number of times the left open parenthesis `(` of marked subexpressions has been encountered in the entire regular expression at this point. Besides being returned in the `[std::match\_results](match_results "cpp/regex/match results")`, the captured submatches are accessible as backreferences (`\1`, `\2`, ...) and can be referenced in regular expressions. Note that `[std::regex\_replace](regex_replace "cpp/regex/regex replace")` uses `$` instead of `\` for backreferences (`$1`, `$2`, ...) in the same manner as `String.prototype.replace` (ECMA-262, part 15.5.4.11). The *Atom* `(` `?` `:` *Disjunction* `)` (non-marking subexpression) simply evaluates the *Disjunction* and does not store its results in the submatch. This is a purely lexical grouping. ### Backreferences *DecimalEscape* :: *DecimalIntegerLiteral* [*lookahead* ∉ *DecimalDigit*] If `\` is followed by a decimal number `N` whose first digit is not `0`, then the escape sequence is considered to be a *backreference*. The value `N` is obtained by calling `[std::regex\_traits::value](regex_traits/value "cpp/regex/regex traits/value")`(C++ only) on each of the digits and combining their results using base-10 arithmetic. It is an error if `N` is greater than the total number of left capturing parentheses in the entire regular expression. When a backreference `\N` appears as an *Atom*, it matches the same substring as what is currently stored in the N'th element of the submatch array. The decimal escape `\0` is NOT a backreference: it is a character escape that represents the [`NUL`](../language/ascii "cpp/language/ascii") character. It cannot be followed by a decimal digit. As above, note that `[std::regex\_replace](regex_replace "cpp/regex/regex replace")` uses `$` instead of `\` for backreferences (`$1`, `$2`, ...). ### Single character matches The *Atom* `.` matches and consumes any one character from the input string except for *LineTerminator* (`U+000D`, `U+000A`, `U+2029`, or `U+2028`). The *Atom* *PatternCharacter*, where *PatternCharacter* is any *SourceCharacter* EXCEPT the characters `^ $ \ . * + ? ( ) [ ] { } |`, matches and consumes one character from the input if it is equal to this *PatternCharacter*. The equality for this and all other single character matches is defined as follows: 1) If `[std::regex\_constants::icase](syntax_option_type "cpp/regex/syntax option type")` is set, the characters are equal if the return values of `[std::regex\_traits::translate\_nocase](regex_traits/translate_nocase "cpp/regex/regex traits/translate nocase")` are equal (C++ only). 2) Otherwise, if `[std::regex\_constants::collate](syntax_option_type "cpp/regex/syntax option type")` is set, the characters are equal if the return values of `[std::regex\_traits::translate](regex_traits/translate "cpp/regex/regex traits/translate")` are equal (C++ only). 3) Otherwise, the characters are equal if `operator==` returns `true`. Each *Atom* that consists of the escape character `\` followed by *CharacterEscape* as well as the special DecimalEscape `\0`, matches and consumes one character from the input if it is equal to the character represented by the *CharacterEscape*. The following character escape sequences are recognized: *CharacterEscape* :: *ControlEscape* `c` *ControlLetter* *HexEscapeSequence* *UnicodeEscapeSequence* *IdentityEscape* Here, *ControlEscape* is one of the following five characters: `f n r t v`. | ControlEscape | Code Unit | Name | | --- | --- | --- | | `f` | U+000C | form feed | | `n` | U+000A | new line | | `r` | U+000D | carriage return | | `t` | U+0009 | horizontal tab | | `v` | U+000B | vertical tab | *ControlLetter* is any lowercase or uppercase ASCII letters and this character escape matches the character whose code unit equals the remainder of dividing the value of the code unit of *ControlLetter* by `32`. For example, `\cD` and `\cd` both match code unit `U+0004` (EOT) because 'D' is `U+0044` and `0x44 % 32 == 4`, and 'd' is `U+0064` and `0x64 % 32 == 4`. *HexEscapeSequence* is the letter `x` followed by exactly two *HexDigit*s (where *HexDigit* is one of `0 1 2 3 4 5 6 7 8 9 a b c d e f A B C D E F`). This character escape matches the character whose code unit equals the numeric value of the two-digit hexadecimal number. *UnicodeEscapeSequence* is the letter `u` followed by exactly four *HexDigit*s. This character escape matches the character whose code unit equals the numeric value of this four-digit hexadecimal number. If the value does not fit in this `[std::basic\_regex](basic_regex "cpp/regex/basic regex")`'s `CharT`, `[std::regex\_error](regex_error "cpp/regex/regex error")` is thrown (C++ only). *IdentityEscape* can be any non-alphanumeric character: for example, another backslash. It matches the character as-is. ``` #include <iostream> #include <string> #include <regex> void show_matches(const std::wstring& in, const std::wstring& re) { std::wsmatch m; std::regex_search(in, m, std::wregex(re)); if(!m.empty()) { std::wcout << L"input=[" << in << L"], regex=[" << re << L"]\n " L"prefix=[" << m.prefix() << L"]\n wsmatch: "; for(std::size_t n = 0; n < m.size(); ++n) std::wcout << L"m[" << n << L"]=[" << m[n] << L"] "; std::wcout << L"\n suffix=[" << m.suffix() << L"]\n"; } else { std::wcout << L"input=[" << in << "], regex=[" << re << L"]: NO MATCH\n"; } } int main() { // Most escapes are similar to C++, save for metacharacters. You will have to // double-escape or use raw strings on the slashes though. show_matches(L"C++\\", LR"(C\+\+\\)"); // Escape sequences and NUL. std::wstring s(L"ab\xff\0cd", 5); show_matches(s, L"(\\0|\\u00ff)"); // No matching for non-BMP Unicode is defined, because ECMAScript uses UTF-16 // atoms. Whether this emoji banana matches can be platform dependent: // These need to be wide-strings! show_matches(L"\U0001f34c", L"[\\u0000-\\ufffe]+"); } ``` Possible output: ``` input=[C++\], regex=[C\+\+\\] prefix=[] wsmatch: m[0]=[C++\] suffix=[] input=[ab?c], regex=[(\0{{!}}\u00ff)] prefix=[ab] wsmatch: m[0]=[?] m[1]=[?] suffix=[c] input=[?], regex=[[\u0000-\ufffe]+]: NO MATCH ``` ### Character classes An Atom can represent a character class, that is, it will match and consume one character if it belongs to one of the predefined groups of characters. A character class can be introduced through a character class escape: *Atom* :: `\` *CharacterClassEscape* or directly. *Atom* :: *CharacterClass* The character class escapes are shorthands for some of the common characters classes, as follows: | CharacterClassEscape | ClassName expression(C++ only) | Meaning | | --- | --- | --- | | `d` | `[[:digit:]]` | digits | | `D` | `[^[:digit:]]` | non-digits | | `s` | `[[:space:]]` | whitespace characters | | `S` | `[^[:space:]]` | non-whitespace characters | | `w` | `[_[:alnum:]]` | alphanumeric characters and the character `_` | | `W` | `[^_[:alnum:]]` | characters other than alphanumeric or `_` | The exact meaning of each of these character class escapes in C++ is defined in terms of the locale-dependent named character classes, and not by explicitly listing the acceptable characters as in ECMAScript. A *CharacterClass* is a bracket-enclosed sequence of *ClassRanges*, optionally beginning with the negation operator `^`. If it begins with `^`, this *Atom* matches any character that is NOT in the set of characters represented by the union of all *ClassRanges*. Otherwise, this *Atom* matches any character that IS in the set of the characters represented by the union of all *ClassRanges*. *CharacterClass* :: `[` `[` *lookahead ∉ {*`^`*}]* *ClassRanges* `]` `[` `^` *ClassRanges* `]` ClassRanges :: [empty] *NonemptyClassRanges* *NonemptyClassRanges* :: *ClassAtom* *ClassAtom* *NonemptyClassRangesNoDash* *ClassAtom* - *ClassAtom* *ClassRanges* If non-empty class range has the form `*ClassAtom* - *ClassAtom*`, it matches any character from a range defined as follows: (C++ only). The first *ClassAtom* must match a single collating element `c1` and the second *ClassAtom* must match a single collating element `c2`. To test if the input character `c` is matched by this range, the following steps are taken: 1) If `[std::regex\_constants::collate](syntax_option_type "cpp/regex/syntax option type")` is not on, the character is matched by direct comparison of code points: `c` is matched if `c1 <= c && c <= c2` 1) Otherwise (if `[std::regex\_constants::collate](syntax_option_type "cpp/regex/syntax option type")` is enabled): 1) If `[std::regex\_constants::icase](syntax_option_type "cpp/regex/syntax option type")` is enabled, all three characters (`c`, `c1`, and `c2`) are passed `[std::regex\_traits::translate\_nocase](regex_traits/translate_nocase "cpp/regex/regex traits/translate nocase")` 2) Otherwise (if `[std::regex\_constants::icase](syntax_option_type "cpp/regex/syntax option type")` is not set), all three characters (`c`, `c1`, and `c2`) are passed `[std::regex\_traits::translate](regex_traits/translate "cpp/regex/regex traits/translate")` 2) The resulting strings are compared using `[std::regex\_traits::transform](regex_traits/transform "cpp/regex/regex traits/transform")` and the character `c` is matched if `transformed c1 <= transformed c && transformed c <= transformed c2` The character `-` is treated literally if it is. * the first or last character of *ClassRanges* * the beginning or end ClassAtom of a dash-separated range specification * immediately follows a dash-separated range specification. * escaped with a backslash as a *CharacterEscape* NonemptyClassRangesNoDash :: *ClassAtom* *ClassAtomNoDash* *NonemptyClassRangesNoDash* *ClassAtomNoDash* - *ClassAtom* *ClassRanges* *ClassAtom* :: `-` *ClassAtomNoDash* *ClassAtomExClass*(C++ only) *ClassAtomCollatingElement*(C++ only) *ClassAtomEquivalence*(C++ only) ClassAtomNoDash :: *SourceCharacter* but not one of `\ or ] or -` `\` *ClassEscape* Each *ClassAtomNoDash* represents a single character -- either *SourceCharacter* as-is or escaped as follows: ClassEscape :: *DecimalEscape* `b` *CharacterEscape* *CharacterClassEscape* The special *ClassEscape* `\b` produces a character set that matches the code unit U+0008 (backspace). Outside of *CharacterClass*, it is the word-boundary *Assertion*. The use of `\B` and the use of any backreference (*DecimalEscape* other than zero) inside a *CharacterClass* is an error. The characters `-` and `]` may need to be escaped in some situations in order to be treated as atoms. Other characters that have special meaning outside of *CharacterClass*, such as `*` or `?`, do not need to be escaped. ### POSIX-based character classes These character classes are an extension to the ECMAScript grammar, and are equivalent to character classes found in the POSIX regular expressions. ClassAtomExClass(C++ only) :: `[:` *ClassName* `:]` Represents all characters that are members of the named character class *ClassName*. The name is valid only if `[std::regex\_traits::lookup\_classname](regex_traits/lookup_classname "cpp/regex/regex traits/lookup classname")` returns non-zero for this name. As described in `[std::regex\_traits::lookup\_classname](regex_traits/lookup_classname "cpp/regex/regex traits/lookup classname")`, the following names are guaranteed to be recognized: `alnum, alpha, blank, cntrl, digit, graph, lower, print, punct, space, upper, xdigit, d, s, w`. Additional names may be provided by system-supplied locales (such as `jdigit` or `jkanji` in Japanese) or implemented as a user-defined extension. ClassAtomCollatingElement(C++ only) :: `[.` *ClassName* `.]` Represents the named collating element, which may represent a single character or a sequence of characters that collates as a single unit under the imbued locale, such as `[.tilde.]` or `[.ch.]` in Czech. The name is valid only if `[std::regex\_traits::lookup\_collatename](regex_traits/lookup_collatename "cpp/regex/regex traits/lookup collatename")` is not an empty string. When using `[std::regex\_constants::collate](syntax_option_type "cpp/regex/syntax option type")`, collating elements can always be used as ends points of a range (e.g. `[[.dz.]-g]` in Hungarian). ClassAtomEquivalence(C++ only) :: `[=` *ClassName* `=]` Represents all characters that are members of the same equivalence class as the named collating element, that is, all characters whose whose primary collation key is the same as that for collating element *ClassName*. The name is valid only if `[std::regex\_traits::lookup\_collatename](regex_traits/lookup_collatename "cpp/regex/regex traits/lookup collatename")` for that name is not an empty string and if the value returned by `[std::regex\_traits::transform\_primary](regex_traits/transform_primary "cpp/regex/regex traits/transform primary")` for the result of the call to `[std::regex\_traits::lookup\_collatename](regex_traits/lookup_collatename "cpp/regex/regex traits/lookup collatename")` is not an empty string. A primary sort key is one that ignores case, accentation, or locale-specific tailorings; so for example `[[=a=]]` matches any of the characters: `a, À, Á, Â, Ã, Ä, Å, A, à, á, â, ã, ä and å.` ClassName(C++ only) :: ClassNameCharacter ClassNameCharacter ClassName ClassNameCharacter(C++ only) :: *SourceCharacter* but not one of `. = :`
programming_docs
cpp std::match_results std::match\_results =================== | Defined in header `[<regex>](../header/regex "cpp/header/regex")` | | | | --- | --- | --- | | ``` template< class BidirIt, class Alloc = std::allocator<std::sub_match<BidirIt>> > class match_results; ``` | (1) | (since C++11) | | ``` namespace pmr { template <class BidirIt> using match_results = std::match_results<BidirIt, std::pmr::polymorphic_allocator< std::sub_match<BidirIt>>>; } ``` | (2) | (since C++17) | The class template `std::match_results` holds a collection of character sequences that represent the result of a regular expression match. This is a specialized allocator-aware container. It can only be default created, obtained from `[std::regex\_iterator](regex_iterator "cpp/regex/regex iterator")`, or modified by `[std::regex\_search](regex_search "cpp/regex/regex search")` or `[std::regex\_match](regex_match "cpp/regex/regex match")`. Because `std::match_results` holds `[std::sub\_match](sub_match "cpp/regex/sub match")`es, each of which is a pair of iterators into the original character sequence that was matched, it's undefined behavior to examine `std::match_results` if the original character sequence was destroyed or iterators to it were invalidated for other reasons. The first `sub_match` (index 0) contained in a `match_result` always represents the full match within a target sequence made by a regex, and subsequent `sub_match`es represent sub-expression matches corresponding in sequence to the left parenthesis delimiting the sub-expression in the regex. `std::match_results` meets the requirements of a [AllocatorAwareContainer](../named_req/allocatorawarecontainer "cpp/named req/AllocatorAwareContainer") and of a [SequenceContainer](../named_req/sequencecontainer "cpp/named req/SequenceContainer"), except that only copy assignment, move assignment, and operations defined for a constant containers are supported, and that the semantics of comparison functions are different from those required for a container. ### Type requirements | | | --- | | -`BidirIt` must meet the requirements of [LegacyBidirectionalIterator](../named_req/bidirectionaliterator "cpp/named req/BidirectionalIterator"). | | -`Alloc` must meet the requirements of [Allocator](../named_req/allocator "cpp/named req/Allocator"). | ### Specializations Several specializations for common character sequence types are provided: | Defined in header `[<regex>](../header/regex "cpp/header/regex")` | | --- | | Type | Definition | | `std::cmatch` | `std::match_results<const char*>` | | `std::wcmatch` | `std::match_results<const wchar_t*>` | | `std::smatch` | `std::match_results<std::string::const_iterator>` | | `std::wsmatch` | `std::match_results<std::wstring::const_iterator>` | | `std::pmr::cmatch` (C++17) | `std::pmr::match_results<const char*>` | | `std::pmr::wcmatch` (C++17) | `std::pmr::match_results<const wchar_t*>` | | `std::pmr::smatch` (C++17) | `std::pmr::match_results<std::string::const_iterator>` | | `std::pmr::wsmatch` (C++17) | `std::pmr::match_results<std::wstring::const_iterator>` | ### Member types | Member type | Definition | | --- | --- | | `allocator_type` | `Allocator` | | `value_type` | `[std::sub\_match](http://en.cppreference.com/w/cpp/regex/sub_match)<BidirIt>` | | `const_reference` | `const value_type&` | | `reference` | `value_type&` | | `const_iterator` | *implementation defined* (depends on the underlying container) | | `iterator` | `const_iterator` | | `difference_type` | `[std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<BidirIt>::difference\_type` | | `size_type` | `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<Alloc>::size\_type` | | `char_type` | `[std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<BidirIt>::value\_type` | | `string_type` | `[std::basic\_string](http://en.cppreference.com/w/cpp/string/basic_string)<char_type>` | ### Member functions | | | | --- | --- | | [(constructor)](match_results/match_results "cpp/regex/match results/match results") | constructs the object (public member function) | | [(destructor)](match_results/~match_results "cpp/regex/match results/~match results") | destructs the object (public member function) | | [operator=](match_results/operator= "cpp/regex/match results/operator=") | assigns the contents (public member function) | | [get\_allocator](match_results/get_allocator "cpp/regex/match results/get allocator") | returns the associated allocator (public member function) | | State | | [ready](match_results/ready "cpp/regex/match results/ready") | checks if the results are available (public member function) | | Size | | [empty](match_results/empty "cpp/regex/match results/empty") | checks whether the match was successful (public member function) | | [size](match_results/size "cpp/regex/match results/size") | returns the number of matches in a fully-established result state (public member function) | | [max\_size](match_results/max_size "cpp/regex/match results/max size") | returns the maximum possible number of sub-matches (public member function) | | Element access | | [length](match_results/length "cpp/regex/match results/length") | returns the length of the particular sub-match (public member function) | | [position](match_results/position "cpp/regex/match results/position") | returns the position of the first character of the particular sub-match (public member function) | | [str](match_results/str "cpp/regex/match results/str") | returns the sequence of characters for the particular sub-match (public member function) | | [operator[]](match_results/operator_at "cpp/regex/match results/operator at") | returns specified sub-match (public member function) | | [prefix](match_results/prefix "cpp/regex/match results/prefix") | returns sub-sequence between the beginning of the target sequence and the beginning of the full match. (public member function) | | [suffix](match_results/suffix "cpp/regex/match results/suffix") | returns sub-sequence between the end of the full match and the end of the target sequence (public member function) | | Iterators | | [begincbegin](match_results/begin "cpp/regex/match results/begin") | returns iterator to the beginning of the list of sub-matches (public member function) | | [endcend](match_results/end "cpp/regex/match results/end") | returns iterator to the end of the list of sub-matches (public member function) | | Format | | [format](match_results/format "cpp/regex/match results/format") | formats match results for output (public member function) | | Modifiers | | [swap](match_results/swap "cpp/regex/match results/swap") | swaps the contents (public member function) | ### Non-member functions | | | | --- | --- | | [operator==operator!=](match_results/operator_cmp "cpp/regex/match results/operator cmp") (removed in C++20) | lexicographically compares the values in the two match result (function template) | | [std::swap(std::match\_results)](match_results/swap2 "cpp/regex/match results/swap2") (C++11) | specializes the [`std::swap`](../algorithm/swap "cpp/algorithm/swap") algorithm (function template) | cpp std::regex_constants::syntax_option_type std::regex\_constants::syntax\_option\_type =========================================== | Defined in header `[<regex>](../header/regex "cpp/header/regex")` | | | | --- | --- | --- | | ``` typedef /*unspecified*/ syntax_option_type; ``` | | (since C++11) | | ``` constexpr syntax_option_type icase = /*unspecified*/; constexpr syntax_option_type nosubs = /*unspecified*/; constexpr syntax_option_type optimize = /*unspecified*/; constexpr syntax_option_type collate = /*unspecified*/; constexpr syntax_option_type ECMAScript = /*unspecified*/; constexpr syntax_option_type basic = /*unspecified*/; constexpr syntax_option_type extended = /*unspecified*/; constexpr syntax_option_type awk = /*unspecified*/; constexpr syntax_option_type grep = /*unspecified*/; constexpr syntax_option_type egrep = /*unspecified*/; ``` | | (since C++11) (until C++17) | | ``` inline constexpr syntax_option_type icase = /*unspecified*/; inline constexpr syntax_option_type nosubs = /*unspecified*/; inline constexpr syntax_option_type optimize = /*unspecified*/; inline constexpr syntax_option_type collate = /*unspecified*/; inline constexpr syntax_option_type ECMAScript = /*unspecified*/; inline constexpr syntax_option_type basic = /*unspecified*/; inline constexpr syntax_option_type extended = /*unspecified*/; inline constexpr syntax_option_type awk = /*unspecified*/; inline constexpr syntax_option_type grep = /*unspecified*/; inline constexpr syntax_option_type egrep = /*unspecified*/; inline constexpr syntax_option_type multiline = /*unspecified*/; ``` | | (since C++17) | The `syntax_option_type` is a [BitmaskType](../named_req/bitmasktype "cpp/named req/BitmaskType") that contains options that govern how regular expressions behave. The possible values for this type (`icase`, `optimize`, etc.) are duplicated inside [`std::basic_regex`](basic_regex/constants "cpp/regex/basic regex/constants"). ### Constants | Value | Effect(s) | | --- | --- | | `icase` | Character matching should be performed without regard to case. | | `nosubs` | When performing matches, all marked sub-expressions `(expr)` are treated as non-marking sub-expressions `(?:expr)`. No matches are stored in the supplied `[std::regex\_match](regex_match "cpp/regex/regex match")` structure and `mark_count()` is zero. | | `optimize` | Instructs the regular expression engine to make matching faster, with the potential cost of making construction slower. For example, this might mean converting a non-deterministic FSA to a deterministic FSA. | | `collate` | Character ranges of the form *"[a-b]"* will be locale sensitive. | | `multiline` (C++17) | Specifies that `^` shall match the beginning of a line and `$` shall match the end of a line, if the ECMAScript engine is selected. | | `ECMAScript` | Use the [Modified ECMAScript regular expression grammar](ecmascript "cpp/regex/ecmascript"). | | `basic` | Use the basic POSIX regular expression grammar ([grammar documentation](http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap09.html#tag_09_03)). | | `extended` | Use the extended POSIX regular expression grammar ([grammar documentation](http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap09.html#tag_09_04)). | | `awk` | Use the regular expression grammar used by the *awk* utility in POSIX ([grammar documentation](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/awk.html#tag_20_06_13_04)). | | `grep` | Use the regular expression grammar used by the *grep* utility in POSIX. This is effectively the same as the `basic` option with the addition of newline `'\n'` as an alternation separator. | | `egrep` | Use the regular expression grammar used by the *grep* utility, with the *-E* option, in POSIX. This is effectively the same as the `extended` option with the addition of newline `'\n'` as an alternation separator in addition to `'|'`. | At most one grammar option must be chosen out of `ECMAScript`, `basic`, `extended`, `awk`, `grep`, `egrep`. If no grammar is chosen, `ECMAScript` is assumed to be selected. The other options serve as modifiers, such that `[std::regex](http://en.cppreference.com/w/cpp/regex/basic_regex)("meow", std::regex::icase)` is equivalent to `[std::regex](http://en.cppreference.com/w/cpp/regex/basic_regex)("meow", std::regex::ECMAScript|std::regex::icase)`. ### Notes Because POSIX uses "leftmost longest" matching rule (the longest matching subsequence is matched, and if there are several such subsequences, the first one is matched), it is not suitable, for example, for parsing markup languages: a POSIX regex such as `"<tag[^>]*>.*</tag>"` would match everything from the first `"<tag"` to the last `"</tag>"`, including every `"</tag>"` and `"<tag>"` inbetween. On the other hand, ECMAScript supports non-greedy matches, and the ECMAScript regex `"<tag[^>]*>.*?</tag>"` would match only until the first closing tag. In C++11, these constants were specified with redundant keyword `static`, which was removed by C++14 via [LWG issue 2053](http://www.open-std.org/jtc1/sc22/wg21/docs/lwg-defects.html#2053). ### Example Illustrates the difference in the matching algorithm between ECMAScript and POSIX regular expressions. ``` #include <iostream> #include <string> #include <regex> int main() { std::string str = "zzxayyzz"; std::regex re1(".*(a|xayy)"); // ECMA std::regex re2(".*(a|xayy)", std::regex::extended); // POSIX std::cout << "Searching for .*(a|xayy) in zzxayyzz:\n"; std::smatch m; std::regex_search(str, m, re1); std::cout << " ECMA (depth first search) match: " << m[0] << '\n'; std::regex_search(str, m, re2); std::cout << " POSIX (leftmost longest) match: " << m[0] << '\n'; } ``` Output: ``` Searching for .*(a|xayy) in zzxayyzz: ECMA (depth first search) match: zzxa POSIX (leftmost longest) match: zzxayy ``` ### See also | | | | --- | --- | | [basic\_regex](basic_regex "cpp/regex/basic regex") (C++11) | regular expression object (class template) | cpp std::regex_iterator std::regex\_iterator ==================== | Defined in header `[<regex>](../header/regex "cpp/header/regex")` | | | | --- | --- | --- | | ``` template< class BidirIt, class CharT = typename std::iterator_traits<BidirIt>::value_type, class Traits = std::regex_traits<CharT> > class regex_iterator ``` | | (since C++11) | `std::regex_iterator` is a read-only iterator that accesses the individual matches of a regular expression within the underlying character sequence. It meets the requirements of a [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"), except that for dereferenceable values `a` and `b` with `a == b`, `*a` and `*b` will not be bound to the same object. On construction, and on every increment, it calls `[std::regex\_search](regex_search "cpp/regex/regex search")` and remembers the result (that is, saves a copy of the value `[std::match\_results](http://en.cppreference.com/w/cpp/regex/match_results)<BidirIt>`). The first object may be read when the iterator is constructed or when the first dereferencing is done. Otherwise, dereferencing only returns a copy of the most recently obtained regex match. The default-constructed `std::regex_iterator` is the end-of-sequence iterator. When a valid `std::regex_iterator` is incremented after reaching the last match (`[std::regex\_search](regex_search "cpp/regex/regex search")` returns `false`), it becomes equal to the end-of-sequence iterator. Dereferencing or incrementing it further invokes undefined behavior. A typical implementation of `std::regex_iterator` holds the begin and the end iterators for the underlying sequence (two instances of BidirIt), a pointer to the regular expression (`const regex_type*`), the match flags (`[std::regex\_constants::match\_flag\_type](match_flag_type "cpp/regex/match flag type")`), and the current match (`[std::match\_results](http://en.cppreference.com/w/cpp/regex/match_results)<BidirIt>`). ### Type requirements | | | --- | | -`BidirIt` must meet the requirements of [LegacyBidirectionalIterator](../named_req/bidirectionaliterator "cpp/named req/BidirectionalIterator"). | ### Specializations Several specializations for common character sequence types are defined: | Defined in header `[<regex>](../header/regex "cpp/header/regex")` | | --- | | Type | Definition | | `cregex_iterator` | `regex_iterator<const char*>` | | `wcregex_iterator` | `regex_iterator<const wchar_t*>` | | `sregex_iterator` | `regex_iterator<std::string::const_iterator>` | | `wsregex_iterator` | `regex_iterator<std::wstring::const_iterator>` | ### Member types | Member type | Definition | | --- | --- | | `value_type` | `[std::match\_results](http://en.cppreference.com/w/cpp/regex/match_results)<BidirIt>` | | `difference_type` | `[std::ptrdiff\_t](../types/ptrdiff_t "cpp/types/ptrdiff t")` | | `pointer` | `const value_type*` | | `reference` | `const value_type&` | | `iterator_category` | `[std::forward\_iterator\_tag](../iterator/iterator_tags "cpp/iterator/iterator tags")` | | `regex_type` | `basic_regex<CharT, Traits>` | ### Member functions | | | | --- | --- | | [(constructor)](regex_iterator/regex_iterator "cpp/regex/regex iterator/regex iterator") | constructs a new `regex_iterator` (public member function) | | (destructor) (implicitly declared) | destructs a `regex_iterator`, including the cached value (public member function) | | [operator=](regex_iterator/operator= "cpp/regex/regex iterator/operator=") | assigns contents (public member function) | | [operator==operator!=](regex_iterator/operator_cmp "cpp/regex/regex iterator/operator cmp") (removed in C++20) | compares two `regex_iterator`s (public member function) | | [operator\*operator->](regex_iterator/operator* "cpp/regex/regex iterator/operator*") | accesses the current match (public member function) | | [operator++operator++(int)](regex_iterator/operator_arith "cpp/regex/regex iterator/operator arith") | advances the iterator to the next match (public member function) | ### Notes It is the programmer's responsibility to ensure that the `[std::basic\_regex](basic_regex "cpp/regex/basic regex")` object passed to the iterator's constructor outlives the iterator. Because the iterator stores a pointer to the regex, incrementing the iterator after the regex was destroyed accesses a dangling pointer. If the part of the regular expression that matched is just an [assertion](ecmascript#Assertions "cpp/regex/ecmascript") (`^`, `$`, `\b`, `\B`), the match stored in the iterator is a zero-length match, that is, `match[0].first == match[0].second`. ### Example ``` #include <regex> #include <iterator> #include <iostream> #include <string> int main() { const std::string s = "Quick brown fox."; std::regex words_regex("[^\\s]+"); auto words_begin = std::sregex_iterator(s.begin(), s.end(), words_regex); auto words_end = std::sregex_iterator(); std::cout << "Found " << std::distance(words_begin, words_end) << " words:\n"; for (std::sregex_iterator i = words_begin; i != words_end; ++i) { std::smatch match = *i; std::string match_str = match.str(); std::cout << match_str << '\n'; } } ``` Output: ``` Found 3 words: Quick brown fox. ``` ### See also | | | | --- | --- | | [match\_results](match_results "cpp/regex/match results") (C++11) | identifies one regular expression match, including all sub-expression matches (class template) | | [regex\_search](regex_search "cpp/regex/regex search") (C++11) | attempts to match a regular expression to any part of a character sequence (function template) | | | | --- | | | cpp std::regex_traits<CharT>::imbue std::regex\_traits<CharT>::imbue ================================ | | | | | --- | --- | --- | | ``` locale_type imbue( locale_type loc ); ``` | | (since C++11) | Replaces the current locale with a copy of `loc`. If `loc` is different than the current locale, then all cached data is invalidated. After the call `getloc() == loc`. ### Parameters | | | | | --- | --- | --- | | loc | - | the locale to imbue | ### Return value The current locale of the traits object. If `imbue()` has been never called for this object, then the global locale at the time of the call is returned. Otherwise, the locale passed to the last call to `imbue()` is returned. ### Example ### See also | | | | --- | --- | | [getloc](getloc "cpp/regex/regex traits/getloc") | gets the locale (public member function) |
programming_docs
cpp std::regex_traits<CharT>::transform_primary std::regex\_traits<CharT>::transform\_primary ============================================= | | | | | --- | --- | --- | | ``` template< class ForwardIt > string_type transform_primary( ForwardIt first, ForwardIt last ) const; ``` | | | For the character sequence `[first, last)`, obtains the primary sort key in the imbued locale's collating order, that is, the sort key that is based on the positions of the letters and collation units in the national alphabet, ignoring case, diacritics, variants, etc. If a primary sort key compares less than another primary sort key with `operator<`, then the character sequence that produced the first sort key comes before the character sequence that produced the second sort key, in the currently imbued locale's primary collation order. The regex library uses this trait to match characters against equivalence classes. For example, the regex `[[=a=]]` is equivalent to the character `c1` if `traits.transform_primary(c1)` is equivalent to `traits.transform_primary("a")` (which is true for any `c1` from `"AÀÁÂÃÄÅaàáâãäå"` in the U.S. English locale). Note that `transform_primary()` takes a character sequence argument because equivalence classes may be multicharacter, such as `[[=ch=]]` in Czech or `[[=dzs=]]` in Hungarian. There is no portable way to define primary sort key in terms of `[std::locale](../../locale/locale "cpp/locale/locale")` since the conversion from the collation key returned by `std::collate::transform()` to the primary equivalence key is locale-specific, and if the user replaces the `[std::collate](../../locale/collate "cpp/locale/collate")` facet, that conversion is no longer known to the standard library's `[std::regex\_traits](../regex_traits "cpp/regex/regex traits")`. Standard library specializations of `[std::regex\_traits](../regex_traits "cpp/regex/regex traits")` return an empty string unless the `[std::collate](../../locale/collate "cpp/locale/collate")` facet of the currently-imbued locale was not replaced by the user, and still matches the system-supplied `[std::collate](../../locale/collate "cpp/locale/collate")` facet), in which case `[std::collate\_byname](http://en.cppreference.com/w/cpp/locale/collate_byname)<charT>::transform(first, last)` is executed and the sort key it produces is converted to the expected primary sort key using a locale-specific conversion. ### Parameters | | | | | --- | --- | --- | | first, last | - | a pair of iterators which determines the sequence of characters to compare | | Type requirements | | -`ForwardIt` must meet the requirements of [LegacyForwardIterator](../../named_req/forwarditerator "cpp/named req/ForwardIterator"). | ### Return value The primary sort key for the character sequence `[first, last)` in the currently imbued locale, ignoring case, variant, diacritics, etc. ### Example Demonstrates the regex feature that works through transform\_primary(). ``` #include <iostream> #include <regex> int main() { std::locale::global(std::locale("en_US.UTF-8")); std::wstring str = L"AÀÁÂÃÄÅaàáâãäå"; std::wregex re(L"[[=a=]]*", std::regex::basic); std::cout << std::boolalpha << std::regex_match(str, re) << '\n'; } ``` Output: ``` true ``` cpp std::regex_traits<CharT>::transform std::regex\_traits<CharT>::transform ==================================== | | | | | --- | --- | --- | | ``` template< class ForwardIt > string_type transform( ForwardIt first, ForwardIt last) const; ``` | | | Obtains the sort key for the character sequence `[first, last)`, such that if a sort key compares less than another sort key with `operator<`, then the character sequence that produced the first sort key comes before the character sequence that produced the second sort key, in the currently imbued locale's collation order. For example when the regex flag `[std::regex\_constants::collate](../syntax_option_type "cpp/regex/syntax option type")` is set, then the sequence `[a-b]` would match some character `c1` if `traits.transform("a") <= traits.transform(c1) <= traits.transform("b")`. Note that this function takes a character sequence as the argument to accomodate to the ranges defined like `[``[.ae.]-d]`. Standard library specializations of `[std::regex\_traits](../regex_traits "cpp/regex/regex traits")` return `[std::use\_facet](http://en.cppreference.com/w/cpp/locale/use_facet)<[std::collate](http://en.cppreference.com/w/cpp/locale/collate)<CharT>>(getloc()).transform(str.data(), str.data() + str.length())` for some temporary string `str` constructed as `string_type str(first, last)`. ### Parameters | | | | | --- | --- | --- | | first, last | - | a pair of [LegacyForwardIterators](../../named_req/forwarditerator "cpp/named req/ForwardIterator") which determines the sequence of characters to compare | | Type requirements | | -`ForwardIt` must meet the requirements of [LegacyForwardIterator](../../named_req/forwarditerator "cpp/named req/ForwardIterator"). | ### Return value The collation key for the character sequence `[first, last)` in the currently imbued locale. ### Example cpp std::regex_traits<CharT>::lookup_collatename std::regex\_traits<CharT>::lookup\_collatename ============================================== | | | | | --- | --- | --- | | ``` template< class ForwardIt > string_type lookup_collatename( ForwardIt first, ForwardIt last ) const; ``` | | | If the character sequence `[first, last)` represents the name of a valid collating element in the currently imbued locale, returns the name of that collating element. Otherwise, returns an empty string. Collating elements are the symbols found in POSIX regular expressions between `[.` and `.]`. For example, `[.a.]` matches the character `a` in the C locale. `[.tilde.]` matches the character `~` in the C locale as well. `[.ch.]` matches the digraph `ch` in Czech locale, but generates `[std::regex\_error](../regex_error "cpp/regex/regex error")` with error code `[std::regex\_constants::error\_collate](../error_type "cpp/regex/error type")` in most other locales. ### Parameters | | | | | --- | --- | --- | | first, last | - | a pair of iterators which determines the sequence of characters that represents a collating element name | | Type requirements | | -`ForwardIt` must meet the requirements of [LegacyForwardIterator](../../named_req/forwarditerator "cpp/named req/ForwardIterator"). | ### Return value The representation of the named collating element as a character string. ### Example ``` #include <iostream> #include <string> #include <regex> struct noisy_traits : std::regex_traits<char> { template< class Iter > string_type lookup_collatename( Iter first, Iter last ) const { string_type result = regex_traits::lookup_collatename(first, last); std::cout << "regex_traits<>::lookup_collatename(\"" << string_type(first, last) << "\") returns \"" << result << "\"\n"; return result; } }; int main() { std::string str = "z|}a"; // C locale collation order: x,y,z,{,|,},~ std::basic_regex<char, noisy_traits> re("[x-[.tilde.]]*a", std::regex::basic); std::cout << std::boolalpha << std::regex_match(str, re) << '\n'; } ``` Output: ``` regex_traits<>::lookup_collatename("tilde") returns "~" true ``` cpp std::regex_traits<CharT>::getloc std::regex\_traits<CharT>::getloc ================================= | | | | | --- | --- | --- | | ``` locale_type getloc() const; ``` | | (since C++11) | Returns the current locale of the traits object. If `[imbue()](imbue "cpp/regex/regex traits/imbue")` has been never called for this object, then the global locale at the time of the call is returned. Otherwise, the locale passed to the last call to `[imbue()](imbue "cpp/regex/regex traits/imbue")` is returned. ### Parameters (none). ### Return value The current locale of the traits object. ### Example ### See also | | | | --- | --- | | [imbue](imbue "cpp/regex/regex traits/imbue") | sets the locale (public member function) | cpp std::regex_traits<CharT>::length std::regex\_traits<CharT>::length ================================= | | | | | --- | --- | --- | | ``` static std::size_t length(const char_type* p); ``` | | | Calculates the length of a null-terminated character sequence, that is, the smallest `i` such that `p[i]==0`. Standard library specializations of `[std::regex\_traits](../regex_traits "cpp/regex/regex traits")` execute `[std::char\_traits](http://en.cppreference.com/w/cpp/string/char_traits)<CharT>::length(p);` ### Parameters | | | | | --- | --- | --- | | p | - | pointer to the first element of the null-terminated character sequence | ### Return value The length of the null-terminated character string. ### Example ``` #include <regex> #include <iostream> int main() { std::cout << std::regex_traits<char>::length(u8"Кошка") << '\n' << std::regex_traits<wchar_t>::length(L"Кошка") << '\n'; } ``` Output: ``` 10 5 ``` cpp std::regex_traits<CharT>::translate_nocase std::regex\_traits<CharT>::translate\_nocase ============================================ | | | | | --- | --- | --- | | ``` CharT translate_nocase(CharT c) const; ``` | | | Obtains the comparison key for the character `c`, such that all characters that are equivalent to this character in the imbued locale, ignoring the case differences, if any, produce the same key. When the regex library needs to match two characters `c1` and `c2` and the flag `[std::regex\_constants::icase](../syntax_option_type "cpp/regex/syntax option type")` is `true`, it executes `regex_traits<>::translate_nocase(c1) == regex_traits<>::translate_nocase(c2)`. Standard library specializations of `[std::regex\_traits](../regex_traits "cpp/regex/regex traits")` return `[std::use\_facet](http://en.cppreference.com/w/cpp/locale/use_facet)<[std::ctype](http://en.cppreference.com/w/cpp/locale/ctype)<CharT>>(getloc()).tolower(c)`, that is, convert `c` to lowercase, using the currently imbued locale. ### Parameters | | | | | --- | --- | --- | | c | - | character that needs to be examined for equivalence, ignoring case | ### Return value The case-insensitive comparison key for `c` in the currently imbued locale. ### Example cpp std::regex_traits<CharT>::regex_traits std::regex\_traits<CharT>::regex\_traits ======================================== | | | | | --- | --- | --- | | ``` regex_traits(); ``` | | | Default-constructs the `[std::regex\_traits](../regex_traits "cpp/regex/regex traits")` object, including default-constructing the private `[std::locale](../../locale/locale "cpp/locale/locale")` member or any other internal state as necessary. ### Parameters (none). ### Return value (none). ### Example ``` #include <iostream> #include <regex> int main() { std::locale::global(std::locale("en_US.utf8")); std::regex_traits<char> r1; std::regex_traits<wchar_t> r2; std::cout << "The regex locale is " << r1.getloc().name() << '\n'; } ``` Output: ``` The regex locale is en_US.utf8 ``` cpp std::regex_traits<CharT>::lookup_classname std::regex\_traits<CharT>::lookup\_classname ============================================ | | | | | --- | --- | --- | | ``` template< class ForwardIt > char_class_type lookup_classname( ForwardIt first, ForwardIt last, bool icase = false ) const; ``` | | | If the character sequence `[first, last)` represents the name of a valid character class in the currently imbued locale (that is, the string between `[:` and `:]` in regular expressions), returns the implementation-defined value representing this character class. Otherwise, returns zero. If the parameter `icase` is `true`, the character class ignores character case, e.g. the regex `[:lower:]` with `[std::regex\_constants::icase](../syntax_option_type "cpp/regex/syntax option type")` generates a call to `regex_traits<>::lookup_classname()` with `[first, last)` indicating the string `"lower"` and `icase == true`. This call returns the same bitmask as the call generated by the regex `[:alpha:]` with `icase == false`. The following character classes are always recognized, in both narrow and wide character forms, and the classifications returned (with `icase == false`) correspond to the matching classifications obtained by the `[std::ctype](../../locale/ctype "cpp/locale/ctype")` facet of the imbued locale, as follows: | character class | `[std::ctype](../../locale/ctype "cpp/locale/ctype")` classification | | --- | --- | | `"alnum"` | `[std::ctype\_base::alnum](../../locale/ctype_base "cpp/locale/ctype base")` | | `"alpha"` | `[std::ctype\_base::alpha](../../locale/ctype_base "cpp/locale/ctype base")` | | `"blank"` | `[std::ctype\_base::blank](../../locale/ctype_base "cpp/locale/ctype base")` | | `"cntrl"` | `[std::ctype\_base::cntrl](../../locale/ctype_base "cpp/locale/ctype base")` | | `"digit"` | `[std::ctype\_base::digit](../../locale/ctype_base "cpp/locale/ctype base")` | | `"graph"` | `[std::ctype\_base::graph](../../locale/ctype_base "cpp/locale/ctype base")` | | `"lower"` | `[std::ctype\_base::lower](../../locale/ctype_base "cpp/locale/ctype base")` | | `"print"` | `[std::ctype\_base::print](../../locale/ctype_base "cpp/locale/ctype base")` | | `"punct"` | `[std::ctype\_base::punct](../../locale/ctype_base "cpp/locale/ctype base")` | | `"space"` | `[std::ctype\_base::space](../../locale/ctype_base "cpp/locale/ctype base")` | | `"upper"` | `[std::ctype\_base::upper](../../locale/ctype_base "cpp/locale/ctype base")` | | `"xdigit"` | `[std::ctype\_base::xdigit](../../locale/ctype_base "cpp/locale/ctype base")` | | `"d"` | `[std::ctype\_base::digit](../../locale/ctype_base "cpp/locale/ctype base")` | | `"s"` | `[std::ctype\_base::space](../../locale/ctype_base "cpp/locale/ctype base")` | | `"w"` | `[std::ctype\_base::alnum](../../locale/ctype_base "cpp/locale/ctype base")` with '\_' optionally added | The classification returned for the string `"w"` may be exactly the same as `"alnum"`, in which case `[isctype()](isctype "cpp/regex/regex traits/isctype")` adds '\_' explicitly. Additional classifications such as `"jdigit"` or `"jkanji"` may be provided by system-supplied locales (in which case they are also accessible through `[std::wctype](../../string/wide/wctype "cpp/string/wide/wctype")`). ### Parameters | | | | | --- | --- | --- | | first, last | - | a pair of iterators which determines the sequence of characters that represents a name of a character class | | icase | - | if true, ignores the upper/lower case distinction in the character classification | | Type requirements | | -`ForwardIt` must meet the requirements of [LegacyForwardIterator](../../named_req/forwarditerator "cpp/named req/ForwardIterator"). | ### Return value The bitmask representing the character classification determined by the given character class, or `char_class_type()` if the class is unknown. ### Example demonstraits a custom regex\_traits implementation of lookup\_classname/isctype. ``` #include <iostream> #include <locale> #include <regex> #include <cwctype> // This custom regex traits uses wctype/iswctype to implement lookup_classname/isctype struct wctype_traits : std::regex_traits<wchar_t> { using char_class_type = std::wctype_t; template<class It> char_class_type lookup_classname(It first, It last, bool=false) const { return std::wctype(std::string(first, last).c_str()); } bool isctype(wchar_t c, char_class_type f) const { return std::iswctype(c, f); } }; int main() { std::locale::global(std::locale("ja_JP.utf8")); std::wcout.sync_with_stdio(false); std::wcout.imbue(std::locale()); std::wsmatch m; std::wstring in = L"風の谷のナウシカ"; // matches all characters (they are classified as alnum) std::regex_search(in, m, std::wregex(L"([[:alnum:]]+)")); std::wcout << "alnums: " << m[1] << '\n'; // prints "風の谷のナウシカ" // matches only the katakana std::regex_search(in, m, std::basic_regex<wchar_t, wctype_traits>(L"([[:jkata:]]+)")); std::wcout << "katakana: " << m[1] << '\n'; // prints "ナウシカ" } ``` Output: ``` alnums: 風の谷のナウシカ katakana: ナウシカ ``` ### See also | | | | --- | --- | | [isctype](isctype "cpp/regex/regex traits/isctype") | indicates membership in a character class (public member function) | | [wctype](../../string/wide/wctype "cpp/string/wide/wctype") | looks up a character classification category in the current C locale (function) | cpp std::regex_traits<CharT>::value std::regex\_traits<CharT>::value ================================ | | | | | --- | --- | --- | | ``` int value( CharT ch, int radix ) const; ``` | | (since C++11) | Determines the value represented by the digit `ch` in the numeric base `radix`, given the currently imbued locale. This function is called by `[std::regex](../basic_regex "cpp/regex/basic regex")` when processing [Quantifiers](../ecmascript#Quantifiers "cpp/regex/ecmascript") such as `{1`} or `{2,5`}, [Backreferences](../ecmascript#Backreferences "cpp/regex/ecmascript") such as `\1`, and hexadecimal and Unicode character escapes. ### Parameters | | | | | --- | --- | --- | | ch | - | the character that may represent a digit | | radix | - | either 8, 10, or 16 | ### Return value The numeric value if `ch` indeed represents a digit in the currently imbued locale that is valid for the numeric base `radix`, or `-1` on error. ### Example ``` #include <iostream> #include <locale> #include <regex> #include <map> // This custom regex traits allows japanese numerals struct jnum_traits : std::regex_traits<wchar_t> { static std::map<wchar_t, int> data; int value(wchar_t ch, int radix ) const { wchar_t up = std::toupper(ch, getloc()); return data.count(up) ? data[up] : regex_traits::value(ch, radix); } }; std::map<wchar_t, int> jnum_traits::data = {{L'〇',0}, {L'一',1}, {L'二',2}, {L'三',3}, {L'四',4}, {L'五',5}, {L'六',6}, {L'七',7}, {L'八',8}, {L'九',9}, {L'A',10}, {L'B',11}, {L'C',12}, {L'D',13}, {L'E',14}, {L'F',15}}; int main() { std::locale::global(std::locale("ja_JP.utf8")); std::wcout.sync_with_stdio(false); std::wcout.imbue(std::locale()); std::wstring in = L"風"; if(std::regex_match(in, std::wregex(L"\\u98a8"))) std::wcout << "\\u98a8 matched " << in << '\n'; if(std::regex_match(in, std::basic_regex<wchar_t, jnum_traits>(L"\\u九八a八"))) std::wcout << L"\\u九八a八 with custom traits matched " << in << '\n'; } ``` Output: ``` \u98a8 matched 風 \u九八a八 with custom traits matched 風 ``` cpp std::regex_traits<CharT>::isctype std::regex\_traits<CharT>::isctype ================================== | | | | | --- | --- | --- | | ``` bool isctype( CharT c, char_class_type f ) const; ``` | | | Determines whether the character `c` belongs to the character class identified by `f`, which, in turn, is a value returned by `[lookup\_classname()](lookup_classname "cpp/regex/regex traits/lookup classname")` or a bitwise OR of several such values. The version of this function provided in the standard library specializations of `[std::regex\_traits](../regex_traits "cpp/regex/regex traits")` does the following: 1) First converts `f` to some temporary value `m` of type `[std::ctype\_base::mask](../../locale/ctype_base "cpp/locale/ctype base")` in implementation-defined manner 2) Then attempts to classify the character in the imbued locale by calling `[std::use\_facet](http://en.cppreference.com/w/cpp/locale/use_facet)<[std::ctype](http://en.cppreference.com/w/cpp/locale/ctype)<CharT>>(getloc()).is(m, c)`. If that returned `true`, `true` is returned by `isctype()`. 3) Otherwise, checks whether `c` equals `'_'` and the bitmask `f` includes the result of calling `[lookup\_classname()](lookup_classname "cpp/regex/regex traits/lookup classname")` for the character class `[:w:]`, in which case `true` is returned. 4) Otherwise, `false` is returned. ### Parameters | | | | | --- | --- | --- | | c | - | the character to classify | | f | - | the bitmask obtained from one or several calls to lookup\_classname() | ### Return value `true` if `c` is classified by `f`, `false` otherwise. ### Notes The description above summarizes C++14; the C++11 phrasing required this function to return true for `'_'` in all cases ([LWG issue 2018](http://www.open-std.org/jtc1/sc22/wg21/docs/lwg-active.html#2018)). ### Example ``` #include <iostream> #include <string> #include <regex> int main() { std::regex_traits<char> t; std::string str_alnum = "alnum"; auto a = t.lookup_classname(str_alnum.begin(), str_alnum.end()); std::string str_w = "w"; // [:w:] is [:alnum:] plus '_' auto w = t.lookup_classname(str_w.begin(), str_w.end()); std::cout << std::boolalpha << t.isctype('A', w) << ' ' << t.isctype('A', a) << '\n' << t.isctype('_', w) << ' ' << t.isctype('_', a) << '\n' << t.isctype(' ', w) << ' ' << t.isctype(' ', a) << '\n'; } ``` Output: ``` true true true false false false ``` demonstraits a custom regex\_traits implementation of lookup\_classname/isctype. ``` #include <iostream> #include <locale> #include <regex> #include <cwctype> // This custom regex traits uses wctype/iswctype to implement lookup_classname/isctype struct wctype_traits : std::regex_traits<wchar_t> { using char_class_type = std::wctype_t; template<class It> char_class_type lookup_classname(It first, It last, bool=false) const { return std::wctype(std::string(first, last).c_str()); } bool isctype(wchar_t c, char_class_type f) const { return std::iswctype(c, f); } }; int main() { std::locale::global(std::locale("ja_JP.utf8")); std::wcout.sync_with_stdio(false); std::wcout.imbue(std::locale()); std::wsmatch m; std::wstring in = L"風の谷のナウシカ"; // matches all characters (they are classified as alnum) std::regex_search(in, m, std::wregex(L"([[:alnum:]]+)")); std::wcout << "alnums: " << m[1] << '\n'; // prints "風の谷のナウシカ" // matches only the katakana std::regex_search(in, m, std::basic_regex<wchar_t, wctype_traits>(L"([[:jkata:]]+)")); std::wcout << "katakana: " << m[1] << '\n'; // prints "ナウシカ" } ``` Output: ``` alnums: 風の谷のナウシカ katakana: ナウシカ ``` ### See also | | | | --- | --- | | [lookup\_classname](lookup_classname "cpp/regex/regex traits/lookup classname") | gets a character class by name (public member function) | | [do\_is](../../locale/ctype/is "cpp/locale/ctype/is") [virtual] | classifies a character or a character sequence (virtual protected member function of `std::ctype<CharT>`) | | [iswctype](../../string/wide/iswctype "cpp/string/wide/iswctype") | classifies a wide character according to the specified LC\_CTYPE category (function) |
programming_docs
cpp std::regex_traits<CharT>::translate std::regex\_traits<CharT>::translate ==================================== | | | | | --- | --- | --- | | ``` CharT translate(CharT c) const; ``` | | | Obtains the comparison key for the character `c`, such that all characters that are equivalent to this character in the imbued locale produce the same key. When the regex library needs to match two characters `c1` and `c2` and the flag `[std::regex\_constants::collate](../syntax_option_type "cpp/regex/syntax option type")` is `true`, it executes `regex_traits<>::translate(c1) == regex_traits<>::translate(c2)`. Standard library specializations of `[std::regex\_traits](../regex_traits "cpp/regex/regex traits")` return `c` unmodified. ### Parameters | | | | | --- | --- | --- | | c | - | character that needs to be examined for equivalence | ### Return value The comparison key for `c` in the currently imbued locale. ### Example cpp std::regex_error::regex_error std::regex\_error::regex\_error =============================== | Defined in header `[<regex>](../../header/regex "cpp/header/regex")` | | | | --- | --- | --- | | ``` regex_error( std::regex_constants::error_type ecode ); ``` | (1) | (since C++11) | | ``` regex_error( const regex_error& other ); ``` | (2) | (since C++11) | 1) Constructs a `regex_error` with a given `ecode` of type `[std::regex\_constants::error\_type](../error_type "cpp/regex/error type")`. 2) Copy constructor. Initializes the contents with those of `other`. If `*this` and `other` both have dynamic type `std::regex_error` then `[std::strcmp](http://en.cppreference.com/w/cpp/string/byte/strcmp)(what(), other.what()) == 0`. ### Parameters | | | | | --- | --- | --- | | ecode | - | error code indicating the error raised in regular expression parsing | | other | - | another `regex_error` object to copy | ### See also | | | | --- | --- | | [error\_type](../error_type "cpp/regex/error type") (C++11) | describes different types of matching errors (typedef) | cpp std::regex_error::operator= std::regex\_error::operator= ============================ | | | | | --- | --- | --- | | ``` regex_error& operator=( const regex_error& other ) noexcept; ``` | | (since C++11) | Assigns the contents with those of `other`. If `*this` and `other` both have dynamic type `std::regex_error` then `[std::strcmp](http://en.cppreference.com/w/cpp/string/byte/strcmp)(what(), other.what()) == 0` after assignment. ### Parameters | | | | | --- | --- | --- | | other | - | another `regex_error` object to assign with | ### Return value `*this`. ### Example cpp std::regex_error::code std::regex\_error::code ======================= | Defined in header `[<regex>](../../header/regex "cpp/header/regex")` | | | | --- | --- | --- | | ``` std::regex_constants::error_type code() const; ``` | | (since C++11) | Returns the `[std::regex\_constants::error\_type](../error_type "cpp/regex/error type")` that was passed to the `[std::regex\_error](../regex_error "cpp/regex/regex error")` constructor. ### See also | | | | --- | --- | | [error\_type](../error_type "cpp/regex/error type") (C++11) | describes different types of matching errors (typedef) | | [(constructor)](regex_error "cpp/regex/regex error/regex error") | constructs a `regex_error` object (public member function) | cpp std::match_results<BidirIt,Alloc>::size std::match\_results<BidirIt,Alloc>::size ======================================== | | | | | --- | --- | --- | | ``` size_type size() const noexcept; ``` | | (since C++11) | Returns the number of submatches, i.e. `[std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(begin(), end())`. Returns `​0​` if `*this` does not represent the result of a successful match. ### Parameters (none). ### Return value The number of submatches. ### Complexity Constant. ### Example ``` #include <iostream> #include <regex> #include <string> int main() { std::regex re("a(a)*b"); std::string target("aaab"); std::smatch sm; std::cout << sm.size() << '\n'; std::regex_match(target, sm, re); std::cout << sm.size() << '\n'; } ``` Output: ``` 0 2 ``` ### See also | | | | --- | --- | | [begincbegin](begin "cpp/regex/match results/begin") | returns iterator to the beginning of the list of sub-matches (public member function) | | [endcend](end "cpp/regex/match results/end") | returns iterator to the end of the list of sub-matches (public member function) | cpp std::match_results<BidirIt,Alloc>::format std::match\_results<BidirIt,Alloc>::format ========================================== | | | | | --- | --- | --- | | ``` template< class OutputIt > OutputIt format( OutputIt out, const char_type* fmt_first, const char_type* fmt_last, std::regex_constants::match_flag_type flags = std::regex_constants::format_default ) const; ``` | (1) | (since C++11) | | ``` template< class OutputIt, class ST, class SA > OutputIt format( OutputIt out, const basic_string<char_type,ST,SA>& fmt, std::regex_constants::match_flag_type flags = std::regex_constants::format_default ) const; ``` | (2) | (since C++11) | | ``` template< class ST, class SA > std::basic_string<char_type,ST,SA> format( const std::basic_string<char_type,ST,SA>& fmt, std::regex_constants::match_flag_type flags = std::regex_constants::format_default ) const; ``` | (3) | (since C++11) | | ``` string_type format( const char_type* fmt_s, std::regex_constants::match_flag_type flags = std::regex_constants::format_default ) const; ``` | (4) | (since C++11) | `format` outputs a format string, replacing any format specifiers or escape sequences in that string with match data from `*this`. 1) The format character sequence is defined by the range `[fmt_first, fmt_last)`. The resulting character sequence is copied to `out`. 2) The format character sequence is defined by the characters in `fmt`. The resulting character sequence is copied to `out`. 3-4) The format character sequence is defined by the characters in `fmt` and `fmt_s` respectively. The resulting character sequence is copied to a newly constructed `[std::basic\_string](../../string/basic_string "cpp/string/basic string")`, which is returned. The `flags` bitmask determines which format specifiers and escape sequences are recognized. The behavior of `format` is undefined if `ready() != true`. ### Parameters | | | | | --- | --- | --- | | fmt\_begin, fmt\_end | - | pointers to a range of characters defining the format character sequence | | fmt | - | `[std::basic\_string](../../string/basic_string "cpp/string/basic string")` defining the format character sequence | | fmt\_s | - | pointer to a null-terminated character string defining the format character sequence | | out | - | iterator that the resulting character sequence is copied to | | flags | - | `[std::regex\_constants::match\_flag\_type](../match_flag_type "cpp/regex/match flag type")` bitmask specifying which format specifiers and escape sequences are recognized | | Type requirements | | -`OutputIt` must meet the requirements of [LegacyOutputIterator](../../named_req/outputiterator "cpp/named req/OutputIterator"). | ### Return value 1-2) `out` 3-4) The newly constructed string containing resulting character sequence. ### Exceptions May throw implementation-defined exceptions. ### Example ``` #include <iostream> #include <string> #include <regex> int main() { std::string s = "for a good time, call 867-5309"; std::regex phone_regex("\\d{3}-\\d{4}"); std::smatch phone_match; if (std::regex_search(s, phone_match, phone_regex)) { std::string fmt_s = phone_match.format( "$`" // $` means characters before the match "[$&]" // $& means the matched characters "$'"); // $' means characters following the match std::cout << fmt_s << '\n'; } } ``` Output: ``` for a good time, call [867-5309] ``` ### See also | | | | --- | --- | | [regex\_replace](../regex_replace "cpp/regex/regex replace") (C++11) | replaces occurrences of a regular expression with formatted replacement text (function template) | | [match\_flag\_type](../match_flag_type "cpp/regex/match flag type") (C++11) | options specific to matching (typedef) | cpp std::match_results<BidirIt,Alloc>::ready std::match\_results<BidirIt,Alloc>::ready ========================================= | | | | | --- | --- | --- | | ``` bool ready() const; ``` | | (since C++11) | Indicates if the match results are ready (valid) or not. A default-constructed match result has no result state (is not *ready*), and can only be made ready by one of the regex algorithms. The *ready* state implies that all match results have been fully established. The result of calling most member functions of the match\_results object that is not *ready* is undefined. ### Return value `true` if the match results are ready, `false` otherwise. ### Example ``` #include <iostream> #include <regex> #include <string> int main() { std::string target("pattern"); std::smatch sm; std::cout << "default constructed smatch is " << (sm.ready() ? " ready\n" : " not ready\n"); std::regex re1("tte"); std::regex_search(target, sm, re1); std::cout << "after search, smatch is " << (sm.ready() ? " ready\n" : " not ready\n"); } ``` Output: ``` default constructed smatch is not ready after search, smatch is ready ``` cpp std::match_results<BidirIt,Alloc>::get_allocator std::match\_results<BidirIt,Alloc>::get\_allocator ================================================== | | | | | --- | --- | --- | | ``` allocator_type get_allocator() const; ``` | | (since C++11) | Returns the allocator associated with the object. ### Parameters (none). ### Return value The associated allocator. ### Complexity Constant. cpp std::match_results<BidirIt,Alloc>::prefix std::match\_results<BidirIt,Alloc>::prefix ========================================== | | | | | --- | --- | --- | | ``` const_reference prefix() const; ``` | | (since C++11) | Obtains a reference to the `[std::sub\_match](../sub_match "cpp/regex/sub match")` object representing the target sequence between the start of the beginning of the target sequence and the start of the entire match of the regular expression. The behavior is undefined unless `ready() == true`. ### Parameters (none). ### Return value Reference to the unmatched prefix. ### Example ``` #include <iostream> #include <regex> #include <string> int main() { std::regex re("a(a)*b"); std::string target("baaaby"); std::smatch sm; std::regex_search(target, sm, re); std::cout << sm.prefix().str() << '\n'; } ``` Output: ``` b ``` ### See also | | | | --- | --- | | [suffix](suffix "cpp/regex/match results/suffix") | returns sub-sequence between the end of the full match and the end of the target sequence (public member function) | cpp std::match_results<BidirIt,Alloc>::~match_results std::match\_results<BidirIt,Alloc>::~match\_results =================================================== | | | | | --- | --- | --- | | ``` ~match_results(); ``` | | (since C++11) | Destructs the `match_results` object and the associated sub-matches. ### Complexity Linear in the number of sub-matches. cpp std::match_results<BidirIt,Alloc>::operator[] std::match\_results<BidirIt,Alloc>::operator[] ============================================== | | | | | --- | --- | --- | | ``` const_reference operator[]( size_type n ) const; ``` | | (since C++11) | If `n > 0` and `n < size()`, returns a reference to the `[std::sub\_match](../sub_match "cpp/regex/sub match")` representing the part of the target sequence that was matched by the *n*th captured [marked subexpression](../ecmascript#Sub-expressions "cpp/regex/ecmascript")). If `n == 0`, returns a reference to the `[std::sub\_match](../sub_match "cpp/regex/sub match")` representing the part of the target sequence matched by the entire matched regular expression. if `n >= size()`, returns a reference to a `[std::sub\_match](../sub_match "cpp/regex/sub match")` representing an unmatched sub-expression (an empty subrange of the target sequence). The behavior is undefined unless `ready() == true`. ### Parameters | | | | | --- | --- | --- | | n | - | integral number specifying which match to return | ### Return value Reference to the `[std::sub\_match](../sub_match "cpp/regex/sub match")` representing the specified matched subrange within the target sequence. ### Example ``` #include <iostream> #include <regex> #include <string> int main() { std::string target("baaaby"); std::smatch sm; std::regex re1("a(a)*b"); std::regex_search(target, sm, re1); std::cout << "entire match: " << sm[0] << '\n' << "submatch #1: " << sm[1] << '\n'; std::regex re2("a(a*)b"); std::regex_search(target, sm, re2); std::cout << "entire match: " << sm[0] << '\n' << "submatch #1: " << sm[1] << '\n'; } ``` Output: ``` entire match: aaab submatch #1: a entire match: aaab submatch #1: aa ``` ### See also | | | | --- | --- | | [str](str "cpp/regex/match results/str") | returns the sequence of characters for the particular sub-match (public member function) | cpp std::match_results<BidirIt,Alloc>::swap std::match\_results<BidirIt,Alloc>::swap ======================================== | | | | | --- | --- | --- | | ``` void swap( match_results& other ) noexcept; ``` | | (since C++11) | Exchanges the shared states of two `match_results` objects. ### Parameters | | | | | --- | --- | --- | | other | - | the `match_results` to swap with | ### Return value (none). ### Example ### See also | | | | --- | --- | | [std::swap(std::match\_results)](swap2 "cpp/regex/match results/swap2") (C++11) | specializes the [`std::swap`](../../algorithm/swap "cpp/algorithm/swap") algorithm (function template) | cpp std::match_results<BidirIt,Alloc>::max_size std::match\_results<BidirIt,Alloc>::max\_size ============================================= | | | | | --- | --- | --- | | ``` size_type max_size() const noexcept; ``` | | (since C++11) | Returns the maximum number of submatches the `match_results` type is able to hold due to system or library implementation limitations, i.e. `[std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(begin(), end())` for the largest number of submatches. ### Parameters (none). ### Return value Maximum number of submatches. ### Complexity Constant. cpp std::match_results<BidirIt,Alloc>::length std::match\_results<BidirIt,Alloc>::length ========================================== | | | | | --- | --- | --- | | ``` difference_type length( size_type n = 0 ) const; ``` | | (since C++11) | Returns the length of the specified sub-match. If `n == 0`, the length of the entire matched expression is returned. If `n > 0 && n < size()`, the length of *n*th sub-match is returned. if `n >= size()`, a length of the unmatched match is returned. The call is equivalent to `(*this)[n].length()`. ### Parameters | | | | | --- | --- | --- | | n | - | integral number specifying which match to examine | ### Return value The length of the specified match or sub-match. ### See also | | | | --- | --- | | [operator[]](operator_at "cpp/regex/match results/operator at") | returns specified sub-match (public member function) | | [length](../sub_match/length "cpp/regex/sub match/length") | returns the length of the match (if any) (public member function of `std::sub_match<BidirIt>`) | cpp std::match_results<BidirIt,Alloc>::str std::match\_results<BidirIt,Alloc>::str ======================================= | | | | | --- | --- | --- | | ``` string_type str( size_type n = 0 ) const; ``` | | (since C++11) | Returns a string representing the indicated sub-match. If `n == 0`, a string representing entire matched expression is returned. If `n > 0 && n < size()`, a string representing *n*th sub-match is returned. if `n >= size()`, a string representing the unmatched match is returned. The call is equivalent to `string_type((*this)[n])`; ### Parameters | | | | | --- | --- | --- | | n | - | integral number specifying which match to return | ### Return value Returns a string representing the specified match or sub match. ### Example ``` #include <iostream> #include <regex> #include <string> int main() { std::string target("baaaby"); std::smatch sm; std::regex re1("a(a)*b"); std::regex_search(target, sm, re1); std::cout << "entire match: " << sm.str(0) << '\n' << "submatch #1: " << sm.str(1) << '\n'; std::regex re2("a(a*)b"); std::regex_search(target, sm, re2); std::cout << "entire match: " << sm.str(0) << '\n' << "submatch #1: " << sm.str(1) << '\n'; } ``` Output: ``` entire match: aaab submatch #1: a entire match: aaab submatch #1: aa ``` ### See also | | | | --- | --- | | [operator[]](operator_at "cpp/regex/match results/operator at") | returns specified sub-match (public member function) | cpp std::match_results<BidirIt,Alloc>::position std::match\_results<BidirIt,Alloc>::position ============================================ | | | | | --- | --- | --- | | ``` difference_type position( size_type n = 0 ) const; ``` | | (since C++11) | Returns the position of the first character of the specified sub-match. If `n == 0`, the position of the first character of the entire matched expression is returned. If `n > 0 && n < size()`, the position of the first character of the *n*th sub-match is returned. if `n >= size()`, a position of the first character of the unmatched match is returned. ### Parameters | | | | | --- | --- | --- | | n | - | integral number specifying which match to examine | ### Return value The position of the first character of the specified match or sub-match. ### Example ``` #include <iostream> #include <regex> #include <string> int main() { std::regex re("a(a)*b"); std::string target("aaab"); std::smatch sm; std::regex_match(target, sm, re); std::cout << sm.position(1) << '\n'; } ``` Output: ``` 1 ``` ### See also | | | | --- | --- | | [operator[]](operator_at "cpp/regex/match results/operator at") | returns specified sub-match (public member function) | cpp std::swap(std::match_results) std::swap(std::match\_results) ============================== | Defined in header `[<regex>](../../header/regex "cpp/header/regex")` | | | | --- | --- | --- | | ``` template< class BidirIt, class Alloc > void swap( match_results<BidirIt,Alloc>& x1, match_results<BidirIt,Alloc>& x2 ) noexcept; ``` | | (since C++11) | Specializes the `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` algorithm for `[std::match\_results](../match_results "cpp/regex/match results")`. Exchanges the contents of `x1` with those of `x2`. Effectively calls `x1.swap(x2)`. ### Parameters | | | | | --- | --- | --- | | x1, x2 | - | the match\_results objects whose contents will be swapped | | Type requirements | | -`BidirIt` must meet the requirements of [LegacyBidirectionalIterator](../../named_req/bidirectionaliterator "cpp/named req/BidirectionalIterator"). | | -`Alloc` must meet the requirements of [Allocator](../../named_req/allocator "cpp/named req/Allocator"). | ### Return value (none). ### Example ### See also | | | | --- | --- | | [swap](swap "cpp/regex/match results/swap") | swaps the contents (public member function) |
programming_docs
cpp std::match_results<BidirIt,Alloc>::operator= std::match\_results<BidirIt,Alloc>::operator= ============================================= | Defined in header `[<regex>](../../header/regex "cpp/header/regex")` | | | | --- | --- | --- | | ``` match_results& operator=( const match_results& other ); ``` | (1) | (since C++11) | | ``` match_results& operator=( match_results&& other ) noexcept; ``` | (2) | (since C++11) | Assigns the contents. 1) Copy assignment operator. Assigns the contents of `other`. 2) Move assignment operator. Assigns the contents of `other` using move semantics. `other` is in a valid, but unspecified state after the operation. ### Parameters | | | | | --- | --- | --- | | other | - | another match results object | ### Return value `*this`. ### Exceptions 1) May throw implementation-defined exceptions. cpp std::match_results<BidirIt,Alloc>::suffix std::match\_results<BidirIt,Alloc>::suffix ========================================== | | | | | --- | --- | --- | | ``` const_reference suffix() const; ``` | | (since C++11) | Obtains a reference to the `[std::sub\_match](../sub_match "cpp/regex/sub match")` object representing the target sequence between the end of the entire match of the regular expression and the end of the target sequence. The behavior is undefined unless `[ready()](ready "cpp/regex/match results/ready")` is `true`. ### Parameters (none). ### Return value Reference to the unmatched suffix. ### Example ``` #include <iostream> #include <regex> #include <string> int main() { std::regex re("a(a)*by"); std::string target("baaaby123"); std::smatch sm; std::regex_search(target, sm, re); std::cout << sm.suffix() << '\n'; } ``` Output: ``` 123 ``` ### See also | | | | --- | --- | | [prefix](prefix "cpp/regex/match results/prefix") | returns sub-sequence between the beginning of the target sequence and the beginning of the full match. (public member function) | cpp operator==,!=(std::match_results) operator==,!=(std::match\_results) ================================== | Defined in header `[<regex>](../../header/regex "cpp/header/regex")` | | | | --- | --- | --- | | ``` template< class BidirIt, class Alloc > bool operator==( match_results<BidirIt,Alloc>& lhs, match_results<BidirIt,Alloc>& rhs ); ``` | (1) | (since C++11) | | ``` template< class BidirIt, class Alloc > bool operator!=( match_results<BidirIt,Alloc>& lhs, match_results<BidirIt,Alloc>& rhs ); ``` | (2) | (since C++11) (until C++20) | Compares two `match_results` objects. Two `match_results` are equal if the following conditions are met: * neither of the objects is *ready*, *or* * both match results are *ready* and the following conditions are met: * `lhs.empty()` and `rhs.empty()`, *or* * `!lhs.empty()` and `!rhs.empty()` and the following conditions are met: + `lhs.prefix() == rhs.prefix()` + `lhs.size() == rhs.size() && [std::equal](http://en.cppreference.com/w/cpp/algorithm/equal)(lhs.begin(), lhs.end(), rhs.begin())` + `lhs.suffix() == rhs.suffix()` 1) Checks if `lhs` and `rhs` are equal. 2) Checks if `lhs` and `rhs` are not equal. | | | | --- | --- | | The `!=` operator is [synthesized](../../language/operators#Relational_operators "cpp/language/operators") from `operator==`. | (since C++20) | ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | match results to compare | | Type requirements | | -`BidirIt` must meet the requirements of [LegacyBidirectionalIterator](../../named_req/bidirectionaliterator "cpp/named req/BidirectionalIterator"). | | -`Alloc` must meet the requirements of [Allocator](../../named_req/allocator "cpp/named req/Allocator"). | ### Return value 1) `true` if `lhs` and `rhs` are equal, `false` otherwise. 2) `true` if `lhs` and `rhs` are not equal, `false` otherwise. ### Exceptions May throw implementation-defined exceptions. ### Example cpp std::match_results<BidirIt,Alloc>::empty std::match\_results<BidirIt,Alloc>::empty ========================================= | | | | | --- | --- | --- | | ``` bool empty() const; ``` | | (since C++11) (until C++20) | | ``` [[nodiscard]] bool empty() const; ``` | | (since C++20) | Checks whether the match was successful. ### Parameters (none). ### Return value `true` if `*this` represents the result of a failed match, `false` otherwise, i.e. `size() == 0`. ### Exceptions May throw implementation-defined exceptions. ### Complexity Constant. ### See also | | | | --- | --- | | [size](size "cpp/regex/match results/size") | returns the number of matches in a fully-established result state (public member function) | cpp std::match_results<BidirIt,Alloc>::begin, std::match_results<BidirIt,Alloc>::cbegin std::match\_results<BidirIt,Alloc>::begin, std::match\_results<BidirIt,Alloc>::cbegin ===================================================================================== | | | | | --- | --- | --- | | ``` iterator begin() noexcept; ``` | | (since C++11) | | ``` const_iterator begin() const noexcept; ``` | | (since C++11) | | ``` const_iterator cbegin() const noexcept; ``` | | (since C++11) | Returns an iterator to the beginning of the list of sub-matches. If match was successful, the iterator will point to the entire matched expression. ### Parameters (none). ### Return value Iterator to the first sub-match. ### Complexity Constant. ### See also | | | | --- | --- | | [endcend](end "cpp/regex/match results/end") | returns iterator to the end of the list of sub-matches (public member function) | cpp std::match_results<BidirIt,Alloc>::match_results std::match\_results<BidirIt,Alloc>::match\_results ================================================== | | | | | --- | --- | --- | | ``` match_results() : match_results(Allocator()) { } ``` | (1) | (since C++11) | | ``` explicit match_results( const Allocator& a ); ``` | (2) | (since C++11) | | ``` match_results( const match_results& rhs ); ``` | (3) | (since C++11) | | ``` match_results( match_results&& rhs ) noexcept; ``` | (4) | (since C++11) | 1) Default constructor. Constructs a match result with no established result state (`ready() != true`). 2) Constructs a match result with no established result state (`ready() != true`) using a copy of `a` as the allocator. 3) Copy constructor. Constructs a match result with a copy of `rhs`. 4) Move constructor. Constructs a match result with the contents of `rhs` using move semantics. `rhs` is in valid, but unspecified state after the call. ### Parameters | | | | | --- | --- | --- | | a | - | allocator to use for all memory allocations of this container | | rhs | - | another match\_result to use as source to initialize the match\_result with | ### Exceptions 1-3) May throw implementation-defined exceptions. ### Example ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [P0935R0](https://wg21.link/P0935R0) | C++11 | default constructor was explicit | made implicit | cpp std::match_results<BidirIt,Alloc>::end, std::match_results<BidirIt,Alloc>::cend std::match\_results<BidirIt,Alloc>::end, std::match\_results<BidirIt,Alloc>::cend ================================================================================= | | | | | --- | --- | --- | | ``` iterator end() noexcept; ``` | | (since C++11) | | ``` const_iterator end() const noexcept; ``` | | (since C++11) | | ``` const_iterator cend() const noexcept; ``` | | (since C++11) | Returns an iterator to the end of the list of sub-matches. ### Parameters (none). ### Return value Iterator to the element past the last sub-match. ### Complexity Constant. ### See also | | | | --- | --- | | [begincbegin](begin "cpp/regex/match results/begin") | returns iterator to the beginning of the list of sub-matches (public member function) | cpp std::sub_match<BidirIt>::compare std::sub\_match<BidirIt>::compare ================================= | | | | | --- | --- | --- | | ``` int compare( const sub_match& m ) const; ``` | (1) | (since C++11) | | ``` int compare( const string_type& s ) const; ``` | (2) | (since C++11) | | ``` int compare( const value_type* c ) const; ``` | (3) | (since C++11) | 1) Compares two `sub_match` directly by comparing their underlying character sequences. Equivalent to `str().compare(m.str())`. 2) Compares a `sub_match` with a `[std::basic\_string](../../string/basic_string "cpp/string/basic string")`. Equivalent to `str().compare(s)`. 3) Compares a `sub_match` with a null-terminated sequence of the underlying character type pointed to by `s`. Equivalent to `str().compare(c)`. This function is infrequently used directly by application code. Instead, one of the non-member comparison operators is used. ### Parameters | | | | | --- | --- | --- | | m | - | a reference to another sub\_match | | s | - | a reference to a string to compare to | | c | - | a pointer to a null-terminated character sequence of the underlying `value_type` to compare to | ### Return value A value less than zero if this `sub_match` is *less* than the other character sequence, zero if the both underlying character sequences are equal, greater than zero if this `sub_match` is *greater* than the other character sequence. ### Example ### See also | | | | --- | --- | | [compare](../../string/basic_string/compare "cpp/string/basic string/compare") | compares two strings (public member function of `std::basic_string<CharT,Traits,Allocator>`) | | [stroperator string\_type](str "cpp/regex/sub match/str") | converts to the underlying string type (public member function) | | [operator==operator!=operator<operator<=operator>operator>=operator<=>](operator_cmp "cpp/regex/sub match/operator cmp") (removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(C++20) | compares a `sub_match` with another `sub_match`, a string, or a character (function template) | cpp operator<<(std::sub_match) operator<<(std::sub\_match) =========================== | | | | | --- | --- | --- | | ``` template< class CharT, class Traits, class BidirIt > std::basic_ostream<CharT,Traits>& operator<<( std::basic_ostream<CharT,Traits>& os, const sub_match<BidirIt>& m ); ``` | | (since C++11) | Writes the representation of the matched subsequence `m` to the output stream `os`. Equivalent to `os << m.str()`. ### Parameters | | | | | --- | --- | --- | | os | - | output stream to write the representation to | | m | - | a sub-match object to output | ### Return value `os`. ### Example cpp std::sub_match<BidirIt>::sub_match std::sub\_match<BidirIt>::sub\_match ==================================== | | | | | --- | --- | --- | | ``` constexpr sub_match(); ``` | | (since C++11) | Default constructs a `[std::sub\_match](../sub_match "cpp/regex/sub match")`. The `matched` member is set to `false` and the inherited members `first` and `second` are value-initialized. This is the only publicly accessible and defined constructor. ### Parameters (none). cpp std::sub_match<BidirIt>::length std::sub\_match<BidirIt>::length ================================ | | | | | --- | --- | --- | | ``` difference_type length() const; ``` | | | ### Parameters (none). ### Return value Returns the number of characters in the match, i.e. `[std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(first, second)` if the match is valid, 0 otherwise. ### Complexity Constant. cpp std::sub_match<BidirIt>::operator string_type, std::sub_match<BidirIt>::str std::sub\_match<BidirIt>::operator string\_type, std::sub\_match<BidirIt>::str ============================================================================== | | | | | --- | --- | --- | | ``` operator string_type() const; ``` | (1) | | | ``` string_type str() const; ``` | (2) | | Converts to an object of the underlying `[std::basic\_string](../../string/basic_string "cpp/string/basic string")` type. The first version is an implicit conversion, the second one is explicit. ### Parameters (none). ### Return value Returns the matched character sequence as an object of the underlying `[std::basic\_string](../../string/basic_string "cpp/string/basic string")` type. If the `matched` member is `false`, then the empty string is returned. ### Complexity Linear in the length of the underlying character sequence. ### Example ``` #include <cassert> #include <iostream> #include <regex> #include <string> int main() { const std::string html {R"("<a href="https://cppreference.com/">)"}; const std::regex url {"https://([a-z]+)\\.([a-z]{3})"}; std::smatch parts; std::regex_search(html, parts, url); for (std::ssub_match const& sub: parts) { const std::string s = sub; // (1) implicit conversion assert(s == sub.str()); // (2) std::cout << s << '\n'; } } ``` Output: ``` https://cppreference.com cppreference com ``` cpp operator==,!=,<,<=,>,>=,<=>(std::sub_match) operator==,!=,<,<=,>,>=,<=>(std::sub\_match) ============================================ | Defined in header `[<regex>](../../header/regex "cpp/header/regex")` | | | | --- | --- | --- | | Direct comparison | | | | ``` template< class BidirIt > bool operator==( const std::sub_match<BidirIt>& lhs, const std::sub_match<BidirIt>& rhs ); ``` | (1) | (since C++11) | | ``` template< class BidirIt > bool operator!=( const std::sub_match<BidirIt>& lhs, const std::sub_match<BidirIt>& rhs ); ``` | (2) | (since C++11) (until C++20) | | ``` template< class BidirIt > bool operator<( const std::sub_match<BidirIt>& lhs, const std::sub_match<BidirIt>& rhs ); ``` | (3) | (since C++11) (until C++20) | | ``` template< class BidirIt > bool operator<=( const std::sub_match<BidirIt>& lhs, const std::sub_match<BidirIt>& rhs ); ``` | (4) | (since C++11) (until C++20) | | ``` template< class BidirIt > bool operator>( const std::sub_match<BidirIt>& lhs, const std::sub_match<BidirIt>& rhs ); ``` | (5) | (since C++11) (until C++20) | | ``` template< class BidirIt > bool operator>=( const std::sub_match<BidirIt>& lhs, const std::sub_match<BidirIt>& rhs ); ``` | (6) | (since C++11) (until C++20) | | ``` template< class BidirIt > /*comp-cat*/ operator<=>( const std::sub_match<BidirIt>& lhs, const std::sub_match<BidirIt>& rhs ); ``` | (7) | (since C++20) | | `std::sub_match` and `std::basic_string` | | | | ``` template< class BidirIt, class Traits, class Alloc > bool operator==( const std::sub_match<BidirIt>& sm, const std::basic_string< typename std::iterator_traits<BidirIt>::value_type, Traits,Alloc>& rhs ); ``` | (8) | (since C++11) | | ``` template< class BidirIt, class Traits, class Alloc > bool operator!=( const std::sub_match<BidirIt>& sm, const std::basic_string< typename std::iterator_traits<BidirIt>::value_type, Traits,Alloc>& st ); ``` | (9) | (since C++11) (until C++20) | | ``` template< class BidirIt, class Traits, class Alloc > bool operator<( const std::sub_match<BidirIt>& sm, const std::basic_string< typename std::iterator_traits<BidirIt>::value_type, Traits,Alloc>& st ); ``` | (10) | (since C++11) (until C++20) | | ``` template< class BidirIt, class Traits, class Alloc > bool operator<=( const std::sub_match<BidirIt>& sm, const std::basic_string< typename std::iterator_traits<BidirIt>::value_type, Traits,Alloc>& st ); ``` | (11) | (since C++11) (until C++20) | | ``` template< class BidirIt, class Traits, class Alloc > bool operator>( const std::sub_match<BidirIt>& sm, const std::basic_string< typename std::iterator_traits<BidirIt>::value_type, Traits,Alloc>& st ); ``` | (12) | (since C++11) (until C++20) | | ``` template< class BidirIt, class Traits, class Alloc > bool operator>=( const std::sub_match<BidirIt>& sm, const std::basic_string< typename std::iterator_traits<BidirIt>::value_type, Traits,Alloc>& st ); ``` | (13) | (since C++11) (until C++20) | | ``` template< class BidirIt, class Traits, class Alloc > /*comp-cat*/ operator<=>( const std::sub_match<BidirIt>& sm, const std::basic_string< typename std::iterator_traits<BidirIt>::value_type, Traits,Alloc>& st ); ``` | (14) | (since C++20) | | `std::basic_string` and `std::sub_match` | | | | ``` template< class BidirIt, class Traits, class Alloc > bool operator==( const std::basic_string< typename std::iterator_traits<BidirIt>::value_type, Traits,Alloc>& st, const std::sub_match<BidirIt>& sm ); ``` | (15) | (since C++11) (until C++20) | | ``` template< class BidirIt, class Traits, class Alloc > bool operator!=( const std::basic_string< typename std::iterator_traits<BidirIt>::value_type, Traits,Alloc>& st, const std::sub_match<BidirIt>& sm ); ``` | (16) | (since C++11) (until C++20) | | ``` template< class BidirIt, class Traits, class Alloc > bool operator<( const std::basic_string< typename std::iterator_traits<BidirIt>::value_type, Traits,Alloc>& st, const std::sub_match<BidirIt>& sm ); ``` | (17) | (since C++11) (until C++20) | | ``` template< class BidirIt, class Traits, class Alloc > bool operator<=( const std::basic_string< typename std::iterator_traits<BidirIt>::value_type, Traits,Alloc>& st, const std::sub_match<BidirIt>& sm ); ``` | (18) | (since C++11) (until C++20) | | ``` template< class BidirIt, class Traits, class Alloc > bool operator>( const std::basic_string< typename std::iterator_traits<BidirIt>::value_type, Traits,Alloc>& st, const std::sub_match<BidirIt>& sm ); ``` | (19) | (since C++11) (until C++20) | | ``` template< class BidirIt, class Traits, class Alloc > bool operator>=( const std::basic_string< typename std::iterator_traits<BidirIt>::value_type, Traits,Alloc>& st, const std::sub_match<BidirIt>& sm ); ``` | (20) | (since C++11) (until C++20) | | `std::sub_match` and `std::iterator_traits<BidirIt>::value_type*` | | | | ``` template< class BidirIt > bool operator==( const std::sub_match<BidirIt>& sm, const typename std::iterator_traits<BidirIt>::value_type* s ); ``` | (21) | (since C++11) | | ``` template< class BidirIt > bool operator!=( const std::sub_match<BidirIt>& sm, const typename std::iterator_traits<BidirIt>::value_type* s ); ``` | (22) | (since C++11) (until C++20) | | ``` template< class BidirIt > bool operator<( const std::sub_match<BidirIt>& sm, const typename std::iterator_traits<BidirIt>::value_type* s ); ``` | (23) | (since C++11) (until C++20) | | ``` template< class BidirIt > bool operator<=( const std::sub_match<BidirIt>& sm, const typename std::iterator_traits<BidirIt>::value_type* s ); ``` | (24) | (since C++11) (until C++20) | | ``` template< class BidirIt > bool operator>( const std::sub_match<BidirIt>& sm, const typename std::iterator_traits<BidirIt>::value_type* s ); ``` | (25) | (since C++11) (until C++20) | | ``` template< class BidirIt > bool operator>=( const std::sub_match<BidirIt>& sm, const typename std::iterator_traits<BidirIt>::value_type* s ); ``` | (26) | (since C++11) (until C++20) | | ``` template< class BidirIt > /*comp-cat*/ operator<=>( const std::sub_match<BidirIt>& sm, const typename std::iterator_traits<BidirIt>::value_type* s ); ``` | (27) | (since C++20) | | `std::iterator_traits<BidirIt>::value_type*` and `std::sub_match` | | | | ``` template< class BidirIt > bool operator==( const typename std::iterator_traits<BidirIt>::value_type* s, const std::sub_match<BidirIt>& sm ); ``` | (28) | (since C++11) (until C++20) | | ``` template< class BidirIt > bool operator!=( const typename std::iterator_traits<BidirIt>::value_type* s, const std::sub_match<BidirIt>& sm ); ``` | (29) | (since C++11) (until C++20) | | ``` template< class BidirIt > bool operator<( const typename std::iterator_traits<BidirIt>::value_type* s, const std::sub_match<BidirIt>& sm ); ``` | (30) | (since C++11) (until C++20) | | ``` template< class BidirIt > bool operator<=( const typename std::iterator_traits<BidirIt>::value_type* s, const std::sub_match<BidirIt>& sm ); ``` | (31) | (since C++11) (until C++20) | | ``` template< class BidirIt > bool operator>( const typename std::iterator_traits<BidirIt>::value_type* s, const std::sub_match<BidirIt>& sm ); ``` | (32) | (since C++11) (until C++20) | | ``` template< class BidirIt > bool operator>=( const typename std::iterator_traits<BidirIt>::value_type* s, const std::sub_match<BidirIt>& sm ); ``` | (33) | (since C++11) (until C++20) | | `std::sub_match` and `std::iterator_traits<BidirIt>::value_type` | | | | ``` template< class BidirIt > bool operator==( const std::sub_match<BidirIt>& sm, const typename std::iterator_traits<BidirIt>::value_type& ch ); ``` | (34) | (since C++11) | | ``` template< class BidirIt > bool operator!=( const std::sub_match<BidirIt>& sm, const typename std::iterator_traits<BidirIt>::value_type& ch ); ``` | (35) | (since C++11) (until C++20) | | ``` template< class BidirIt > bool operator<( const std::sub_match<BidirIt>& sm, const typename std::iterator_traits<BidirIt>::value_type& ch ); ``` | (36) | (since C++11) (until C++20) | | ``` template< class BidirIt > bool operator<=( const std::sub_match<BidirIt>& sm, const typename std::iterator_traits<BidirIt>::value_type& ch ); ``` | (37) | (since C++11) (until C++20) | | ``` template< class BidirIt > bool operator>( const std::sub_match<BidirIt>& sm, const typename std::iterator_traits<BidirIt>::value_type& ch ); ``` | (38) | (since C++11) (until C++20) | | ``` template< class BidirIt > bool operator>=( const std::sub_match<BidirIt>& sm, const typename std::iterator_traits<BidirIt>::value_type& ch ); ``` | (39) | (since C++11) (until C++20) | | ``` template< class BidirIt > /*comp-cat*/ operator<=>( const std::sub_match<BidirIt>& sm, const typename std::iterator_traits<BidirIt>::value_type& ch ); ``` | (40) | (since C++20) | | `std::iterator_traits<BidirIt>::value_type` and `std::sub_match` | | | | ``` template< class BidirIt > bool operator==( const typename std::iterator_traits<BidirIt>::value_type& ch, const std::sub_match<BidirIt>& sm ); ``` | (41) | (since C++11) (until C++20) | | ``` template< class BidirIt > bool operator!=( const typename std::iterator_traits<BidirIt>::value_type& ch, const std::sub_match<BidirIt>& sm ); ``` | (42) | (since C++11) (until C++20) | | ``` template< class BidirIt > bool operator<( const typename std::iterator_traits<BidirIt>::value_type& ch, const std::sub_match<BidirIt>& sm ); ``` | (43) | (since C++11) (until C++20) | | ``` template< class BidirIt > bool operator<=( const typename std::iterator_traits<BidirIt>::value_type& ch, const std::sub_match<BidirIt>& sm ); ``` | (44) | (since C++11) (until C++20) | | ``` template< class BidirIt > bool operator>( const typename std::iterator_traits<BidirIt>::value_type& ch, const std::sub_match<BidirIt>& sm ); ``` | (45) | (since C++11) (until C++20) | | ``` template< class BidirIt > bool operator>=( const typename std::iterator_traits<BidirIt>::value_type& ch, const std::sub_match<BidirIt>& sm ); ``` | (46) | (since C++11) (until C++20) | Compares a `sub_match` to another `sub_match`, a string, a null-terminated character sequence or a character. 1-7) Compares two `sub_match` directly by comparing their underlying character sequences. Implemented as if by `lhs.compare(rhs)` 8-20) Compares a `sub_match` with a `[std::basic\_string](../../string/basic_string "cpp/string/basic string")`. Implemented as if by `sm.compare(typename sub_match<BidirIt>::string_type(st.data(), st.size())`. 21-33) Compares a `sub_match` with a null-terminated string. Implemented as if by `sm.compare(s)`. 34-46) Compares a `sub_match` with a character. Implemented as if by `sm.compare(typename sub_match<BidirIt>::string_type(1, ch))`. | | | | --- | --- | | The return type of three-way comparison operators (`/*comp-cat*/`) is `[std::compare\_three\_way\_result\_t](http://en.cppreference.com/w/cpp/utility/compare/compare_three_way_result)<typename [std::sub\_match](http://en.cppreference.com/w/cpp/regex/sub_match)<BidirIt>::string\_type>>`, i.e. `[std::char\_traits](http://en.cppreference.com/w/cpp/string/char_traits)<typename [std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<BidirIt>::value\_type>::comparison\_category` if that qualified-id is valid and denotes a type, `std::weak_ordering` otherwise. If `/*comp-cat*/` is not a comparison category type, the program is ill-formed. The `<`, `<=`, `>`, `>=`, and `!=` operators are [synthesized](../../language/operators#Relational_operators "cpp/language/operators") from `operator<=>` and `operator==` respectively. | (since C++20) | ### Parameters | | | | | --- | --- | --- | | lhs, rhs, sm | - | a `sub_match` to compare | | st | - | a `basic_string` to compare | | s | - | a pointer to a null-terminated string to compare | | ch | - | a character to compare | ### Return value For `operator==`, (since C++20)`true` if the corresponding comparison holds as defined by `[std::sub\_match::compare()](compare "cpp/regex/sub match/compare")`, `false` otherwise. | | | | --- | --- | | For `operator<=>`, `static_cast</*comp-cat*/>(/*comp-res*/ <=> 0)`, where `/*comp-res*/` is the result of `[std::sub\_match::compare()](compare "cpp/regex/sub match/compare")` described above. | (since C++20) | ### Notes | | | | --- | --- | | If value type of `BidirIt` is `char`, `wchar_t`, `char8_t`, `char16_t`, or `char32_t`, the return type of `operator<=>` is `std::strong_ordering`. | (since C++20) | ### Example ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 3432](https://cplusplus.github.io/LWG/issue3432) | C++20 | the return type of `operator<=>` was not required to be a comparison category type | required | ### See also | | | | --- | --- | | [compare](compare "cpp/regex/sub match/compare") | compares matched subsequence (if any) (public member function) |
programming_docs
cpp std::regex_iterator<BidirIt,CharT,Traits>::operator= std::regex\_iterator<BidirIt,CharT,Traits>::operator= ===================================================== | | | | | --- | --- | --- | | ``` regex_iterator& operator=( const regex_iterator& other ); ``` | | (since C++11) | Assigns the contents of `other`. ### Parameters | | | | | --- | --- | --- | | other | - | regex iterator to assign | ### Return value `*this`. cpp std::regex_iterator<BidirIt,CharT,Traits>::operator++, operator++(int) std::regex\_iterator<BidirIt,CharT,Traits>::operator++, operator++(int) ======================================================================= | | | | | --- | --- | --- | | ``` regex_iterator& operator++(); ``` | | (since C++11) | | ``` regex_iterator operator++(int); ``` | | (since C++11) | Advances the iterator on the next match. At first, a local variable of type `BidirIt` is constructed with the value of `match[0].second`. If the iterator holds a zero-length match and `start == end`, `*this` is set to end-of-sequence iterator and the function returns. Otherwise, if the iterator holds a zero-length match the operator invokes the following: `regex_search(start, end, match, *pregex, flags | regex_constants::match_not_null | regex_constants::match_continuous);` If the call returns `true`, the function returns. Otherwise the operator increments `start` and continues as if the most recent match was not a zero-length match. If the most recent match was not a zero-length match, the operator sets `flags` to `flags | regex_constants::match_prev_avail` and invokes the following: `regex_search(start, end, match, *pregex, flags);` If the call returns `false`, the iterator sets `*this` to the end-of-sequence iterator, the function returns. In all cases in which the call to `regex_search` returns `true`, `match.prefix().first` will be equal to the previous value of `match[0].second` and for each index *i* in the range *[0,* `match.size()`*)* for which `match[i].matched` is `true`, `match[i].position()` will return `distance(begin, match[i].first)`. This means that `match[i].position()` gives the offset from the beginning of the target sequence, which is often not the same as the offset from the sequence passed in the call to `regex_search`. It is unspecified how the implementation makes these adjustments. This means that a compiler may call an implementation-specific search function, in which case a user-defined specialization of `regex_search` will not be called. The behavior is undefined if the iterator is end-of-sequence iterator. ### Parameters (none). ### Return value 1) `*this` 2) The previous value of the iterator. cpp std::regex_iterator<BidirIt,CharT,Traits>::operator==,operator!= std::regex\_iterator<BidirIt,CharT,Traits>::operator==,operator!= ================================================================= | | | | | --- | --- | --- | | ``` bool operator==(const regex_iterator& rhs) const; ``` | (1) | (since C++11) | | ``` bool operator!=(const regex_iterator& rhs) const; ``` | (2) | (since C++11) (until C++20) | Compares two `regex_iterator`s. | | | | --- | --- | | The `!=` operator is [synthesized](../../language/operators#Relational_operators "cpp/language/operators") from `operator==`. | (since C++20) | ### Parameters | | | | | --- | --- | --- | | rhs | - | a `regex_iterator` to compare to | ### Return value For the sake of exposition, assume that `regex_iterator` contains the following members: * `BidirIt begin`; * `BidirIt end`; * `const regex_type *pregex;` * `[std::regex\_constants::match\_flag\_type](http://en.cppreference.com/w/cpp/regex/match_flag_type) flags;` * `[std::match\_results](http://en.cppreference.com/w/cpp/regex/match_results)<BidirIt> match;` 1) Returns `true` if `*this` and `rhs` are both end-of-sequence iterators, or if all of the following conditions are true: * `begin == rhs.begin` * `end == rhs.end` * `pregex == rhs.pregex` * `flags == rhs.flags` * `match[0] == rhs.match[0]` 2) Returns `!(*this == rhs)` ### Example cpp std::regex_iterator<BidirIt,CharT,Traits>::regex_iterator std::regex\_iterator<BidirIt,CharT,Traits>::regex\_iterator =========================================================== | | | | | --- | --- | --- | | ``` regex_iterator(); ``` | (1) | (since C++11) | | ``` regex_iterator( BidirIt a, BidirIt b, const regex_type& re, std::regex_constants::match_flag_type m = std::regex_constants::match_default ); ``` | (2) | (since C++11) | | ``` regex_iterator( const regex_iterator& ); ``` | (3) | (since C++11) | | ``` regex_iterator( BidirIt, BidirIt, const regex_type&&, std::regex_constants::match_flag_type = std::regex_constants::match_default ) = delete; ``` | (4) | (since C++11) | Constructs a new `regex_iterator`: 1) Default constructor. Constructs an end-of-sequence iterator. 2) Constructs a `regex_iterator` from the sequence of characters `[a, b)`, the regular expression `re`, and a flag `m` that governs matching behavior. This constructor performs an initial call to `[std::regex\_search](../regex_search "cpp/regex/regex search")` with this data. If the result of this initial call is `false`, `*this` is set to an end-of-sequence iterator. 3) Copies a `regex_iterator`. 4) The overload (2) is not allowed to be called with a temporary regex, since the returned iterator would be immediately invalidated. ### Parameters | | | | | --- | --- | --- | | a | - | [LegacyBidirectionalIterator](../../named_req/bidirectionaliterator "cpp/named req/BidirectionalIterator") to the beginning of the target character sequence | | b | - | [LegacyBidirectionalIterator](../../named_req/bidirectionaliterator "cpp/named req/BidirectionalIterator") to the end of the target character sequence | | re | - | regular expression used to search the target character sequence | | m | - | flags that govern the behavior of `re` | ### Example ``` #include <iostream> #include <regex> #include <string_view> int main() { constexpr std::string_view str{"#ONE:*p=&Mass; #Two:MOV %rd,42"}; const std::regex re("[a-w]"); // create regex_iterator, overload (2) auto it = std::regex_iterator<std::string_view::iterator>{ str.cbegin(), str.cend(), re // re is lvalue; if an immediate expression was used // instead, e.g. std::regex{"[a-z]"}, this would // produce an error - overload (4) is deleted }; for (decltype(it) last /* overload (1) */; it != last; ++it) std::cout << (*it).str(); } ``` Output: ``` password ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 2332](https://cplusplus.github.io/LWG/issue2332) | C++11 | a `regex_iterator` constructed from a temporary`basic_regex` became invalid immediately | such construction is disallowed via a deleted overload | cpp std::regex_token_iterator<BidirIt,CharT,Traits>::regex_token_iterator std::regex\_token\_iterator<BidirIt,CharT,Traits>::regex\_token\_iterator ========================================================================= | | | | | --- | --- | --- | | ``` regex_token_iterator(); ``` | (1) | (since C++11) | | ``` regex_token_iterator( BidirIt a, BidirIt b, const regex_type& re, int submatch = 0, std::regex_constants::match_flag_type m = std::regex_constants::match_default ); ``` | (2) | (since C++11) | | ``` regex_token_iterator( BidirIt a, BidirIt b, const regex_type& re, const std::vector<int>& submatches, std::regex_constants::match_flag_type m = std::regex_constants::match_default ); ``` | (3) | (since C++11) | | ``` regex_token_iterator( BidirIt a, BidirIt b, const regex_type& re, std::initializer_list<int> submatches, std::regex_constants::match_flag_type m = std::regex_constants::match_default ); ``` | (4) | (since C++11) | | ``` template <std::size_t N> regex_token_iterator( BidirIt a, BidirIt b, const regex_type& re, const int (&submatches)[N], std::regex_constants::match_flag_type m = std::regex_constants::match_default ); ``` | (5) | (since C++11) | | ``` regex_token_iterator( const regex_token_iterator& other ); ``` | (6) | (since C++11) | | ``` regex_token_iterator( BidirIt a, BidirIt b, const regex_type&& re, int submatch = 0, std::regex_constants::match_flag_type m = std::regex_constants::match_default ) = delete; ``` | (7) | (since C++11) | | ``` regex_token_iterator( BidirIt a, BidirIt b, const regex_type&& re, const std::vector<int>& submatches, std::regex_constants::match_flag_type m = std::regex_constants::match_default ) = delete; ``` | (8) | (since C++11) | | ``` regex_token_iterator( BidirIt a, BidirIt b, const regex_type&& re, std::initializer_list<int> submatches, std::regex_constants::match_flag_type m = std::regex_constants::match_default ) = delete; ``` | (9) | (since C++11) | | ``` template <std::size_t N> regex_token_iterator( BidirIt a, BidirIt b, const regex_type&& re, const int (&submatches)[N], std::regex_constants::match_flag_type m = std::regex_constants::match_default ) = delete; ``` | (10) | (since C++11) | Constructs a new `regex_token_iterator`: 1) Default constructor. Constructs the end-of-sequence iterator. 2-5) First, copies the list of the requested submatch out of the `submatches` or `submatch` argument into the member list stored in the iterator and constructs the member `[std::regex\_iterator](../regex_iterator "cpp/regex/regex iterator")` by passing `a`, `b`, `re`, and `m` to its four-argument constructor (that constructor performs the initial call to `[std::regex\_search](../regex_search "cpp/regex/regex search")`) and sets the internal counter of submatches to zero. * If, after construction, the member `regex_iterator` is not an end-of-sequence iterator, sets the member pointer to the address of the current `[std::sub\_match](../sub_match "cpp/regex/sub match")`. * Otherwise (if the member `regex_iterator` is an end-of-sequence iterator), but the value `-1` is one of the values in `submatches`/`submatch`, turns `*this` into a *suffix iterator* pointing at the range `[a,b)` (the entire string is the non-matched suffix) * Otherwise (if -1 is not in the list of submatches), turns `*this` into the end-of-sequence iterator. The behavior is undefined if any value in `submatches` is less than `-1`. 6) Copy constructor: performs member-wise copy (including making a copy of the member `regex_iterator` and the member pointer to current `sub_match`). 7-10) The overloads (2-5) are prohibited from being called with a temporary regex since otherwise the returned iterator would be immediately invalidated ### Parameters | | | | | --- | --- | --- | | a | - | [LegacyBidirectionalIterator](../../named_req/bidirectionaliterator "cpp/named req/BidirectionalIterator") to the beginning of the target character sequence | | b | - | [LegacyBidirectionalIterator](../../named_req/bidirectionaliterator "cpp/named req/BidirectionalIterator") to the end of the target character sequence | | re | - | regular expression used to search the target character sequence | | submatch | - | the index of the submatch that should be returned. "0" represents the entire match, and "-1" represents the parts that are not matched (e.g, the stuff between matches). | | submatches | - | the sequence of submatch indices that should be iterated over within each match, may include the special value -1 for the non-matched fragments | | m | - | flags that govern the behavior of `re` | ### Example ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 2332](https://cplusplus.github.io/LWG/issue2332) | C++11 | a `regex_token_iterator` constructed from atemporary `basic_regex` became invalid immediately | such construction is disallowed via deleted overloads | cpp std::regex_token_iterator<BidirIt,CharT,Traits>::operator*, operator-> std::regex\_token\_iterator<BidirIt,CharT,Traits>::operator\*, operator-> ========================================================================= | | | | | --- | --- | --- | | ``` const value_type& operator*() const; ``` | (1) | (since C++11) | | ``` const value_type* operator->() const; ``` | (2) | (since C++11) | Returns a pointer or reference to the current match. ### Return value 1) Returns a reference to the current match. 2) Returns a pointer to the current match. The behavior is undefined if the iterator is end-of-sequence iterator. cpp std::regex_token_iterator<BidirIt,CharT,Traits>::operator= std::regex\_token\_iterator<BidirIt,CharT,Traits>::operator= ============================================================ | | | | | --- | --- | --- | | ``` regex_token_iterator& operator=( const regex_token_iterator& other ); ``` | | (since C++11) | Assigns the contents of `other`. ### Parameters | | | | | --- | --- | --- | | other | - | regex token iterator to assign. | ### Return value `*this`. cpp std::regex_token_iterator<BidirIt,CharT,Traits>::operator++, operator++(int) std::regex\_token\_iterator<BidirIt,CharT,Traits>::operator++, operator++(int) ============================================================================== | | | | | --- | --- | --- | | ``` regex_token_iterator& operator++(); ``` | | (since C++11) | | ``` regex_token_iterator operator++(int); ``` | | (since C++11) | Advances the iterator on the next sub match. If `*this` is a suffix iterator, sets `*this` to an end-of-sequence iterator. Otherwise, if `N + 1 < subs.size()`, increments N and sets result to the address of the current match. Otherwise, sets `N` to `​0​` and increments `position`. If `position` is not an end-of-sequence iterator the operator sets result to the address of the current match. Otherwise, if any of the values stored in subs is equal to `-1` and `prev->suffix().length()` is not `​0​` the operator sets `*this` to a suffix iterator that points to the range [`prev->suffix().first`, `prev->suffix().second`). Otherwise, sets `*this` to an end-of-sequence iterator. The behavior is undefined if the iterator is end-of-sequence iterator. ### Parameters (none). ### Return value 1) `*this` 2) The previous value of the iterator. cpp std::regex_token_iterator<BidirIt,CharT,Traits>::operator==, operator!= std::regex\_token\_iterator<BidirIt,CharT,Traits>::operator==, operator!= ========================================================================= | | | | | --- | --- | --- | | ``` bool operator==( const regex_token_iterator& other ) const; ``` | (1) | (since C++11) | | ``` bool operator!=( const regex_token_iterator& other ) const; ``` | (2) | (since C++11) (until C++20) | Checks whether `*this` and `other` are equivalent. Two regex token iterators are equal if: a) They are both end-of-sequence iterators b) They are both suffix iterators and the suffixes are equal. c) Neither of them is end-of-sequence or suffix iterator and: * `position == other.position` * `N == other.N` * `subs == other.subs` 1) Checks whether `*this` is *equal to* `other`. 2) Checks whether `*this` is *not equal to* `other`. | | | | --- | --- | | The `!=` operator is [synthesized](../../language/operators#Relational_operators "cpp/language/operators") from `operator==`. | (since C++20) | ### Parameters | | | | | --- | --- | --- | | other | - | another regex token iterator to compare to | ### Return value 1) `true` if `*this` is *equal to* `other`, `false` otherwise. 2) `true` if `*this` is *not equal to* `other`, `false` otherwise. cpp std::basic_regex<CharT,Traits>::flags std::basic\_regex<CharT,Traits>::flags ====================================== | | | | | --- | --- | --- | | ``` flag_type flags() const; ``` | | (since C++11) | Returns the regular expression syntax flags as set in the constructor or the last call to `[assign()](assign "cpp/regex/basic regex/assign")`. ### Parameters (none). ### Return value Current regular expression syntax flags. ### Exceptions May throw implementation-defined exceptions. ### Example cpp deduction guides for std::basic_regex deduction guides for `std::basic_regex` ======================================= | Defined in header `[<regex>](../../header/regex "cpp/header/regex")` | | | | --- | --- | --- | | ``` template<class ForwardIt> basic_regex(ForwardIt, ForwardIt, std::regex_constants::syntax_option_type = std::regex_constants::ECMAScript) -> basic_regex<typename std::iterator_traits<ForwardIt>::value_type>; ``` | | (since C++17) | This [deduction guide](../../language/class_template_argument_deduction "cpp/language/class template argument deduction") is provided for `[std::basic\_regex](../basic_regex "cpp/regex/basic regex")` to allow deduction from an iterator range. ### Example ``` #include <regex> #include <vector> int main() { std::vector<char> v = {'a', 'b', 'c'}; std::basic_regex re(v.begin(), v.end()); // uses explicit deduction guide } ``` cpp std::basic_regex<CharT,Traits>::basic_regex std::basic\_regex<CharT,Traits>::basic\_regex ============================================= | | | | | --- | --- | --- | | ``` basic_regex(); ``` | (1) | (since C++11) | | ``` explicit basic_regex( const CharT* s, flag_type f = std::regex_constants::ECMAScript ); ``` | (2) | (since C++11) | | ``` basic_regex( const CharT* s, std::size_t count, flag_type f = std::regex_constants::ECMAScript ); ``` | (3) | (since C++11) | | ``` basic_regex( const basic_regex& other ); ``` | (4) | (since C++11) | | ``` basic_regex( basic_regex&& other ) noexcept; ``` | (5) | (since C++11) | | ``` template< class ST, class SA > explicit basic_regex( const std::basic_string<CharT,ST,SA>& str, flag_type f = std::regex_constants::ECMAScript ); ``` | (6) | (since C++11) | | ``` template< class ForwardIt > basic_regex( ForwardIt first, ForwardIt last, flag_type f = std::regex_constants::ECMAScript ); ``` | (7) | (since C++11) | | ``` basic_regex( std::initializer_list<CharT> init, flag_type f = std::regex_constants::ECMAScript ); ``` | (8) | (since C++11) | Constructs a new regular expression from a sequence of characters interpreted according to the flags `f`. 1) Default constructor. Constructs an empty regular expression which will match nothing. 2) Constructs a regex from a null-terminated string `s`. 3) Constructs a regex from a sequence of `count` characters, pointed to by `s`. 4) Copy constructor. Constructs a regex by copying `other`. 5) Move constructor. Constructs a regex with the contents of `other` using move semantics. 6) Constructs a regex from a string `str`. 7) Range constructor. Constructs the string with the contents of the range `[first, last)`. 8) Initializer list constructor. Constructs the string with the contents of the initializer list `init`. ### Parameters | | | | | --- | --- | --- | | s | - | pointer to a null-terminated string | | count | - | length of a character sequence used to initialize the regex | | first, last | - | range of a character sequence used to initialize the regex | | str | - | a basic\_string used as a source used to initialize the regex | | other | - | another regex to use as source to initialize the regex | | init | - | initializer list used to initialize the regex | | f | - | flags used to guide the interpretation of the character sequence as a regular expression | | Type requirements | | -`ForwardIt` must meet the requirements of [LegacyForwardIterator](../../named_req/forwarditerator "cpp/named req/ForwardIterator"). | ### Exceptions 1) May throw implementation-defined exceptions. 2-3) `[std::regex\_error](../regex_error "cpp/regex/regex error")` if the supplied regular expression is not valid. 5) May throw implementation-defined exceptions. 6-8) `[std::regex\_error](../regex_error "cpp/regex/regex error")` if the supplied regular expression is not valid. ### Example
programming_docs
cpp std::basic_regex<CharT,Traits>::imbue std::basic\_regex<CharT,Traits>::imbue ====================================== | | | | | --- | --- | --- | | ``` locale_type imbue( locale_type loc ); ``` | | (since C++11) | Replaces the current locale with `loc`. The regular expression does not match any character sequence after the call. Effectively calls `traits_i.imbue(loc)` where `traits_i` is a default initialized instance of the type `Traits` stored within the regular expression object. ### Parameters | | | | | --- | --- | --- | | loc | - | new locale to use | ### Return value The locale before the call to this function. Effectively returns the result of expression `traits_i.imbue(loc)`. ### Exceptions May throw implementation-defined exceptions. ### Example ### See also | | | | --- | --- | | [getloc](getloc "cpp/regex/basic regex/getloc") | get locale information (public member function) | cpp std::basic_regex<CharT,Traits>::mark_count std::basic\_regex<CharT,Traits>::mark\_count ============================================ | | | | | --- | --- | --- | | ``` unsigned mark_count() const; ``` | | (since C++11) | Returns the number of marked sub-expressions (also known as capture groups) within the regular expression. ### Parameters (none). ### Return value The number of marked sub-expressions within the regular expression. ### Exceptions May throw implementation-defined exceptions. ### Example ``` #include <iostream> #include <regex> int main() { std::regex r1{"abcde"}; std::cout << "r1 has " << r1.mark_count() << " subexpressions" << '\n'; // Expected: 0 std::regex r2{"ab(c)de"}; std::cout << "r2 has " << r2.mark_count() << " subexpressions" << '\n'; // Expected: 1 std::regex r3{"a(bc)d(e)"}; std::cout << "r3 has " << r3.mark_count() << " subexpressions" << '\n'; // Expected: 2 // nested sub-expressions std::regex r4{"abc(de(fg))"}; std::cout << "r4 has " << r4.mark_count() << " subexpressions" << '\n'; // Expected: 2 // escaped parentheses std::regex r5{"a(bc\\(\\)de)"}; std::cout << "r5 has " << r5.mark_count() << " subexpressions" << '\n'; // Expected: 1 // using nosubs flag std::regex r6 {"ab(c)de", std::regex_constants::nosubs}; std::cout << "r6 has " << r6.mark_count() << " subexpressions" << '\n'; // Expected: 0 } ``` Output: ``` r1 has 0 subexpressions r2 has 1 subexpressions r3 has 2 subexpressions r4 has 2 subexpressions r5 has 1 subexpressions r6 has 0 subexpressions ``` cpp std::basic_regex<CharT,Traits>::swap std::basic\_regex<CharT,Traits>::swap ===================================== | | | | | --- | --- | --- | | ``` void swap( basic_regex& other ) noexcept; ``` | | (since C++11) | Exchanges the contents of two regular expressions. ### Parameters | | | | | --- | --- | --- | | other | - | the regular expression to swap with | ### Return value (none). ### Example ### See also | | | | --- | --- | | [std::swap(std::basic\_regex)](swap2 "cpp/regex/basic regex/swap2") (C++11) | specializes the `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | cpp std::basic_regex<CharT,Traits>::getloc std::basic\_regex<CharT,Traits>::getloc ======================================= | | | | | --- | --- | --- | | ``` locale_type getloc() const; ``` | | (since C++11) | Returns the current locale associated with the regular expression. Effectively calls `traits_i.getloc()` where `traits_i` is a default initialized instance of the type `Traits`, stored within the regular expression object. ### Parameters (none). ### Return value The current locale associated with the regular expression. ### Exceptions May throw implementation-defined exceptions. ### Example ### See also | | | | --- | --- | | [imbue](imbue "cpp/regex/basic regex/imbue") | set locale information (public member function) | cpp std::basic_regex<CharT,Traits>::assign std::basic\_regex<CharT,Traits>::assign ======================================= | | | | | --- | --- | --- | | ``` basic_regex& assign( const basic_regex& other ); ``` | (1) | (since C++11) | | ``` basic_regex& assign( basic_regex&& other ) noexcept; ``` | (2) | (since C++11) | | ``` basic_regex& assign( const CharT* s, flag_type f = std::regex_constants::ECMAScript ); ``` | (3) | (since C++11) | | ``` basic_regex& assign( const CharT* ptr, size_t count, flag_type f = std::regex_constants::ECMAScript ); ``` | (4) | (since C++11) | | ``` template< class ST, class SA > basic_regex& assign( const std::basic_string<CharT,ST,SA>& str, flag_type f = std::regex_constants::ECMAScript ); ``` | (5) | (since C++11) | | ``` template< class InputIt > basic_regex& assign( InputIt first, InputIt last, flag_type f = std::regex_constants::ECMAScript ); ``` | (6) | (since C++11) | | ``` basic_regex& assign( std::initializer_list<CharT> ilist, flag_type f = std::regex_constants::ECMAScript ); ``` | (7) | (since C++11) | Assigns the contents to the regular expression. 1) Assigns the contents of `other`. `[flags()](flags "cpp/regex/basic regex/flags")` and `[mark\_count()](mark_count "cpp/regex/basic regex/mark count")` are equivalent to the values of `other.flags()` and `other.mark_count()` after the call. 2) Assigns the contents of `other` using move semantics. `[flags()](flags "cpp/regex/basic regex/flags")` and `[mark\_count()](mark_count "cpp/regex/basic regex/mark count")` are equivalent to the values of `other.flags()` and `other.mark_count()` before the assignment. After the call, `other` is in a valid, but unspecified state. 3-7) Assigns a sequence of characters to the regular expression. The syntax flags are set to `f`. `[mark\_count()](mark_count "cpp/regex/basic regex/mark count")` returns the number of marked subexpressions within the resulting subexpression after the call. 3) Assigns a null-terminated string pointed to by `s`. 4) Assigns a sequence of `count` characters, pointed to by `s`. 5) Assigns the string `str`. 6) Assigns the characters in the range `[first, last)`. 7) Assigns the characters in the initializer list `ilist`. ### Parameters | | | | | --- | --- | --- | | other | - | another regular expression to assign | | s | - | pointer to a character sequence to assign | | str | - | string to assign | | first, last | - | the range of characters to assign | | ilist | - | initializer list containing characters to assign | | Type requirements | | -`InputIt` must meet the requirements of [LegacyInputIterator](../../named_req/inputiterator "cpp/named req/InputIterator"). | ### Return value `*this`. ### Exceptions 1) May throw implementation-defined exceptions. 3-7) `[std::regex\_error](../regex_error "cpp/regex/regex error")` if the supplied regular expression is not valid. The object is not modified in that case. ### Example ### See also | | | | --- | --- | | [operator=](operator= "cpp/regex/basic regex/operator=") | assigns the contents (public member function) | cpp std::swap(std::basic_regex) std::swap(std::basic\_regex) ============================ | | | | | --- | --- | --- | | ``` template< class CharT, class Traits > void swap( basic_regex<CharT,Traits> &lhs, basic_regex<CharT,Traits> &rhs ) noexcept; ``` | | (since C++11) | Overloads the `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` algorithm for `[std::basic\_regex](../basic_regex "cpp/regex/basic regex")`. Exchanges the state of `lhs` with that of `rhs`. Effectively calls `lhs.swap(rhs)`. ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | regular expressions to swap | ### Return value (none). ### Example ### See also | | | | --- | --- | | [swap](swap "cpp/regex/basic regex/swap") | swaps the contents (public member function) | cpp std::basic_regex<CharT,Traits>::operator= std::basic\_regex<CharT,Traits>::operator= ========================================== | Defined in header `[<regex>](../../header/regex "cpp/header/regex")` | | | | --- | --- | --- | | ``` basic_regex& operator=( const basic_regex& other ); ``` | (1) | (since C++11) | | ``` basic_regex& operator=( basic_regex&& other ) noexcept; ``` | (2) | (since C++11) | | ``` basic_regex& operator=( const CharT* ptr ); ``` | (3) | (since C++11) | | ``` basic_regex& operator=( std::initializer_list<CharT> il ); ``` | (4) | (since C++11) | | ``` template< class ST, class SA > basic_regex& operator=( const std::basic_string<CharT,ST,SA>& p ); ``` | (5) | (since C++11) | Assigns the contents. 1) Copy assignment operator. Assigns the contents of `other`. Equivalent to `assign(other);`. 2) Move assignment operator. Assigns the contents of `other` using move semantics. `other` is in valid, but unspecified state after the operation. Equivalent to `assign(other);`. 3) Assigns a null-terminated character string pointed to by `ptr`. Equivalent to `assign(ptr);`. 4) Assigns characters contained in initializer list `il`. Equivalent to `assign(il);`. 5) Assigns the contents of the string `p`. Equivalent to `assign(p);`. ### Parameters | | | | | --- | --- | --- | | other | - | another regex object | | ptr | - | pointer to a null-terminated character string | | il | - | initializer list containing characters to assign | | p | - | string containing characters to assign | ### Return value `*this`. ### Exceptions 1) May throw implementation-defined exceptions. 3-5) `[std::regex\_error](../regex_error "cpp/regex/regex error")` if the supplied regular expression is not valid. The object is not modified in that case. ### See also | | | | --- | --- | | [assign](assign "cpp/regex/basic regex/assign") | assigns the contents (public member function) | cpp std::basic_regex<CharT,Traits>::~basic_regex std::basic\_regex<CharT,Traits>::~basic\_regex ============================================== | | | | | --- | --- | --- | | ``` ~basic_regex(); ``` | | (since C++11) | Destroys the regular expression object. cpp std::basic_regex constants std::basic\_regex constants =========================== | Defined in header `[<regex>](../../header/regex "cpp/header/regex")` | | | | --- | --- | --- | | ``` static constexpr std::regex_constants::syntax_option_type icase = std::regex_constants::icase; static constexpr std::regex_constants::syntax_option_type nosubs = std::regex_constants::nosubs; static constexpr std::regex_constants::syntax_option_type optimize = std::regex_constants::optimize; static constexpr std::regex_constants::syntax_option_type collate = std::regex_constants::collate; static constexpr std::regex_constants::syntax_option_type ECMAScript = std::regex_constants::ECMAScript; static constexpr std::regex_constants::syntax_option_type basic = std::regex_constants::basic; static constexpr std::regex_constants::syntax_option_type extended = std::regex_constants::extended; static constexpr std::regex_constants::syntax_option_type awk = std::regex_constants::awk; static constexpr std::regex_constants::syntax_option_type grep = std::regex_constants::grep; static constexpr std::regex_constants::syntax_option_type egrep = std::regex_constants::egrep; ``` | | | | ``` static constexpr std::regex_constants::syntax_option_type multiline = std::regex_constants::multiline; ``` | | (since C++17) | `[std::basic\_regex](../basic_regex "cpp/regex/basic regex")` defines several constants that govern general regex matching syntax. These constants are duplicated from `std::regex_constants`: | Value | Effect(s) | | --- | --- | | `icase` | Character matching should be performed without regard to case. | | `nosubs` | When performing matches, all marked sub-expressions `(expr)` are treated as non-marking sub-expressions `(?:expr)`. No matches are stored in the supplied `[std::regex\_match](../regex_match "cpp/regex/regex match")` structure and `mark_count()` is zero. | | `optimize` | Instructs the regular expression engine to make matching faster, with the potential cost of making construction slower. For example, this might mean converting a non-deterministic FSA to a deterministic FSA. | | `collate` | Character ranges of the form *"[a-b]"* will be locale sensitive. | | `multiline` (C++17) | Specifies that `^` shall match the beginning of a line and `$` shall match the end of a line, if the ECMAScript engine is selected. | | `ECMAScript` | Use the [Modified ECMAScript regular expression grammar](../ecmascript "cpp/regex/ecmascript"). | | `basic` | Use the basic POSIX regular expression grammar ([grammar documentation](http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap09.html#tag_09_03)). | | `extended` | Use the extended POSIX regular expression grammar ([grammar documentation](http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap09.html#tag_09_04)). | | `awk` | Use the regular expression grammar used by the *awk* utility in POSIX ([grammar documentation](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/awk.html#tag_20_06_13_04)). | | `grep` | Use the regular expression grammar used by the *grep* utility in POSIX. This is effectively the same as the `basic` option with the addition of newline `'\n'` as an alternation separator. | | `egrep` | Use the regular expression grammar used by the *grep* utility, with the *-E* option, in POSIX. This is effectively the same as the `extended` option with the addition of newline `'\n'` as an alternation separator in addition to `'|'`. | At most one grammar option must be chosen out of `ECMAScript`, `basic`, `extended`, `awk`, `grep`, `egrep`. If no grammar is chosen, `ECMAScript` is assumed to be selected. The other options serve as modifiers, such that `[std::regex](http://en.cppreference.com/w/cpp/regex/basic_regex)("meow", std::regex::icase)` is equivalent to `[std::regex](http://en.cppreference.com/w/cpp/regex/basic_regex)("meow", std::regex::ECMAScript|std::regex::icase)`. ### See also | | | | --- | --- | | [syntax\_option\_type](../syntax_option_type "cpp/regex/syntax option type") (C++11) | general options controlling regex behavior (typedef) | cpp std::atomic_exchange, std::atomic_exchange_explicit std::atomic\_exchange, std::atomic\_exchange\_explicit ====================================================== | Defined in header `[<atomic>](../header/atomic "cpp/header/atomic")` | | | | --- | --- | --- | | | (1) | (since C++11) | | ``` template< class T > T atomic_exchange( std::atomic<T>* obj, typename std::atomic<T>::value_type desr ) noexcept; ``` | | | ``` template< class T > T atomic_exchange( volatile std::atomic<T>* obj, typename std::atomic<T>::value_type desr ) noexcept; ``` | | | | (2) | (since C++11) | | ``` template< class T > T atomic_exchange_explicit( std::atomic<T>* obj, typename std::atomic<T>::value_type desr, std::memory_order order ) noexcept; ``` | | | ``` template< class T > T atomic_exchange_explicit( volatile std::atomic<T>* obj, typename std::atomic<T>::value_type desr, std::memory_order order ) noexcept; ``` | | 1) Atomically replaces the value pointed to by `obj` with the value of `desr` and returns the value `obj` held previously, as if by `obj->exchange(desr)` 2) Atomically replaces the value pointed to by `obj` with the value of `desr` and returns the value `obj` held previously, as if by `obj->exchange(desr, order)` ### Parameters | | | | | --- | --- | --- | | obj | - | pointer to the atomic object to modify | | desr | - | the value to store in the atomic object | | order | - | the memory synchronization ordering for this operation: all values are permitted. | ### Return value The value held previously by the atomic object pointed to by `obj`. ### Example A spinlock mutex can be implemented in userspace using an atomic exchange operation, similar to `[std::atomic\_flag\_test\_and\_set](http://en.cppreference.com/w/cpp/atomic/atomic_flag_test_and_set)`: ``` #include <thread> #include <vector> #include <iostream> #include <atomic> std::atomic<bool> lock(false); // holds true when locked // holds false when unlocked void f(int n) { for (int cnt = 0; cnt < 100; ++cnt) { while(std::atomic_exchange_explicit(&lock, true, std::memory_order_acquire)) ; // spin until acquired std::cout << "Output from thread " << n << '\n'; std::atomic_store_explicit(&lock, false, std::memory_order_release); } } int main() { std::vector<std::thread> v; for (int n = 0; n < 10; ++n) { v.emplace_back(f, n); } for (auto& t : v) { t.join(); } } ``` Output: ``` Output from thread 2 Output from thread 6 Output from thread 7 ...<exactly 1000 lines>... ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [P0558R1](https://wg21.link/P0558R1) | C++11 | exact type match required because `T` is deduced from multiple arguments | `T` is deduced from the `atomic` argument only | ### See also | | | | --- | --- | | [exchange](atomic/exchange "cpp/atomic/atomic/exchange") | atomically replaces the value of the atomic object and obtains the value held previously (public member function of `std::atomic<T>`) | | [atomic\_compare\_exchange\_weakatomic\_compare\_exchange\_weak\_explicitatomic\_compare\_exchange\_strongatomic\_compare\_exchange\_strong\_explicit](atomic_compare_exchange "cpp/atomic/atomic compare exchange") (C++11)(C++11)(C++11)(C++11) | atomically compares the value of the atomic object with non-atomic argument and performs atomic exchange if equal or atomic load if not (function template) | | | | | --- | --- | | [std::atomic\_exchange(std::shared\_ptr) std::atomic\_exchange\_explicit(std::shared\_ptr)](../memory/shared_ptr/atomic "cpp/memory/shared ptr/atomic") (deprecated in C++20) | specializes atomic operations for `[std::shared\_ptr](../memory/shared_ptr "cpp/memory/shared ptr")` (function template) | | [C documentation](https://en.cppreference.com/w/c/atomic/atomic_exchange "c/atomic/atomic exchange") for `atomic_exchange, atomic_exchange_explicit` | cpp std::atomic_store, std::atomic_store_explicit std::atomic\_store, std::atomic\_store\_explicit ================================================ | Defined in header `[<atomic>](../header/atomic "cpp/header/atomic")` | | | | --- | --- | --- | | | (1) | (since C++11) | | ``` template< class T > void atomic_store( std::atomic<T>* obj, typename std::atomic<T>::value_type desr ) noexcept; ``` | | | ``` template< class T > void atomic_store( volatile std::atomic<T>* obj, typename std::atomic<T>::value_type desr ) noexcept; ``` | | | | (2) | (since C++11) | | ``` template< class T > void atomic_store_explicit( std::atomic<T>* obj, typename std::atomic<T>::value_type desr, std::memory_order order) noexcept; ``` | | | ``` template< class T > void atomic_store_explicit( volatile std::atomic<T>* obj, typename std::atomic<T>::value_type desr, std::memory_order order) noexcept; ``` | | 1) Atomically replaces the value pointed to by `obj` with the value of `desr` as if by `obj->store(desr)` 2) Atomically replaces the value pointed to by `obj` with the value of `desr` as if by `obj->store(desr, order)` ### Parameters | | | | | --- | --- | --- | | obj | - | pointer to the atomic object to modify | | desr | - | the value to store in the atomic object | | order | - | the memory synchronization ordering for this operation: only `[std::memory\_order\_relaxed](memory_order "cpp/atomic/memory order")`, `[std::memory\_order\_release](memory_order "cpp/atomic/memory order")` and `[std::memory\_order\_seq\_cst](memory_order "cpp/atomic/memory order")` are permitted. | ### Return value none. ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [P0558R1](https://wg21.link/P0558R1) | C++11 | exact type match required because `T` is deduced from multiple arguments | `T` is deduced from the `atomic` argument only | ### See also | | | | --- | --- | | [store](atomic/store "cpp/atomic/atomic/store") | atomically replaces the value of the atomic object with a non-atomic argument (public member function of `std::atomic<T>`) | | [atomic\_loadatomic\_load\_explicit](atomic_load "cpp/atomic/atomic load") (C++11)(C++11) | atomically obtains the value stored in an atomic object (function template) | | [memory\_order](memory_order "cpp/atomic/memory order") (C++11) | defines memory ordering constraints for the given atomic operation (enum) | | | | | --- | --- | | [std::atomic\_store(std::shared\_ptr) std::atomic\_store\_explicit(std::shared\_ptr)](../memory/shared_ptr/atomic "cpp/memory/shared ptr/atomic") (deprecated in C++20) | specializes atomic operations for `[std::shared\_ptr](../memory/shared_ptr "cpp/memory/shared ptr")` (function template) | | [C documentation](https://en.cppreference.com/w/c/atomic/atomic_store "c/atomic/atomic store") for `atomic_store, atomic_store_explicit` |
programming_docs
cpp std::atomic_wait, std::atomic_wait_explicit std::atomic\_wait, std::atomic\_wait\_explicit ============================================== | Defined in header `[<atomic>](../header/atomic "cpp/header/atomic")` | | | | --- | --- | --- | | | (1) | (since C++20) | | ``` template< class T > void atomic_wait( const std::atomic<T>* object, typename std::atomic<T>::value_type old ); ``` | | | ``` template< class T > void atomic_wait( const volatile std::atomic<T>* object, typename std::atomic<T>::value_type old ); ``` | | | | (2) | (since C++20) | | ``` template< class T > void atomic_wait_explicit( const std::atomic<T>* object, typename std::atomic<T>::value_type old, std::memory_order order ); ``` | | | ``` template< class T > void atomic_wait_explicit( const volatile std::atomic<T>* object, typename std::atomic<T>::value_type old, std::memory_order order ); ``` | | Performs atomic waiting operations. Behaves as if it repeatedly performs the following steps: * Compare the [value representation](../language/object "cpp/language/object") of `object->load([std::memory\_order\_seq\_cst](http://en.cppreference.com/w/cpp/atomic/memory_order))` or `object->load(order)` with that of `old`. + If those are bitwise equal, then blocks until `*object` is notified by `std::atomic::notify_one()` or `std::atomic::notify_all()`, or the thread is unblocked spuriously. + Otherwise, returns. These functions are guaranteed to return only if value has changed, even if underlying implementation unblocks spuriously. 1) Equivalent to `object->wait(old, [std::memory\_order\_seq\_cst](http://en.cppreference.com/w/cpp/atomic/memory_order))`. 2) Equivalent to `object->wait(old, order)`. ### Parameters | | | | | --- | --- | --- | | object | - | pointer to the atomic object to check and wait on | | old | - | the value to check the atomic object no longer contains | | order | - | the memory synchronization ordering for this operation: must not be `std::memory_order::release` or `std::memory_order::acq_rel` | ### Return value (none). ### Notes This form of change-detection is often more efficient than simple polling or pure spinlocks. Due to the [ABA problem](https://en.wikipedia.org/wiki/ABA_problem), transient changes from `old` to another value and back to `old` might be missed, and not unblock. The comparison is bitwise (similar to `[std::memcmp](../string/byte/memcmp "cpp/string/byte/memcmp")`); no comparison operator is used. Padding bits that never participate in an object's value representation are ignored. ### Example ### See also | | | | --- | --- | | [notify\_one](atomic/notify_one "cpp/atomic/atomic/notify one") (C++20) | notifies at least one thread waiting on the atomic object (public member function of `std::atomic<T>`) | | [notify\_all](atomic/notify_all "cpp/atomic/atomic/notify all") (C++20) | notifies all threads blocked waiting on the atomic object (public member function of `std::atomic<T>`) | | [atomic\_notify\_one](atomic_notify_one "cpp/atomic/atomic notify one") (C++20) | notifies a thread blocked in atomic\_wait (function template) | | [atomic\_notify\_all](atomic_notify_all "cpp/atomic/atomic notify all") (C++20) | notifies all threads blocked in atomic\_wait (function template) | cpp std::atomic_flag_notify_one std::atomic\_flag\_notify\_one ============================== | Defined in header `[<atomic>](../header/atomic "cpp/header/atomic")` | | | | --- | --- | --- | | | | (since C++20) | | ``` void atomic_flag_notify_one( std::atomic_flag* object ) noexcept; ``` | | | | ``` void atomic_flag_notify_one( volatile std::atomic_flag* object ) noexcept; ``` | | | Performs atomic notifying operations. If there is a thread blocked in an atomic waiting operation (i.e. `[std::atomic\_flag\_wait()](atomic_flag_wait "cpp/atomic/atomic flag wait")`, `[std::atomic\_flag\_wait\_explicit()](atomic_flag_wait "cpp/atomic/atomic flag wait")`, or `std::atomic_flag::wait()`) on `*object`, then unblocks *at least* one such thread; otherwise does nothing. Equivalent to `object->notify_one()`. ### Parameters | | | | | --- | --- | --- | | object | - | pointer to the `atomic_flag` object to notify | ### Return value (none). ### Notes This form of change-detection is often more efficient than simple polling or pure spinlocks. ### Example ### See also | | | | --- | --- | | [notify\_one](atomic_flag/notify_one "cpp/atomic/atomic flag/notify one") (C++20) | notifies at least one thread waiting on the atomic object (public member function of `std::atomic_flag`) | | [notify\_all](atomic_flag/notify_all "cpp/atomic/atomic flag/notify all") (C++20) | notifies all threads blocked waiting on the atomic object (public member function of `std::atomic_flag`) | | [atomic\_flag\_notify\_all](atomic_flag_notify_all "cpp/atomic/atomic flag notify all") (C++20) | notifies all threads blocked in atomic\_flag\_wait (function) | cpp std::atomic_flag_clear, std::atomic_flag_clear_explicit std::atomic\_flag\_clear, std::atomic\_flag\_clear\_explicit ============================================================ | Defined in header `[<atomic>](../header/atomic "cpp/header/atomic")` | | | | --- | --- | --- | | | (1) | (since C++11) | | ``` void atomic_flag_clear( volatile std::atomic_flag* p ) noexcept; ``` | | | ``` void atomic_flag_clear( std::atomic_flag* p ) noexcept; ``` | | | | (2) | (since C++11) | | ``` void atomic_flag_clear_explicit( volatile std::atomic_flag* p, std::memory_order order ) noexcept; ``` | | | ``` void atomic_flag_clear_explicit( std::atomic_flag* p, std::memory_order order ) noexcept; ``` | | Atomically changes the state of a `[std::atomic\_flag](atomic_flag "cpp/atomic/atomic flag")` pointed to by `p` to clear (`false`). ### Parameters | | | | | --- | --- | --- | | p | - | pointer to `[std::atomic\_flag](atomic_flag "cpp/atomic/atomic flag")` to access | | order | - | the memory synchronization ordering for this operation: only `[std::memory\_order\_relaxed](memory_order "cpp/atomic/memory order")`, `[std::memory\_order\_release](memory_order "cpp/atomic/memory order")`, or `[std::memory\_order\_seq\_cst](memory_order "cpp/atomic/memory order")` are permitted. | ### Return value (none). ### Possible implementation | First version | | --- | | ``` void atomic_flag_clear(volatile std::atomic_flag* p) { p->clear(); } ``` | | Second version | | ``` void atomic_flag_clear(std::atomic_flag* p) { p->clear(); } ``` | | Third version | | ``` void atomic_flag_clear_explicit(volatile std::atomic_flag* p, std::memory_order order) { p->clear(order); } ``` | | Fourth version | | ``` void atomic_flag_clear_explicit(std::atomic_flag* p, std::memory_order order) { p->clear(order); } ``` | ### See also | | | | --- | --- | | [atomic\_flag](atomic_flag "cpp/atomic/atomic flag") (C++11) | the lock-free boolean atomic type (class) | | [atomic\_flag\_test\_and\_setatomic\_flag\_test\_and\_set\_explicit](atomic_flag_test_and_set "cpp/atomic/atomic flag test and set") (C++11)(C++11) | atomically sets the flag to `true` and returns its previous value (function) | | [memory\_order](memory_order "cpp/atomic/memory order") (C++11) | defines memory ordering constraints for the given atomic operation (enum) | | [C documentation](https://en.cppreference.com/w/c/atomic/atomic_flag_clear "c/atomic/atomic flag clear") for `atomic_flag_clear, atomic_flag_clear_explicit` | cpp ATOMIC_FLAG_INIT ATOMIC\_FLAG\_INIT ================== | Defined in header `[<atomic>](../header/atomic "cpp/header/atomic")` | | | | --- | --- | --- | | ``` #define ATOMIC_FLAG_INIT /* implementation-defined */ ``` | | (since C++11) | Defines the initializer which can be used to initialize `[std::atomic\_flag](atomic_flag "cpp/atomic/atomic flag")` to clear (false) state with the statement `[std::atomic\_flag](http://en.cppreference.com/w/cpp/atomic/atomic_flag) v = ATOMIC_FLAG_INIT;`. It is unspecified if it can be used with other initialization contexts. If the flag has static [storage duration](../language/storage_duration#Storage_duration "cpp/language/storage duration"), this [initialization is static](../language/initialization#Static_initialization "cpp/language/initialization"). | | | | --- | --- | | This is the only way to initialize `[std::atomic\_flag](atomic_flag "cpp/atomic/atomic flag")` to a definite value: the value held after any other initialization is unspecified. | (until C++20) | | This macro is no longer needed since default constructor of `[std::atomic\_flag](atomic_flag "cpp/atomic/atomic flag")` initializes it to clear state. It is kept for the compatibility with C. | (since C++20) | ### Example ``` #include <atomic> std::atomic_flag static_flag = ATOMIC_FLAG_INIT; // static initialization, // guaranteed to be available during dynamic initialization of static objects. int main() { std::atomic_flag automatic_flag = ATOMIC_FLAG_INIT; // guaranteed to work // std::atomic_flag another_flag(ATOMIC_FLAG_INIT); // unspecified } ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 3659](https://cplusplus.github.io/LWG/issue3659) | C++20 | `ATOMIC_FLAG_INIT` was deprecated, but needed in C on some platforms | it is undeprecated | ### See also | | | | --- | --- | | [atomic\_flag](atomic_flag "cpp/atomic/atomic flag") (C++11) | the lock-free boolean atomic type (class) | | [C documentation](https://en.cppreference.com/w/c/atomic/ATOMIC_FLAG_INIT "c/atomic/ATOMIC FLAG INIT") for `ATOMIC_FLAG_INIT` | cpp std::atomic_fetch_sub, std::atomic_fetch_sub_explicit std::atomic\_fetch\_sub, std::atomic\_fetch\_sub\_explicit ========================================================== | Defined in header `[<atomic>](../header/atomic "cpp/header/atomic")` | | | | --- | --- | --- | | | (1) | | | ``` template< class T > T atomic_fetch_sub( std::atomic<T>* obj, typename std::atomic<T>::difference_type arg ) noexcept; ``` | | | ``` template< class T > T atomic_fetch_sub( volatile std::atomic<T>* obj, typename std::atomic<T>::difference_type arg ) noexcept; ``` | | | | (2) | | | ``` template< class T > T atomic_fetch_sub_explicit( std::atomic<T>* obj, typename std::atomic<T>::difference_type arg, std::memory_order order ) noexcept; ``` | | | ``` template< class T > T atomic_fetch_sub_explicit( volatile std::atomic<T>* obj, typename std::atomic<T>::difference_type arg, std::memory_order order ) noexcept; ``` | | Performs atomic subtraction. Atomically subtracts `arg` from the value pointed to by `obj` and returns the value `obj` held previously. The operation is performed as if the following was executed: 1) `obj->fetch_sub(arg)` 2) `obj->fetch_sub(arg, order)` ### Parameters | | | | | --- | --- | --- | | obj | - | pointer to the atomic object to modify | | arg | - | the value to subtract from the value stored in the atomic object | | order | - | the memory sycnhronization ordering for this operation: all values are permitted. | ### Return value The value immediately preceding the effects of this function in the [modification order](memory_order#Modification_order "cpp/atomic/memory order") of `*obj`. ### Possible implementation | | | --- | | ``` template< class T > T atomic_fetch_sub( std::atomic<T>* obj, typename std::atomic<T>::difference_type arg ) noexcept { return obj->fetch_sub(arg); } ``` | ### Example Multiple threads may use `fetch_sub` to concurrently process an indexed container. ``` #include <string> #include <thread> #include <vector> #include <iostream> #include <atomic> #include <numeric> const int N = 50; std::atomic<int> cnt; std::vector<int> data(N); void reader(int id) { for (;;) { int idx = atomic_fetch_sub_explicit(&cnt, 1, std::memory_order_relaxed); if (idx >= 0) { std::cout << "reader " << std::to_string(id) << " processed item " << std::to_string(data[idx]) << '\n'; } else { std::cout << "reader " << std::to_string(id) << " done\n"; break; } } } int main() { std::iota(data.begin(), data.end(), 1); cnt = data.size() - 1; std::vector<std::thread> v; for (int n = 0; n < 5; ++n) { v.emplace_back(reader, n); } for (auto& t : v) { t.join(); } } ``` Output: ``` reader 2 processed item 50 reader 1 processed item 44 reader 4 processed item 46 <....> reader 0 done reader 4 done reader 3 done ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [P0558R1](https://wg21.link/P0558R1) | C++11 | exact type match required because `T` is deduced from multiple arguments | `T` is deduced from the `atomic` argument only | ### See also | | | | --- | --- | | [fetch\_sub](atomic/fetch_sub "cpp/atomic/atomic/fetch sub") | atomically subtracts the argument from the value stored in the atomic object and obtains the value held previously (public member function of `std::atomic<T>`) | | [atomic\_fetch\_addatomic\_fetch\_add\_explicit](atomic_fetch_add "cpp/atomic/atomic fetch add") (C++11)(C++11) | adds a non-atomic value to an atomic object and obtains the previous value of the atomic (function template) | | [C documentation](https://en.cppreference.com/w/c/atomic/atomic_fetch_sub "c/atomic/atomic fetch sub") for `atomic_fetch_sub, atomic_fetch_sub_explicit` | cpp std::atomic_fetch_and, std::atomic_fetch_and_explicit std::atomic\_fetch\_and, std::atomic\_fetch\_and\_explicit ========================================================== | Defined in header `[<atomic>](../header/atomic "cpp/header/atomic")` | | | | --- | --- | --- | | | (1) | (since C++11) | | ``` template< class T > T atomic_fetch_and( std::atomic<T>* obj, typename std::atomic<T>::value_type arg ) noexcept; ``` | | | ``` template< class T > T atomic_fetch_and( volatile std::atomic<T>* obj, typename std::atomic<T>::value_type arg ) noexcept; ``` | | | | (2) | (since C++11) | | ``` template< class T > T atomic_fetch_and_explicit( std::atomic<T>* obj, typename std::atomic<T>::value_type arg, std::memory_order order) noexcept; ``` | | | ``` template< class T > T atomic_fetch_and_explicit( volatile std::atomic<T>* obj, typename std::atomic<T>::value_type arg, std::memory_order order) noexcept; ``` | | Atomically replaces the value pointed by `obj` with the result of bitwise AND between the old value of `obj` and `arg`. Returns the value `obj` held previously. The operation is performed as if the following is executed: 1) `obj->fetch_and(arg)` 2) `obj->fetch_and(arg, order)` If `std::atomic<T>` has no `fetch_and` member (this member is only provided for [integral types](atomic#Specializations_for_integral_types "cpp/atomic/atomic")), the program is ill-formed. ### Parameters | | | | | --- | --- | --- | | obj | - | pointer to the atomic object to modify. bool is not an Integral type for the purposes of the atomic operations. | | arg | - | the value to bitwise AND to the value stored in the atomic object | | order | - | the memory synchronization ordering for this operation: all values are permitted. | ### Return value The value immediately preceding the effects of this function in the [modification order](memory_order#Modification_order "cpp/atomic/memory order") of `*obj`. ### Possible implementation | | | --- | | ``` template< class T > T atomic_fetch_and(std::atomic<T>* obj, typename std::atomic<T>::value_type arg ) noexcept { return obj->fetch_and(arg); } ``` | ### Example ``` #include <iostream> #include <atomic> #include <thread> #include <chrono> #include <functional> // Binary semaphore for demonstrative purposes only // This is a simple yet meaningful example: atomic operations // are unnecessary without threads. class Semaphore { std::atomic_char m_signaled; public: Semaphore(bool initial = false) { m_signaled = initial; } // Block until semaphore is signaled void take() { while (!std::atomic_fetch_and(&m_signaled, false)) { std::this_thread::sleep_for(std::chrono::milliseconds(10)); } } void put() { std::atomic_fetch_or(&m_signaled, true); } }; class ThreadedCounter { static const int N = 100; static const int REPORT_INTERVAL = 10; int m_count; bool m_done; Semaphore m_count_sem; Semaphore m_print_sem; void count_up() { for (m_count = 1; m_count <= N; m_count++) { if (m_count % REPORT_INTERVAL == 0) { if (m_count == N) m_done = true; m_print_sem.put(); // signal printing to occur m_count_sem.take(); // wait until printing is complete proceeding } } std::cout << "count_up() done\n"; m_done = true; m_print_sem.put(); } void print_count() { do { m_print_sem.take(); std::cout << m_count << '\n'; m_count_sem.put(); } while (!m_done); std::cout << "print_count() done\n"; } public: ThreadedCounter() : m_done(false) {} void run() { auto print_thread = std::thread(&ThreadedCounter::print_count, this); auto count_thread = std::thread(&ThreadedCounter::count_up, this); print_thread.join(); count_thread.join(); } }; int main() { ThreadedCounter m_counter; m_counter.run(); } ``` Output: ``` 10 20 30 40 50 60 70 80 90 100 print_count() done count_up() done ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [P0558R1](https://wg21.link/P0558R1) | C++11 | exact type match required because `T` is deduced from multiple arguments | `T` is deduced from the `atomic` argument only | ### See also | | | | --- | --- | | [fetch\_and](atomic/fetch_and "cpp/atomic/atomic/fetch and") | atomically performs bitwise AND between the argument and the value of the atomic object and obtains the value held previously (public member function of `std::atomic<T>`) | | [atomic\_fetch\_oratomic\_fetch\_or\_explicit](atomic_fetch_or "cpp/atomic/atomic fetch or") (C++11)(C++11) | replaces the atomic object with the result of bitwise OR with a non-atomic argument and obtains the previous value of the atomic (function template) | | [atomic\_fetch\_xoratomic\_fetch\_xor\_explicit](atomic_fetch_xor "cpp/atomic/atomic fetch xor") (C++11)(C++11) | replaces the atomic object with the result of bitwise XOR with a non-atomic argument and obtains the previous value of the atomic (function template) | | [C documentation](https://en.cppreference.com/w/c/atomic/atomic_fetch_and "c/atomic/atomic fetch and") for `atomic_fetch_and, atomic_fetch_and_explicit` |
programming_docs
cpp std::atomic_notify_all std::atomic\_notify\_all ======================== | Defined in header `[<atomic>](../header/atomic "cpp/header/atomic")` | | | | --- | --- | --- | | | | (since C++20) | | ``` template< class T > void atomic_notify_all( std::atomic<T>* object ); ``` | | | | ``` template< class T > void atomic_notify_all( volatile std::atomic<T>* object ); ``` | | | Performs atomic notifying operations. Unblocks all threads blocked in atomic waiting operations (i.e. `[std::atomic\_wait()](atomic_wait "cpp/atomic/atomic wait")`, `[std::atomic\_wait\_explicit()](atomic_wait "cpp/atomic/atomic wait")`, or `std::atomic::wait()`) on `*object`, if there are any; otherwise does nothing. Equivalent to `object->notify_all()`. ### Parameters | | | | | --- | --- | --- | | object | - | pointer to the atomic object to notify | ### Return value (none). ### Notes This form of change-detection is often more efficient than simple polling or pure spinlocks. ### Example ### See also | | | | --- | --- | | [notify\_one](atomic/notify_one "cpp/atomic/atomic/notify one") (C++20) | notifies at least one thread waiting on the atomic object (public member function of `std::atomic<T>`) | | [notify\_all](atomic/notify_all "cpp/atomic/atomic/notify all") (C++20) | notifies all threads blocked waiting on the atomic object (public member function of `std::atomic<T>`) | | [atomic\_waitatomic\_wait\_explicit](atomic_wait "cpp/atomic/atomic wait") (C++20)(C++20) | blocks the thread until notified and the atomic value changes (function template) | | [atomic\_notify\_one](atomic_notify_one "cpp/atomic/atomic notify one") (C++20) | notifies a thread blocked in atomic\_wait (function template) | cpp std::atomic_is_lock_free, ATOMIC_xxx_LOCK_FREE std::atomic\_is\_lock\_free, ATOMIC\_xxx\_LOCK\_FREE ==================================================== | Defined in header `[<atomic>](../header/atomic "cpp/header/atomic")` | | | | --- | --- | --- | | | (1) | (since C++11) | | ``` template< class T > bool atomic_is_lock_free( const volatile std::atomic<T>* obj ) noexcept; ``` | | | ``` template< class T > bool atomic_is_lock_free( const std::atomic<T>* obj ) noexcept; ``` | | | ``` #define ATOMIC_BOOL_LOCK_FREE /* unspecified */ #define ATOMIC_CHAR_LOCK_FREE /* unspecified */ #define ATOMIC_CHAR16_T_LOCK_FREE /* unspecified */ #define ATOMIC_CHAR32_T_LOCK_FREE /* unspecified */ #define ATOMIC_WCHAR_T_LOCK_FREE /* unspecified */ #define ATOMIC_SHORT_LOCK_FREE /* unspecified */ #define ATOMIC_INT_LOCK_FREE /* unspecified */ #define ATOMIC_LONG_LOCK_FREE /* unspecified */ #define ATOMIC_LLONG_LOCK_FREE /* unspecified */ #define ATOMIC_POINTER_LOCK_FREE /* unspecified */ ``` | (2) | (since C++11) | | ``` #define ATOMIC_CHAR8_T_LOCK_FREE /* unspecified */ ``` | (3) | (since C++20) | 1) Determines if the atomic object pointed to by `obj` is implemented lock-free, as if by calling `obj->is_lock_free()`. In any given program execution, the result of the lock-free query is the same for all atomic objects of the same type. 2,3) Expands to an integer constant expression with value * `​0​` for the built-in atomic types that are never lock-free * `1` for the built-in atomic types that are *sometimes* lock-free * `2` for the built-in atomic types that are always lock-free. ### Parameters | | | | | --- | --- | --- | | obj | - | pointer to the atomic object to examine | ### Return value `true` if `*obj` is a lock-free atomic, `false` otherwise. ### Notes All atomic types except for `[std::atomic\_flag](atomic_flag "cpp/atomic/atomic flag")` may be implemented using mutexes or other locking operations, rather than using the lock-free atomic CPU instructions. Atomic types are also allowed to be *sometimes* lock-free: for example, if only some subarchitectures support lock-free atomic access for a given type (such as the CMPXCHG16B instruction on x86-64), whether atomics are lock-free may not be known until runtime. The C++ standard recommends (but does not require) that lock-free atomic operations are also address-free, that is, suitable for communication between processes using shared memory. ### Example ``` #include <iostream> #include <utility> #include <atomic> struct A { int a[100]; }; struct B { int x, y; }; int main() { std::atomic<A> a; std::atomic<B> b; std::cout << std::boolalpha << "std::atomic<A> is lock free? " << std::atomic_is_lock_free(&a) << '\n' << "std::atomic<B> is lock free? " << std::atomic_is_lock_free(&b) << '\n'; } ``` Possible output: ``` std::atomic<A> is lock free? false std::atomic<B> is lock free? true ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 3249](https://cplusplus.github.io/LWG/issue3249) | C++11 | `atomic_is_lock_free` was specified via pointers, which wasambiguous and might accept invalid pointer values | specified via atomic objects | ### See also | | | | --- | --- | | [is\_lock\_free](atomic/is_lock_free "cpp/atomic/atomic/is lock free") | checks if the atomic object is lock-free (public member function of `std::atomic<T>`) | | [std::atomic\_is\_lock\_free(std::shared\_ptr)](../memory/shared_ptr/atomic "cpp/memory/shared ptr/atomic") | specializes atomic operations for `[std::shared\_ptr](../memory/shared_ptr "cpp/memory/shared ptr")` (function template) | | [atomic\_flag](atomic_flag "cpp/atomic/atomic flag") (C++11) | the lock-free boolean atomic type (class) | | [is\_always\_lock\_free](atomic/is_always_lock_free "cpp/atomic/atomic/is always lock free") [static] (C++17) | indicates that the type is always lock-free (public static member constant of `std::atomic<T>`) | | [C documentation](https://en.cppreference.com/w/c/atomic/atomic_is_lock_free "c/atomic/atomic is lock free") for `atomic_is_lock_free` | | [C documentation](https://en.cppreference.com/w/c/atomic/ATOMIC_LOCK_FREE_consts "c/atomic/ATOMIC LOCK FREE consts") for `ATOMIC_*_LOCK_FREE` | cpp std::kill_dependency std::kill\_dependency ===================== | Defined in header `[<atomic>](../header/atomic "cpp/header/atomic")` | | | | --- | --- | --- | | ``` template< class T > T kill_dependency( T y ) noexcept; ``` | | (since C++11) | Informs the compiler that the dependency tree started by an `[std::memory\_order\_consume](memory_order "cpp/atomic/memory order")` atomic load operation does not extend past the return value of `std::kill_dependency`; that is, the argument does not carry a dependency into the return value. This may be used to avoid unnecessary `[std::memory\_order\_acquire](memory_order "cpp/atomic/memory order")` fences when the dependency chain leaves function scope (and the function does not have the `[[[carries\_dependency](../language/attributes/carries_dependency "cpp/language/attributes/carries dependency")]]` attribute). ### Parameters | | | | | --- | --- | --- | | y | - | the expression whose return value is to be removed from a dependency tree | ### Return value Returns `y`, no longer a part of a dependency tree. ### Examples file1.cpp: ``` struct foo { int* a; int* b; }; std::atomic<struct foo*> foo_head[10]; int foo_array[10][10]; // consume operation starts a dependency chain, which escapes this function [[carries_dependency]] struct foo* f(int i) { return foo_head[i].load(memory_order_consume); } // the dependency chain enters this function through the right parameter // and is killed before the function ends (so no extra acquire operation takes place) int g(int* x, int* y [[carries_dependency]]) { return std::kill_dependency(foo_array[*x][*y]); } ``` file2.cpp: ``` [[carries_dependency]] struct foo* f(int i); int g(int* x, int* y [[carries_dependency]]); int c = 3; void h(int i) { struct foo* p; p = f(i); // dependency chain started inside f continues into p without undue acquire do_something_with(g(&c, p->a)); // p->b is not brought in from the cache do_something_with(g(p->a, &c)); // left argument does not have the carries_dependency // attribute: memory acquire fence may be issued // p->b becomes visible before g() is entered } ``` ### See also | | | | --- | --- | | [memory\_order](memory_order "cpp/atomic/memory order") (C++11) | defines memory ordering constraints for the given atomic operation (enum) | | [C documentation](https://en.cppreference.com/w/c/atomic/kill_dependency "c/atomic/kill dependency") for `kill_dependency` | cpp ATOMIC_VAR_INIT ATOMIC\_VAR\_INIT ================= | Defined in header `[<atomic>](../header/atomic "cpp/header/atomic")` | | | | --- | --- | --- | | ``` #define ATOMIC_VAR_INIT(value) /* implementation-defined */ ``` | | (since C++11) (deprecated in C++20) | Expands to an expression which can be used to initialize an `[std::atomic](atomic "cpp/atomic/atomic")` object that can be initialized from `value`. If the atomic object has static storage duration, this initialization is [constant initialization](../language/constant_initialization "cpp/language/constant initialization"). ### Notes Accessing the variable during initialization from another thread, even through an atomic operation, is a data race (it may happen if the address is immediately passed to another thread with a `[std::memory\_order\_relaxed](memory_order "cpp/atomic/memory order")` operation). This macro is primarily provided for compatibility with C; it behaves the same as the constructor of `[std::atomic](atomic "cpp/atomic/atomic")`. ### Example ``` #include <atomic> #include <iostream> int main() { std::atomic<int> a = ATOMIC_VAR_INIT(1); // std::atomic<int> a(1); // C++-only alternative std::cout << "Initialized std::atomic<int> as: " << a << '\n'; } ``` Output: ``` Initialized std::atomic<int> as: 1 ``` ### See also | | | | --- | --- | | [atomic\_init](atomic_init "cpp/atomic/atomic init") (C++11)(deprecated in C++20) | non-atomic initialization of a default-constructed atomic object (function template) | | [(constructor)](atomic/atomic "cpp/atomic/atomic/atomic") | constructs an atomic object (public member function of `std::atomic<T>`) | | [C documentation](https://en.cppreference.com/w/c/atomic/ATOMIC_VAR_INIT "c/atomic/ATOMIC VAR INIT") for `ATOMIC_VAR_INIT` | cpp std::atomic_fetch_xor, std::atomic_fetch_xor_explicit std::atomic\_fetch\_xor, std::atomic\_fetch\_xor\_explicit ========================================================== | Defined in header `[<atomic>](../header/atomic "cpp/header/atomic")` | | | | --- | --- | --- | | | (1) | (since C++11) | | ``` template< class T > T atomic_fetch_xor( std::atomic<T>* obj, typename std::atomic<T>::value_type arg ) noexcept; ``` | | | ``` template< class T > T atomic_fetch_xor( volatile std::atomic<T>* obj, typename std::atomic<T>::value_type arg ) noexcept; ``` | | | | (2) | (since C++11) | | ``` template< class T > T atomic_fetch_xor_explicit( std::atomic<T>* obj, typename std::atomic<T>::value_type arg, std::memory_order order) noexcept; ``` | | | ``` template< class T > T atomic_fetch_xor_explicit( volatile std::atomic<T>* obj, typename std::atomic<T>::value_type arg, std::memory_order order) noexcept; ``` | | Atomically replaces the value pointed by `obj` with the result of bitwise XOR between the old value of `obj` and `arg`. Returns the value `obj` held previously. The operation is performed as if the following is executed: 1) `obj->fetch_xor(arg)` 2) `obj->fetch_xor(arg, order)` If `std::atomic<T>` has no `fetch_xor` member (this member is only provided for [integral types](atomic#Specializations_for_integral_types "cpp/atomic/atomic")), the program is ill-formed. ### Parameters | | | | | --- | --- | --- | | obj | - | pointer to the atomic object to modify | | arg | - | the value to bitwise XOR to the value stored in the atomic object | | order | - | the memory synchronization ordering for this operation: all values are permitted. | ### Return value The value immediately preceding the effects of this function in the [modification order](memory_order#Modification_order "cpp/atomic/memory order") of `*obj`. ### Possible implementation | | | --- | | ``` template< class T > T atomic_fetch_xor( std::atomic<T>* obj, typename std::atomic<T>::value_type arg ) { return obj->fetch_xor(arg); } ``` | ### Example ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [P0558R1](https://wg21.link/P0558R1) | C++11 | exact type match required because `T` is deduced from multiple arguments | `T` is deduced from the `atomic` argument only | ### See also | | | | --- | --- | | [fetch\_xor](atomic/fetch_xor "cpp/atomic/atomic/fetch xor") | atomically performs bitwise XOR between the argument and the value of the atomic object and obtains the value held previously (public member function of `std::atomic<T>`) | | [atomic\_fetch\_oratomic\_fetch\_or\_explicit](atomic_fetch_or "cpp/atomic/atomic fetch or") (C++11)(C++11) | replaces the atomic object with the result of bitwise OR with a non-atomic argument and obtains the previous value of the atomic (function template) | | [atomic\_fetch\_andatomic\_fetch\_and\_explicit](atomic_fetch_and "cpp/atomic/atomic fetch and") (C++11)(C++11) | replaces the atomic object with the result of bitwise AND with a non-atomic argument and obtains the previous value of the atomic (function template) | | [C documentation](https://en.cppreference.com/w/c/atomic/atomic_fetch_xor "c/atomic/atomic fetch xor") for `atomic_fetch_xor, atomic_fetch_xor_explicit` | cpp std::atomic_compare_exchange_weak, std::atomic_compare_exchange_strong, std::atomic_compare_exchange_weak_explicit, std::atomic_compare_exchange_strong_explicit std::atomic\_compare\_exchange\_weak, std::atomic\_compare\_exchange\_strong, std::atomic\_compare\_exchange\_weak\_explicit, std::atomic\_compare\_exchange\_strong\_explicit ============================================================================================================================================================================== | Defined in header `[<atomic>](../header/atomic "cpp/header/atomic")` | | | | --- | --- | --- | | | (1) | (since C++11) | | ``` template< class T > bool atomic_compare_exchange_weak( std::atomic<T>* obj, typename std::atomic<T>::value_type* expected, typename std::atomic<T>::value_type desired ) noexcept; ``` | | | ``` template< class T > bool atomic_compare_exchange_weak( volatile std::atomic<T>* obj, typename std::atomic<T>::value_type* expected, typename std::atomic<T>::value_type desired ) noexcept; ``` | | | | (2) | (since C++11) | | ``` template< class T > bool atomic_compare_exchange_strong( std::atomic<T>* obj, typename std::atomic<T>::value_type* expected, typename std::atomic<T>::value_type desired ) noexcept; ``` | | | ``` template< class T > bool atomic_compare_exchange_strong( volatile std::atomic<T>* obj, typename std::atomic<T>::value_type* expected, typename std::atomic<T>::value_type desired ) noexcept; ``` | | | | (3) | (since C++11) | | ``` template< class T > bool atomic_compare_exchange_weak_explicit( std::atomic<T>* obj, typename std::atomic<T>::value_type* expected, typename std::atomic<T>::value_type desired, std::memory_order succ, std::memory_order fail ) noexcept; ``` | | | ``` template< class T > bool atomic_compare_exchange_weak_explicit( volatile std::atomic<T>* obj, typename std::atomic<T>::value_type* expected, typename std::atomic<T>::value_type desired, std::memory_order succ, std::memory_order fail ) noexcept; ``` | | | | (4) | (since C++11) | | ``` template< class T > bool atomic_compare_exchange_strong_explicit( std::atomic<T>* obj, typename std::atomic<T>::value_type* expected, typename std::atomic<T>::value_type desired, std::memory_order succ, std::memory_order fail ) noexcept; ``` | | | ``` template< class T > bool atomic_compare_exchange_strong_explicit( volatile std::atomic<T>* obj, typename std::atomic<T>::value_type* expected, typename std::atomic<T>::value_type desired, std::memory_order succ, std::memory_order fail ) noexcept; ``` | | Atomically compares the [object representation](../language/object "cpp/language/object") (until C++20)[value representation](../language/object "cpp/language/object") (since C++20) of the object pointed to by `obj` with that of the object pointed to by `expected`, and if those are bitwise-equal, replaces the former with `desired` (performs read-modify-write operation). Otherwise, loads the actual value pointed to by `obj` into `*expected` (performs load operation). Copying is performed as if by `[std::memcpy](../string/byte/memcpy "cpp/string/byte/memcpy")`. The memory models for the read-modify-write and load operations are `succ` and `fail` respectively. The (1-2) versions use `[std::memory\_order\_seq\_cst](memory_order "cpp/atomic/memory order")` by default. These functions are defined in terms of member functions of `[std::atomic](atomic "cpp/atomic/atomic")`: 1) `obj->compare_exchange_weak(*expected, desired)` 2) `obj->compare_exchange_strong(*expected, desired)` 3) `obj->compare_exchange_weak(*expected, desired, succ, fail)` 4) `obj->compare_exchange_strong(*expected, desired, succ, fail)` ### Parameters | | | | | --- | --- | --- | | obj | - | pointer to the atomic object to test and modify | | expected | - | pointer to the value expected to be found in the atomic object | | desired | - | the value to store in the atomic object if it is as expected | | succ | - | the memory synchronization ordering for the read-modify-write operation if the comparison succeeds. All values are permitted. | | fail | - | the memory synchronization ordering for the load operation if the comparison fails. Cannot be `[std::memory\_order\_release](memory_order "cpp/atomic/memory order")` or `[std::memory\_order\_acq\_rel](memory_order "cpp/atomic/memory order")` and cannot specify stronger ordering than `succ` (until C++17) | ### Return value The result of the comparison: `true` if `*obj` was equal to `*expected`, `false` otherwise. ### Notes The weak forms ((1) and (3)) of the functions are allowed to fail spuriously, that is, act as if `*obj != *expected` even if they are equal. When a compare-and-exchange is in a loop, the weak version will yield better performance on some platforms. When a weak compare-and-exchange would require a loop and a strong one would not, the strong one is preferable unless the object representation of `T` may include padding bits, (until C++20) trap bits, or offers multiple object representations for the same value (e.g. floating-point NaN). In those cases, weak compare-and-exchange typically works because it quickly converges on some stable object representation. For a union with bits that participate in the value representations of some members but not the others, compare-and-exchange might always fail because such padding bits have indeterminate values when they do not participate in the value representation of the active member. | | | | --- | --- | | Padding bits that never participate in an object's value representation are ignored. | (since C++20) | ### Example compare and exchange operations are often used as basic building blocks of lockfree data structures. ``` #include <atomic> template<class T> struct node { T data; node* next; node(const T& data) : data(data), next(nullptr) {} }; template<class T> class stack { std::atomic<node<T>*> head; public: void push(const T& data) { node<T>* new_node = new node<T>(data); // put the current value of head into new_node->next new_node->next = head.load(std::memory_order_relaxed); // now make new_node the new head, but if the head // is no longer what's stored in new_node->next // (some other thread must have inserted a node just now) // then put that new head into new_node->next and try again while(!std::atomic_compare_exchange_weak_explicit( &head, &new_node->next, new_node, std::memory_order_release, std::memory_order_relaxed)) ; // the body of the loop is empty // note: the above loop is not thread-safe in at least // GCC prior to 4.8.3 (bug 60272), clang prior to 2014-05-05 (bug 18899) // MSVC prior to 2014-03-17 (bug 819819). See member function version for workaround } }; int main() { stack<int> s; s.push(1); s.push(2); s.push(3); } ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [P0558R1](https://wg21.link/P0558R1) | C++11 | exact type match required because `T` is deduced from multiple arguments | `T` is deduced from the `atomic` argument only | ### See also | | | | --- | --- | | [compare\_exchange\_weakcompare\_exchange\_strong](atomic/compare_exchange "cpp/atomic/atomic/compare exchange") | atomically compares the value of the atomic object with non-atomic argument and performs atomic exchange if equal or atomic load if not (public member function of `std::atomic<T>`) | | [atomic\_exchangeatomic\_exchange\_explicit](atomic_exchange "cpp/atomic/atomic exchange") (C++11)(C++11) | atomically replaces the value of the atomic object with non-atomic argument and returns the old value of the atomic (function template) | | | | | --- | --- | | [std::atomic\_compare\_exchange\_weak(std::shared\_ptr) std::atomic\_compare\_exchange\_strong(std::shared\_ptr)](../memory/shared_ptr/atomic "cpp/memory/shared ptr/atomic") (deprecated in C++20) | specializes atomic operations for std::shared\_ptr (function template) | | [C documentation](https://en.cppreference.com/w/c/atomic/atomic_compare_exchange "c/atomic/atomic compare exchange") for `atomic_compare_exchange, atomic_compare_exchange_explicit` |
programming_docs
cpp std::atomic_flag_test, std::atomic_flag_test_explicit std::atomic\_flag\_test, std::atomic\_flag\_test\_explicit ========================================================== | Defined in header `[<atomic>](../header/atomic "cpp/header/atomic")` | | | | --- | --- | --- | | | (1) | (since C++20) | | ``` bool atomic_flag_test( const volatile std::atomic_flag* object ) noexcept; ``` | | | ``` bool atomic_flag_test( const std::atomic_flag* object ) noexcept; ``` | | | | (2) | (since C++20) | | ``` bool atomic_flag_test_explicit( const volatile std::atomic_flag* object, std::memory_order order ) noexcept; ``` | | | ``` bool atomic_flag_test_explicit( const std::atomic_flag* object, std::memory_order order ) noexcept; ``` | | Atomically reads the value of the `*object` and returns the value. 1) Equivalent to `object->test([std::memory\_order\_seq\_cst](http://en.cppreference.com/w/cpp/atomic/memory_order))`. 2) Equivalent to `object->test(order)`. ### Parameters | | | | | --- | --- | --- | | object | - | pointer to the `atomic_flag` object to read | | order | - | the memory synchronization ordering for this operation: must not be `std::memory_order::release` or `std::memory_order::acq_rel` | ### Return value The value atomically read. ### Notes | [Feature-test](../utility/feature_test "cpp/utility/feature test") macro | | --- | | [`__cpp_lib_atomic_flag_test`](../feature_test#Library_features "cpp/feature test") | ### Example ### See also | | | | --- | --- | | [test](atomic_flag/test "cpp/atomic/atomic flag/test") (C++20) | atomically returns the value of the flag (public member function of `std::atomic_flag`) | cpp std::atomic_thread_fence std::atomic\_thread\_fence ========================== | Defined in header `[<atomic>](../header/atomic "cpp/header/atomic")` | | | | --- | --- | --- | | ``` extern "C" void atomic_thread_fence( std::memory_order order ) noexcept; ``` | | (since C++11) | Establishes [memory synchronization ordering](memory_order "cpp/atomic/memory order") of non-atomic and relaxed atomic accesses, as instructed by `order`, without an associated atomic operation. Note however, that at least one atomic operation is required to set up the synchronization, as described below. #### Fence-atomic synchronization A release fence F in thread A synchronizes-with atomic [acquire operation](memory_order "cpp/atomic/memory order") Y in thread B, if. * there exists an atomic store X (with any memory order) * Y reads the value written by X (or the value would be written by [release sequence headed by X](memory_order "cpp/atomic/memory order") if X were a release operation) * F is sequenced-before X in thread A In this case, all non-atomic and relaxed atomic stores that are [sequenced-before](memory_order "cpp/atomic/memory order") F in thread A will [happen-before](memory_order "cpp/atomic/memory order") all non-atomic and relaxed atomic loads from the same locations made in thread B after Y. #### Atomic-fence synchronization An atomic [release operation](memory_order "cpp/atomic/memory order") X in thread A synchronizes-with an acquire fence F in thread B, if. * there exists an atomic read Y (with any memory order) * Y reads the value written by X (or by the [release sequence headed by X](memory_order "cpp/atomic/memory order")) * Y is sequenced-before F in thread B In this case, all non-atomic and relaxed atomic stores that are [sequenced-before](memory_order "cpp/atomic/memory order") X in thread A will [happen-before](memory_order "cpp/atomic/memory order") all non-atomic and relaxed atomic loads from the same locations made in thread B after F. #### Fence-fence synchronization A release fence FA in thread A synchronizes-with an acquire fence FB in thread B, if. * There exists an atomic object M, * There exists an atomic write X (with any memory order) that modifies M in thread A * FA is sequenced-before X in thread A * There exists an atomic read Y (with any memory order) in thread B * Y reads the value written by X (or the value would be written by [release sequence headed by X](memory_order "cpp/atomic/memory order") if X were a release operation) * Y is sequenced-before FB in thread B In this case, all non-atomic and relaxed atomic stores that are [sequenced-before](memory_order "cpp/atomic/memory order") FA in thread A will [happen-before](memory_order "cpp/atomic/memory order") all non-atomic and relaxed atomic loads from the same locations made in thread B after FB. ### Parameters | | | | | --- | --- | --- | | order | - | the memory ordering executed by this fence | ### Return value (none). ### Notes On x86 (including x86-64), `atomic_thread_fence` functions issue no CPU instructions and only affect compile-time code motion, except for `std::atomic_thread_fence(std::memory_order::seq_cst)`, which issues the full memory fence instruction MFENCE (see [C++11 mappings](https://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html) for other architectures). `atomic_thread_fence` imposes stronger synchronization constraints than an atomic store operation with the same `[std::memory\_order](memory_order "cpp/atomic/memory order")`. While an atomic store-release operation prevents all preceding reads and writes from moving past the store-release, an `atomic_thread_fence` with `memory_order_release` ordering prevents all preceding reads and writes from moving past all subsequent stores. Fence-fence synchronization can be used to add synchronization to a sequence of several relaxed atomic operations, for example. ``` //Global std::string computation(int); void print( std::string ); std::atomic<int> arr[3] = { -1, -1, -1 }; std::string data[1000]; //non-atomic data // Thread A, compute 3 values void ThreadA( int v0, int v1, int v2 ) { //assert( 0 <= v0, v1, v2 < 1000 ); data[v0] = computation(v0); data[v1] = computation(v1); data[v2] = computation(v2); std::atomic_thread_fence(std::memory_order_release); std::atomic_store_explicit(&arr[0], v0, std::memory_order_relaxed); std::atomic_store_explicit(&arr[1], v1, std::memory_order_relaxed); std::atomic_store_explicit(&arr[2], v2, std::memory_order_relaxed); } // Thread B, prints between 0 and 3 values already computed. void ThreadB() { int v0 = std::atomic_load_explicit(&arr[0], std::memory_order_relaxed); int v1 = std::atomic_load_explicit(&arr[1], std::memory_order_relaxed); int v2 = std::atomic_load_explicit(&arr[2], std::memory_order_relaxed); std::atomic_thread_fence(std::memory_order_acquire); // v0, v1, v2 might turn out to be -1, some or all of them. // otherwise it is safe to read the non-atomic data because of the fences: if( v0 != -1 ) { print( data[v0] ); } if( v1 != -1 ) { print( data[v1] ); } if( v2 != -1 ) { print( data[v2] ); } } ``` ### Example Scan an array of mailboxes, and process only the ones intended for us, without unnecessary synchronization. This example uses atomic-fence synchronization. ``` const int num_mailboxes = 32; std::atomic<int> mailbox_receiver[num_mailboxes]; std::string mailbox_data[num_mailboxes]; // The writer threads update non-atomic shared data // and then update mailbox_receiver[i] as follows mailbox_data[i] = ...; std::atomic_store_explicit(&mailbox_receiver[i], receiver_id, std::memory_order_release); // Reader thread needs to check all mailbox[i], but only needs to sync with one for (int i = 0; i < num_mailboxes; ++i) { if (std::atomic_load_explicit(&mailbox_receiver[i], std::memory_order_relaxed) == my_id) { std::atomic_thread_fence(std::memory_order_acquire); // synchronize with just one writer do_work( mailbox_data[i] ); // guaranteed to observe everything done in the writer thread before // the atomic_store_explicit() } } ``` ### See also | | | | --- | --- | | [memory\_order](memory_order "cpp/atomic/memory order") (C++11) | defines memory ordering constraints for the given atomic operation (enum) | | [atomic\_signal\_fence](atomic_signal_fence "cpp/atomic/atomic signal fence") (C++11) | fence between a thread and a signal handler executed in the same thread (function) | | [C documentation](https://en.cppreference.com/w/c/atomic/atomic_thread_fence "c/atomic/atomic thread fence") for `atomic_thread_fence` | cpp std::atomic_fetch_or, std::atomic_fetch_or_explicit std::atomic\_fetch\_or, std::atomic\_fetch\_or\_explicit ======================================================== | Defined in header `[<atomic>](../header/atomic "cpp/header/atomic")` | | | | --- | --- | --- | | | (1) | (since C++11) | | ``` template< class T > T atomic_fetch_or( std::atomic<T>* obj, typename std::atomic<T>::value_type arg ) noexcept; ``` | | | ``` template< class T > T atomic_fetch_or( volatile std::atomic<T>* obj, typename std::atomic<T>::value_type arg ) noexcept; ``` | | | | (2) | (since C++11) | | ``` template< class T > T atomic_fetch_or_explicit( std::atomic<T>* obj, typename std::atomic<T>::value_type arg, std::memory_order order) noexcept; ``` | | | ``` template< class T > T atomic_fetch_or_explicit( volatile std::atomic<T>* obj, typename std::atomic<T>::value_type arg, std::memory_order order) noexcept; ``` | | Atomically replaces the value pointed by `obj` with the result of bitwise OR between the old value of `obj` and `arg`. Returns the value `obj` held previously. The operation is performed as if the following is executed: 1) `obj->fetch_or(arg)` 2) `obj->fetch_or(arg, order)` If `std::atomic<T>` has no `fetch_or` member (this member is only provided for [integral types](atomic#Specializations_for_integral_types "cpp/atomic/atomic")), the program is ill-formed. ### Parameters | | | | | --- | --- | --- | | obj | - | pointer to the atomic object to modify | | arg | - | the value to bitwise OR to the value stored in the atomic object | | order | - | the memory synchronization ordering for this operation: all values are permitted. | ### Return value The value immediately preceding the effects of this function in the [modification order](memory_order#Modification_order "cpp/atomic/memory order") of `*obj`. ### Possible implementation | | | --- | | ``` template< class T > T atomic_fetch_or( std::atomic<T>* obj, typename std::atomic<T>::value_type arg ) { return obj->fetch_or(arg); } ``` | ### Example ``` #include <iostream> #include <atomic> #include <thread> #include <chrono> #include <functional> // Binary semaphore for demonstrative purposes only // This is a simple yet meaningful example: atomic operations // are unnecessary without threads. class Semaphore { std::atomic_char m_signaled; public: Semaphore(bool initial = false) { m_signaled = initial; } // Block until semaphore is signaled void take() { while (!std::atomic_fetch_and(&m_signaled, false)) { std::this_thread::sleep_for(std::chrono::milliseconds(10)); } } void put() { std::atomic_fetch_or(&m_signaled, true); } }; class ThreadedCounter { static const int N = 100; static const int REPORT_INTERVAL = 10; int m_count; bool m_done; Semaphore m_count_sem; Semaphore m_print_sem; void count_up() { for (m_count = 1; m_count <= N; m_count++) { if (m_count % REPORT_INTERVAL == 0) { if (m_count == N) m_done = true; m_print_sem.put(); // signal printing to occur m_count_sem.take(); // wait until printing is complete proceeding } } std::cout << "count_up() done\n"; m_done = true; m_print_sem.put(); } void print_count() { do { m_print_sem.take(); std::cout << m_count << '\n'; m_count_sem.put(); } while (!m_done); std::cout << "print_count() done\n"; } public: ThreadedCounter() : m_done(false) {} void run() { auto print_thread = std::thread(&ThreadedCounter::print_count, this); auto count_thread = std::thread(&ThreadedCounter::count_up, this); print_thread.join(); count_thread.join(); } }; int main() { ThreadedCounter m_counter; m_counter.run(); } ``` Output: ``` 10 20 30 40 50 60 70 80 90 100 print_count() done count_up() done ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [P0558R1](https://wg21.link/P0558R1) | C++11 | exact type match required because `T` is deduced from multiple arguments | `T` is deduced from the `atomic` argument only | ### See also | | | | --- | --- | | [fetch\_or](atomic/fetch_or "cpp/atomic/atomic/fetch or") | atomically performs bitwise OR between the argument and the value of the atomic object and obtains the value held previously (public member function of `std::atomic<T>`) | | [atomic\_fetch\_andatomic\_fetch\_and\_explicit](atomic_fetch_and "cpp/atomic/atomic fetch and") (C++11)(C++11) | replaces the atomic object with the result of bitwise AND with a non-atomic argument and obtains the previous value of the atomic (function template) | | [atomic\_fetch\_xoratomic\_fetch\_xor\_explicit](atomic_fetch_xor "cpp/atomic/atomic fetch xor") (C++11)(C++11) | replaces the atomic object with the result of bitwise XOR with a non-atomic argument and obtains the previous value of the atomic (function template) | | [C documentation](https://en.cppreference.com/w/c/atomic/atomic_fetch_or "c/atomic/atomic fetch or") for `atomic_fetch_or, atomic_fetch_or_explicit` | cpp std::atomic_fetch_add, std::atomic_fetch_add_explicit std::atomic\_fetch\_add, std::atomic\_fetch\_add\_explicit ========================================================== | Defined in header `[<atomic>](../header/atomic "cpp/header/atomic")` | | | | --- | --- | --- | | | (1) | | | ``` template< class T > T atomic_fetch_add( std::atomic<T>* obj, typename std::atomic<T>::difference_type arg ) noexcept; ``` | | | ``` template< class T > T atomic_fetch_add( volatile std::atomic<T>* obj, typename std::atomic<T>::difference_type arg ) noexcept; ``` | | | | (2) | | | ``` template< class T > T atomic_fetch_add_explicit( std::atomic<T>* obj, typename std::atomic<T>::difference_type arg, std::memory_order order ) noexcept; ``` | | | ``` template< class T > T atomic_fetch_add_explicit( volatile std::atomic<T>* obj, typename std::atomic<T>::difference_type arg, std::memory_order order ) noexcept; ``` | | Performs atomic addition. Atomically adds `arg` to the value pointed to by `obj` and returns the value `obj` held previously. The operation is performed as if the following was executed: 1) `obj->fetch_add(arg)` 2) `obj->fetch_add(arg, order)` ### Parameters | | | | | --- | --- | --- | | obj | - | pointer to the atomic object to modify | | arg | - | the value to add to the value stored in the atomic object | | order | - | the memory synchronization ordering for this operation: all values are permitted. | ### Return value The value immediately preceding the effects of this function in the [modification order](memory_order#Modification_order "cpp/atomic/memory order") of `*obj`. ### Possible implementation | | | --- | | ``` template< class T > T atomic_fetch_add( std::atomic<T>* obj, typename std::atomic<T>::difference_type arg ) { return obj->fetch_add(arg); } ``` | ### Example Single-writer/multiple-reader lock can be made with fetch\_add. Note that this simplistic implementation is not lockout-free. ``` #include <string> #include <thread> #include <vector> #include <iostream> #include <atomic> #include <chrono> // meaning of cnt: // 5: there are no active readers or writers. // 1...4: there are 4...1 readers active, The writer is blocked // 0: temporary value between fetch_sub and fetch_add in reader lock // -1: there is a writer active. The readers are blocked. const int N = 5; // four concurrent readers are allowed std::atomic<int> cnt(N); std::vector<int> data; void reader(int id) { for(;;) { // lock while(std::atomic_fetch_sub(&cnt, 1) <= 0) std::atomic_fetch_add(&cnt, 1); // read if(!data.empty()) std::cout << ( "reader " + std::to_string(id) + " sees " + std::to_string(*data.rbegin()) + '\n'); if(data.size() == 25) break; // unlock std::atomic_fetch_add(&cnt, 1); // pause std::this_thread::sleep_for(std::chrono::milliseconds(1)); } } void writer() { for(int n = 0; n < 25; ++n) { // lock while(std::atomic_fetch_sub(&cnt, N+1) != N) std::atomic_fetch_add(&cnt, N+1); // write data.push_back(n); std::cout << "writer pushed back " << n << '\n'; // unlock std::atomic_fetch_add(&cnt, N+1); // pause std::this_thread::sleep_for(std::chrono::milliseconds(1)); } } int main() { std::vector<std::thread> v; for (int n = 0; n < N; ++n) { v.emplace_back(reader, n); } v.emplace_back(writer); for (auto& t : v) { t.join(); } } ``` Output: ``` writer pushed back 0 reader 2 sees 0 reader 3 sees 0 reader 1 sees 0 <...> reader 2 sees 24 reader 4 sees 24 reader 1 sees 24 ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [P0558R1](https://wg21.link/P0558R1) | C++11 | exact type match required because `T` is deduced from multiple arguments | `T` is deduced from the `atomic` argument only | ### See also | | | | --- | --- | | [fetch\_add](atomic/fetch_add "cpp/atomic/atomic/fetch add") | atomically adds the argument to the value stored in the atomic object and obtains the value held previously (public member function of `std::atomic<T>`) | | [atomic\_fetch\_subatomic\_fetch\_sub\_explicit](atomic_fetch_sub "cpp/atomic/atomic fetch sub") (C++11)(C++11) | subtracts a non-atomic value from an atomic object and obtains the previous value of the atomic (function template) | | [C documentation](https://en.cppreference.com/w/c/atomic/atomic_fetch_add "c/atomic/atomic fetch add") for `atomic_fetch_add, atomic_fetch_add_explicit` | cpp std::atomic_flag_notify_all std::atomic\_flag\_notify\_all ============================== | Defined in header `[<atomic>](../header/atomic "cpp/header/atomic")` | | | | --- | --- | --- | | | | (since C++20) | | ``` void atomic_flag_notify_all( std::atomic_flag* object ) noexcept; ``` | | | | ``` void atomic_flag_notify_all( volatile std::atomic_flag* object ) noexcept; ``` | | | Performs atomic notifying operations. Unblocks all threads blocked in atomic waiting operations (i.e. `[std::atomic\_flag\_wait()](atomic_flag_wait "cpp/atomic/atomic flag wait")`, `[std::atomic\_flag\_wait\_explicit()](atomic_flag_wait "cpp/atomic/atomic flag wait")`, or `std::atomic_flag::wait()`) on `*object`, if there are any; otherwise does nothing. Equivalent to `object->notify_all()`. ### Parameters | | | | | --- | --- | --- | | object | - | pointer to the atomic\_flag object to notify | ### Return value (none). ### Notes This form of change-detection is often more efficient than simple polling or pure spinlocks. ### Example ### See also | | | | --- | --- | | [notify\_one](atomic_flag/notify_one "cpp/atomic/atomic flag/notify one") (C++20) | notifies at least one thread waiting on the atomic object (public member function of `std::atomic_flag`) | | [notify\_all](atomic_flag/notify_all "cpp/atomic/atomic flag/notify all") (C++20) | notifies all threads blocked waiting on the atomic object (public member function of `std::atomic_flag`) | | [atomic\_flag\_waitatomic\_flag\_wait\_explicit](atomic_flag_wait "cpp/atomic/atomic flag wait") (C++20)(C++20) | blocks the thread until notified and the flag changes (function) | | [atomic\_flag\_notify\_one](atomic_flag_notify_one "cpp/atomic/atomic flag notify one") (C++20) | notifies a thread blocked in atomic\_flag\_wait (function) |
programming_docs
cpp std::atomic std::atomic =========== | Defined in header `[<atomic>](../header/atomic "cpp/header/atomic")` | | | | --- | --- | --- | | ``` template< class T > struct atomic; ``` | (1) | (since C++11) | | ``` template< class U > struct atomic<U*>; ``` | (2) | (since C++11) | | Defined in header `[<memory>](../header/memory "cpp/header/memory")` | | | | ``` template< class U > struct atomic<std::shared_ptr<U>>; ``` | (3) | (since C++20) | | ``` template< class U > struct atomic<std::weak_ptr<U>>; ``` | (4) | (since C++20) | | Defined in header `[<stdatomic.h>](../header/stdatomic.h "cpp/header/stdatomic.h")` | | | | ``` #define _Atomic(T) /* see below */ ``` | (5) | (since C++23) | Each instantiation and full specialization of the `std::atomic` template defines an atomic type. If one thread writes to an atomic object while another thread reads from it, the behavior is well-defined (see [memory model](../language/memory_model "cpp/language/memory model") for details on data races). In addition, accesses to atomic objects may establish inter-thread synchronization and order non-atomic memory accesses as specified by `[std::memory\_order](memory_order "cpp/atomic/memory order")`. `std::atomic` is neither copyable nor movable. | | | | --- | --- | | The compatibility macro `_Atomic` is provided in [`<stdatomic.h>`](../header/stdatomic.h "cpp/header/stdatomic.h") such that `_Atomic(T)` is identical to `std::atomic<T>` while both are well-formed. It is unspecified whether any declaration in namespace `std` is available when `<stdatomic.h>` is included. | (since C++23) | ### Specializations #### Primary template The primary `std::atomic` template may be instantiated with any [TriviallyCopyable](../named_req/triviallycopyable "cpp/named req/TriviallyCopyable") type `T` satisfying both [CopyConstructible](../named_req/copyconstructible "cpp/named req/CopyConstructible") and [CopyAssignable](../named_req/copyassignable "cpp/named req/CopyAssignable"). The program is ill-formed if any of following values is `false`: * `[std::is\_trivially\_copyable](http://en.cppreference.com/w/cpp/types/is_trivially_copyable)<T>::value` * `[std::is\_copy\_constructible](http://en.cppreference.com/w/cpp/types/is_copy_constructible)<T>::value` * `[std::is\_move\_constructible](http://en.cppreference.com/w/cpp/types/is_move_constructible)<T>::value` * `[std::is\_copy\_assignable](http://en.cppreference.com/w/cpp/types/is_copy_assignable)<T>::value` * `[std::is\_move\_assignable](http://en.cppreference.com/w/cpp/types/is_move_assignable)<T>::value` ``` struct Counters { int a; int b; }; // user-defined trivially-copyable type std::atomic<Counters> cnt; // specialization for the user-defined type ``` `std::atomic<bool>` uses the primary template. It is guaranteed to be a standard layout struct. #### Partial specializations The standard library provides partial specializations of the `std::atomic` template for the following types with additional properties that the primary template does not have: 2) Partial specializations `std::atomic<U*>` for all pointer types. These specializations have standard layout, trivial default constructors, (until C++20) and trivial destructors. Besides the operations provided for all atomic types, these specializations additionally support atomic arithmetic operations appropriate to pointer types, such as [`fetch_add`](atomic/fetch_add "cpp/atomic/atomic/fetch add"), [`fetch_sub`](atomic/fetch_sub "cpp/atomic/atomic/fetch sub"). | | | | --- | --- | | 3-4) Partial specializations `std::atomic<[std::shared\_ptr](http://en.cppreference.com/w/cpp/memory/shared_ptr)<U>>` and `std::atomic<[std::weak\_ptr](http://en.cppreference.com/w/cpp/memory/weak_ptr)<U>>` are provided for `[std::shared\_ptr](../memory/shared_ptr "cpp/memory/shared ptr")` and `[std::weak\_ptr](../memory/weak_ptr "cpp/memory/weak ptr")`. See [std::atomic<std::shared\_ptr>](../memory/shared_ptr/atomic2 "cpp/memory/shared ptr/atomic2") and [std::atomic<std::weak\_ptr>](../memory/weak_ptr/atomic2 "cpp/memory/weak ptr/atomic2") for details. | (since C++20) | #### Specializations for integral types When instantiated with one of the following integral types, `std::atomic` provides additional atomic operations appropriate to integral types such as [`fetch_add`](atomic/fetch_add "cpp/atomic/atomic/fetch add"), [`fetch_sub`](atomic/fetch_sub "cpp/atomic/atomic/fetch sub"), [`fetch_and`](atomic/fetch_and "cpp/atomic/atomic/fetch and"), [`fetch_or`](atomic/fetch_or "cpp/atomic/atomic/fetch or"), [`fetch_xor`](atomic/fetch_xor "cpp/atomic/atomic/fetch xor"): * The character types `char`, `char8_t` (since C++20), `char16_t`, `char32_t`, and `wchar_t`; * The standard signed integer types: `signed char`, `short`, `int`, `long`, and `long long`; * The standard unsigned integer types: `unsigned char`, `unsigned short`, `unsigned int`, `unsigned long`, and `unsigned long long`; * Any additional integral types needed by the typedefs in the header [`<cstdint>`](../header/cstdint "cpp/header/cstdint"). Additionally, the resulting `std::atomic<*Integral*>` specialization has standard layout, a trivial default constructor, (until C++20) and a trivial destructor. Signed integer arithmetic is defined to use two's complement; there are no undefined results. | | | | --- | --- | | Specializations for floating-point types When instantiated with one of the standard floating-point types `float`, `double`, and `long double`, or one extended floating-point type (since C++23), `std::atomic` provides additional atomic operations appropriate to floating-point types such as [`fetch_add`](atomic/fetch_add "cpp/atomic/atomic/fetch add") and [`fetch_sub`](atomic/fetch_sub "cpp/atomic/atomic/fetch sub"). Additionally, the resulting `std::atomic<*Floating*>` specialization has standard layout and a trivial destructor. No operations result in undefined behavior even if the result is not representable in the floating-point type. The [floating-point environment](../numeric/fenv "cpp/numeric/fenv") in effect may be different from the calling thread's floating-point environment. | (since C++20) | ### Type aliases Type aliases are provided for `bool` and all integral types listed above, as follows: | | | --- | | Aliases for all `std::atomic<Integral>` | | **atomic\_bool** (C++11) | `std::atomic<bool>` (typedef) | | **atomic\_char** (C++11) | `std::atomic<char>` (typedef) | | **atomic\_schar** (C++11) | `std::atomic<signed char>` (typedef) | | **atomic\_uchar** (C++11) | `std::atomic<unsigned char>` (typedef) | | **atomic\_short** (C++11) | `std::atomic<short>` (typedef) | | **atomic\_ushort** (C++11) | `std::atomic<unsigned short>` (typedef) | | **atomic\_int** (C++11) | `std::atomic<int>` (typedef) | | **atomic\_uint** (C++11) | `std::atomic<unsigned int>` (typedef) | | **atomic\_long** (C++11) | `std::atomic<long>` (typedef) | | **atomic\_ulong** (C++11) | `std::atomic<unsigned long>` (typedef) | | **atomic\_llong** (C++11) | `std::atomic<long long>` (typedef) | | **atomic\_ullong** (C++11) | `std::atomic<unsigned long long>` (typedef) | | **atomic\_char8\_t** (C++20) | `std::atomic<char8_t>` (typedef) | | **atomic\_char16\_t** (C++11) | `std::atomic<char16_t>` (typedef) | | **atomic\_char32\_t** (C++11) | `std::atomic<char32_t>` (typedef) | | **atomic\_wchar\_t** (C++11) | `std::atomic<wchar_t>` (typedef) | | **atomic\_int8\_t** (C++11)(optional) | `std::atomic<[std::int8\_t](http://en.cppreference.com/w/cpp/types/integer)>` (typedef) | | **atomic\_uint8\_t** (C++11)(optional) | `std::atomic<[std::uint8\_t](http://en.cppreference.com/w/cpp/types/integer)>` (typedef) | | **atomic\_int16\_t** (C++11)(optional) | `std::atomic<[std::int16\_t](http://en.cppreference.com/w/cpp/types/integer)>` (typedef) | | **atomic\_uint16\_t** (C++11)(optional) | `std::atomic<[std::uint16\_t](http://en.cppreference.com/w/cpp/types/integer)>` (typedef) | | **atomic\_int32\_t** (C++11)(optional) | `std::atomic<[std::int32\_t](http://en.cppreference.com/w/cpp/types/integer)>` (typedef) | | **atomic\_uint32\_t** (C++11)(optional) | `std::atomic<[std::uint32\_t](http://en.cppreference.com/w/cpp/types/integer)>` (typedef) | | **atomic\_int64\_t** (C++11)(optional) | `std::atomic<[std::int64\_t](http://en.cppreference.com/w/cpp/types/integer)>` (typedef) | | **atomic\_uint64\_t** (C++11)(optional) | `std::atomic<[std::uint64\_t](http://en.cppreference.com/w/cpp/types/integer)>` (typedef) | | **atomic\_int\_least8\_t** (C++11) | `std::atomic<[std::int\_least8\_t](http://en.cppreference.com/w/cpp/types/integer)>` (typedef) | | **atomic\_uint\_least8\_t** (C++11) | `std::atomic<[std::uint\_least8\_t](http://en.cppreference.com/w/cpp/types/integer)>` (typedef) | | **atomic\_int\_least16\_t** (C++11) | `std::atomic<[std::int\_least16\_t](http://en.cppreference.com/w/cpp/types/integer)>` (typedef) | | **atomic\_uint\_least16\_t** (C++11) | `std::atomic<[std::uint\_least16\_t](http://en.cppreference.com/w/cpp/types/integer)>` (typedef) | | **atomic\_int\_least32\_t** (C++11) | `std::atomic<[std::int\_least32\_t](http://en.cppreference.com/w/cpp/types/integer)>` (typedef) | | **atomic\_uint\_least32\_t** (C++11) | `std::atomic<[std::uint\_least32\_t](http://en.cppreference.com/w/cpp/types/integer)>` (typedef) | | **atomic\_int\_least64\_t** (C++11) | `std::atomic<[std::int\_least64\_t](http://en.cppreference.com/w/cpp/types/integer)>` (typedef) | | **atomic\_uint\_least64\_t** (C++11) | `std::atomic<[std::uint\_least64\_t](http://en.cppreference.com/w/cpp/types/integer)>` (typedef) | | **atomic\_int\_fast8\_t** (C++11) | `std::atomic<[std::int\_fast8\_t](http://en.cppreference.com/w/cpp/types/integer)>` (typedef) | | **atomic\_uint\_fast8\_t** (C++11) | `std::atomic<[std::uint\_fast8\_t](http://en.cppreference.com/w/cpp/types/integer)>` (typedef) | | **atomic\_int\_fast16\_t** (C++11) | `std::atomic<[std::int\_fast16\_t](http://en.cppreference.com/w/cpp/types/integer)>` (typedef) | | **atomic\_uint\_fast16\_t** (C++11) | `std::atomic<[std::uint\_fast16\_t](http://en.cppreference.com/w/cpp/types/integer)>` (typedef) | | **atomic\_int\_fast32\_t** (C++11) | `std::atomic<[std::int\_fast32\_t](http://en.cppreference.com/w/cpp/types/integer)>` (typedef) | | **atomic\_uint\_fast32\_t** (C++11) | `std::atomic<[std::uint\_fast32\_t](http://en.cppreference.com/w/cpp/types/integer)>` (typedef) | | **atomic\_int\_fast64\_t** (C++11) | `std::atomic<[std::int\_fast64\_t](http://en.cppreference.com/w/cpp/types/integer)>` (typedef) | | **atomic\_uint\_fast64\_t** (C++11) | `std::atomic<[std::uint\_fast64\_t](http://en.cppreference.com/w/cpp/types/integer)>` (typedef) | | **atomic\_intptr\_t** (C++11)(optional) | `std::atomic<[std::intptr\_t](http://en.cppreference.com/w/cpp/types/integer)>` (typedef) | | **atomic\_uintptr\_t** (C++11)(optional) | `std::atomic<[std::uintptr\_t](http://en.cppreference.com/w/cpp/types/integer)>` (typedef) | | **atomic\_size\_t** (C++11) | `std::atomic<[std::size\_t](http://en.cppreference.com/w/cpp/types/size_t)>` (typedef) | | **atomic\_ptrdiff\_t** (C++11) | `std::atomic<[std::ptrdiff\_t](http://en.cppreference.com/w/cpp/types/ptrdiff_t)>` (typedef) | | **atomic\_intmax\_t** (C++11) | `std::atomic<[std::intmax\_t](http://en.cppreference.com/w/cpp/types/integer)>` (typedef) | | **atomic\_uintmax\_t** (C++11) | `std::atomic<[std::uintmax\_t](http://en.cppreference.com/w/cpp/types/integer)>` (typedef) | | Aliases for special-purpose types | | **atomic\_signed\_lock\_free** (C++20) | a signed integral atomic type that is lock-free and for which waiting/notifying is most efficient (typedef) | | **atomic\_unsigned\_lock\_free** (C++20) | a unsigned integral atomic type that is lock-free and for which waiting/notifying is most efficient (typedef) | Note: `std::atomic_int*N*_t`, `std::atomic_uint*N*_t`, `std::atomic_intptr_t`, and `atomic_uintptr_t` are defined if and only if `std::int*N*_t`, `std::uint*N*_t`, `std::intptr_t`, and `std::uintptr_t` are defined, respectively. | | | | --- | --- | | `std::atomic_signed_lock_free` and `std::atomic_unsigned_lock_free` are optional in freestanding implementations. | (since C++20) | ### Member types | Member type | Definition | | --- | --- | | `value_type` | `T` (regardless of whether specialized or not) | | `difference_type` | `value_type` (only for `atomic<*Integral*>` and `atomic<*Floating*>` (since C++20) specializations) `[std::ptrdiff\_t](../types/ptrdiff_t "cpp/types/ptrdiff t")` (only for `atomic<U*>` specializations) | `difference_type` is not defined in the primary `atomic` template or in the partial specializations for `[std::shared\_ptr](../memory/shared_ptr "cpp/memory/shared ptr")` and `[std::weak\_ptr](../memory/weak_ptr "cpp/memory/weak ptr")`. ### Member functions | | | | --- | --- | | [(constructor)](atomic/atomic "cpp/atomic/atomic/atomic") | constructs an atomic object (public member function) | | [operator=](atomic/operator= "cpp/atomic/atomic/operator=") | stores a value into an atomic object (public member function) | | [is\_lock\_free](atomic/is_lock_free "cpp/atomic/atomic/is lock free") | checks if the atomic object is lock-free (public member function) | | [store](atomic/store "cpp/atomic/atomic/store") | atomically replaces the value of the atomic object with a non-atomic argument (public member function) | | [load](atomic/load "cpp/atomic/atomic/load") | atomically obtains the value of the atomic object (public member function) | | [operator T](atomic/operator_t "cpp/atomic/atomic/operator T") | loads a value from an atomic object (public member function) | | [exchange](atomic/exchange "cpp/atomic/atomic/exchange") | atomically replaces the value of the atomic object and obtains the value held previously (public member function) | | [compare\_exchange\_weakcompare\_exchange\_strong](atomic/compare_exchange "cpp/atomic/atomic/compare exchange") | atomically compares the value of the atomic object with non-atomic argument and performs atomic exchange if equal or atomic load if not (public member function) | | [wait](atomic/wait "cpp/atomic/atomic/wait") (C++20) | blocks the thread until notified and the atomic value changes (public member function) | | [notify\_one](atomic/notify_one "cpp/atomic/atomic/notify one") (C++20) | notifies at least one thread waiting on the atomic object (public member function) | | [notify\_all](atomic/notify_all "cpp/atomic/atomic/notify all") (C++20) | notifies all threads blocked waiting on the atomic object (public member function) | | Constants | | [is\_always\_lock\_free](atomic/is_always_lock_free "cpp/atomic/atomic/is always lock free") [static] (C++17) | indicates that the type is always lock-free (public static member constant) | ### Specialized member functions | | | | --- | --- | | [fetch\_add](atomic/fetch_add "cpp/atomic/atomic/fetch add") | atomically adds the argument to the value stored in the atomic object and obtains the value held previously (public member function) | | [fetch\_sub](atomic/fetch_sub "cpp/atomic/atomic/fetch sub") | atomically subtracts the argument from the value stored in the atomic object and obtains the value held previously (public member function) | | [fetch\_and](atomic/fetch_and "cpp/atomic/atomic/fetch and") | atomically performs bitwise AND between the argument and the value of the atomic object and obtains the value held previously (public member function) | | [fetch\_or](atomic/fetch_or "cpp/atomic/atomic/fetch or") | atomically performs bitwise OR between the argument and the value of the atomic object and obtains the value held previously (public member function) | | [fetch\_xor](atomic/fetch_xor "cpp/atomic/atomic/fetch xor") | atomically performs bitwise XOR between the argument and the value of the atomic object and obtains the value held previously (public member function) | | [operator++operator++(int)operator--operator--(int)](atomic/operator_arith "cpp/atomic/atomic/operator arith") | increments or decrements the atomic value by one (public member function) | | [operator+=operator-=operator&=operator|=operator^=](atomic/operator_arith2 "cpp/atomic/atomic/operator arith2") | adds, subtracts, or performs bitwise AND, OR, XOR with the atomic value (public member function) | ### Notes There are non-member function template equivalents for all member functions of `std::atomic`. Those non-member functions may be additionally overloaded for types that are not specializations of `std::atomic`, but are able to guarantee atomicity. The only such type in the standard library is `[std::shared\_ptr](http://en.cppreference.com/w/cpp/memory/shared_ptr)<U>`. `_Atomic` is a [keyword](https://en.cppreference.com/w/c/keyword/_Atomic "c/keyword/ Atomic") and used to provide [atomic types](https://en.cppreference.com/w/c/language/atomic "c/language/atomic") in C. Implementations are recommended to ensure that the representation of `_Atomic(T)` in C is same as that of `std::atomic<T>` in C++ for every possible type `T`. The mechanisms used to ensure atomicity and memory ordering should be compatible. On gcc and clang, some of the functionality described here requires linking against `-latomic`. ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 2441](https://cplusplus.github.io/LWG/issue2441) | C++11 | typedefs for atomic versions of optional[fixed width integer types](../types/integer "cpp/types/integer") were missing | added | | [P0558R1](https://wg21.link/P0558R1) | C++11 | template argument deduction for some functionsfor atomic types might accidently fail;invalid pointer operations were provided | specification was substantially rewritten:member typedefs `value_type` and `difference_type` are added | | [LWG 3012](https://cplusplus.github.io/LWG/issue3012) | C++11 | `std::atomic<T>` was permitted forany `T` that is trivially copyable but not copyable | such specializations are forbidden | ### See also | | | | --- | --- | | [atomic\_flag](atomic_flag "cpp/atomic/atomic flag") (C++11) | the lock-free boolean atomic type (class) | | [std::atomic<std::shared\_ptr>](../memory/shared_ptr/atomic2 "cpp/memory/shared ptr/atomic2") (C++20) | atomic shared pointer (class template specialization) | | [std::atomic<std::weak\_ptr>](../memory/weak_ptr/atomic2 "cpp/memory/weak ptr/atomic2") (C++20) | atomic weak pointer (class template specialization) | | [C documentation](https://en.cppreference.com/w/c/language/atomic "c/language/atomic") for Atomic types | cpp std::atomic_flag std::atomic\_flag ================= | Defined in header `[<atomic>](../header/atomic "cpp/header/atomic")` | | | | --- | --- | --- | | ``` class atomic_flag; ``` | | (since C++11) | `std::atomic_flag` is an atomic boolean type. Unlike all specializations of `[std::atomic](atomic "cpp/atomic/atomic")`, it is guaranteed to be lock-free. Unlike `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<bool>`, `std::atomic_flag` does not provide load or store operations. ### Member functions | | | | --- | --- | | [(constructor)](atomic_flag/atomic_flag "cpp/atomic/atomic flag/atomic flag") | constructs an atomic\_flag (public member function) | | [operator=](atomic_flag/operator= "cpp/atomic/atomic flag/operator=") | the assignment operator (public member function) | | [clear](atomic_flag/clear "cpp/atomic/atomic flag/clear") | atomically sets flag to `false` (public member function) | | [test\_and\_set](atomic_flag/test_and_set "cpp/atomic/atomic flag/test and set") | atomically sets the flag to `true` and obtains its previous value (public member function) | | [test](atomic_flag/test "cpp/atomic/atomic flag/test") (C++20) | atomically returns the value of the flag (public member function) | | [wait](atomic_flag/wait "cpp/atomic/atomic flag/wait") (C++20) | blocks the thread until notified and the atomic value changes (public member function) | | [notify\_one](atomic_flag/notify_one "cpp/atomic/atomic flag/notify one") (C++20) | notifies at least one thread waiting on the atomic object (public member function) | | [notify\_all](atomic_flag/notify_all "cpp/atomic/atomic flag/notify all") (C++20) | notifies all threads blocked waiting on the atomic object (public member function) | ### Example A spinlock mutex demo can be implemented in userspace using an `atomic_flag`. Do note that spinlock mutexes are [extremely dubious](https://www.realworldtech.com/forum/?threadid=189711&curpostid=189723) in practice. ``` #include <thread> #include <vector> #include <iostream> #include <atomic> std::atomic_flag lock = ATOMIC_FLAG_INIT; void f(int n) { for (int cnt = 0; cnt < 40; ++cnt) { while (lock.test_and_set(std::memory_order_acquire)) { // acquire lock // Since C++20, it is possible to update atomic_flag's // value only when there is a chance to acquire the lock. // See also: https://stackoverflow.com/questions/62318642 #if defined(__cpp_lib_atomic_flag_test) while (lock.test(std::memory_order_relaxed)) // test lock #endif ; // spin } static int out{}; std::cout << n << ((++out % 40) == 0 ? '\n' : ' '); lock.clear(std::memory_order_release); // release lock } } int main() { std::vector<std::thread> v; for (int n = 0; n < 10; ++n) { v.emplace_back(f, n); } for (auto& t : v) { t.join(); } } ``` Possible output: ``` 0 1 1 2 0 1 3 2 3 2 0 1 2 3 2 3 0 1 3 2 0 1 2 3 2 3 0 3 2 3 2 3 2 3 1 2 3 0 1 3 2 3 2 0 1 2 3 0 1 2 3 2 0 1 2 3 0 1 2 3 2 3 2 3 2 0 1 2 3 2 3 0 1 3 2 3 0 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 3 2 0 2 3 2 3 2 3 2 3 2 3 0 3 2 3 0 3 0 3 2 3 0 3 2 3 2 3 0 2 3 0 3 2 0 2 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 ``` ### See also | | | | --- | --- | | [atomic\_flag\_test\_and\_setatomic\_flag\_test\_and\_set\_explicit](atomic_flag_test_and_set "cpp/atomic/atomic flag test and set") (C++11)(C++11) | atomically sets the flag to `true` and returns its previous value (function) | | [atomic\_flag\_clearatomic\_flag\_clear\_explicit](atomic_flag_clear "cpp/atomic/atomic flag clear") (C++11)(C++11) | atomically sets the value of the flag to `false` (function) | | [atomic\_flag\_waitatomic\_flag\_wait\_explicit](atomic_flag_wait "cpp/atomic/atomic flag wait") (C++20)(C++20) | blocks the thread until notified and the flag changes (function) | | [atomic\_flag\_notify\_one](atomic_flag_notify_one "cpp/atomic/atomic flag notify one") (C++20) | notifies a thread blocked in atomic\_flag\_wait (function) | | [atomic\_flag\_notify\_all](atomic_flag_notify_all "cpp/atomic/atomic flag notify all") (C++20) | notifies all threads blocked in atomic\_flag\_wait (function) | | [ATOMIC\_FLAG\_INIT](atomic_flag_init "cpp/atomic/ATOMIC FLAG INIT") (C++11) | initializes an `std::atomic_flag` to `false` (macro constant) | | [C documentation](https://en.cppreference.com/w/c/atomic/atomic_flag "c/atomic/atomic flag") for `atomic_flag` |
programming_docs
cpp std::atomic_notify_one std::atomic\_notify\_one ======================== | Defined in header `[<atomic>](../header/atomic "cpp/header/atomic")` | | | | --- | --- | --- | | | | (since C++20) | | ``` template< class T > void atomic_notify_one( std::atomic<T>* object ); ``` | | | | ``` template< class T > void atomic_notify_one( volatile std::atomic<T>* object ); ``` | | | Performs atomic notifying operations. If there is a thread blocked in atomic waiting operation (i.e. `[std::atomic\_wait()](atomic_wait "cpp/atomic/atomic wait")`, `[std::atomic\_wait\_explicit()](atomic_wait "cpp/atomic/atomic wait")`, or `std::atomic::wait()`) on `*object`, then unblocks *at least* one such thread; otherwise does nothing. Equivalent to `object->notify_one()`. ### Parameters | | | | | --- | --- | --- | | object | - | pointer to the atomic object to notify | ### Return value (none). ### Notes This form of change-detection is often more efficient than simple polling or pure spinlocks. ### Example ### See also | | | | --- | --- | | [notify\_one](atomic/notify_one "cpp/atomic/atomic/notify one") (C++20) | notifies at least one thread waiting on the atomic object (public member function of `std::atomic<T>`) | | [notify\_all](atomic/notify_all "cpp/atomic/atomic/notify all") (C++20) | notifies all threads blocked waiting on the atomic object (public member function of `std::atomic<T>`) | | [atomic\_notify\_all](atomic_notify_all "cpp/atomic/atomic notify all") (C++20) | notifies all threads blocked in atomic\_wait (function template) | | [atomic\_waitatomic\_wait\_explicit](atomic_wait "cpp/atomic/atomic wait") (C++20)(C++20) | blocks the thread until notified and the atomic value changes (function template) | cpp std::atomic_ref std::atomic\_ref ================ | Defined in header `[<atomic>](../header/atomic "cpp/header/atomic")` | | | | --- | --- | --- | | ``` template< class T > struct atomic_ref; ``` | (1) | (since C++20) | | ``` template< class T > struct atomic_ref<T*>; ``` | (2) | (since C++20) | The `std::atomic_ref` class template applies atomic operations to the object it references. For the lifetime of the `atomic_ref` object, the object it references is considered an atomic object. If one thread writes to an atomic object while another thread reads from it, the behavior is well-defined (see [memory model](../language/memory_model "cpp/language/memory model") for details on data races). In addition, accesses to atomic objects may establish inter-thread synchronization and order non-atomic memory accesses as specified by `[std::memory\_order](memory_order "cpp/atomic/memory order")`. The lifetime of an object must exceed the lifetime of all `atomic_ref`s that references the object. While any `atomic_ref` instances referencing an object exists, the object must be exclusively accessed through these `atomic_ref` instances. No subobject of an object referenced by an `atomic_ref` object may be concurrently referenced by any other `atomic_ref` object. Atomic operations applied to an object through an `atomic_ref` are atomic with respect to atomic operations applied through any other `atomic_ref` referencing the same object. `std::atomic_ref` is [CopyConstructible](../named_req/copyconstructible "cpp/named req/CopyConstructible"). Like language references, constness is shallow for `atomic_ref` - it is possible to modify the referenced value through a `const` `atomic_ref` object. ### Specializations #### Primary template The primary `std::atomic_ref` template may be instantiated with any [TriviallyCopyable](../named_req/triviallycopyable "cpp/named req/TriviallyCopyable") type `T` (including `bool`): ``` struct Counters { int a; int b; } counter; // user-defined trivially-copyable type std::atomic_ref<Counters> cnt(counter); // specialization for the user-defined type ``` #### Partial specialization for pointer types The standard library provides partial specializations of the `std::atomic_ref` template for all pointer types. In addition to the operations provided for all atomic types, these specializations additionally support atomic arithmetic operations appropriate to pointer types, such as [`fetch_add`](atomic_ref/fetch_add "cpp/atomic/atomic ref/fetch add"), [`fetch_sub`](atomic_ref/fetch_sub "cpp/atomic/atomic ref/fetch sub"). #### Specializations for integral types When instantiated with one of the following integral types, `std::atomic_ref` provides additional atomic operations appropriate to integral types such as [`fetch_add`](atomic_ref/fetch_add "cpp/atomic/atomic ref/fetch add"), [`fetch_sub`](atomic_ref/fetch_sub "cpp/atomic/atomic ref/fetch sub"), [`fetch_and`](atomic_ref/fetch_and "cpp/atomic/atomic ref/fetch and"), [`fetch_or`](atomic_ref/fetch_or "cpp/atomic/atomic ref/fetch or"), [`fetch_xor`](atomic_ref/fetch_xor "cpp/atomic/atomic ref/fetch xor"): * The character types `char`, `char8_t`, `char16_t`, `char32_t`, and `wchar_t`; * The standard signed integer types: `signed char`, `short`, `int`, `long`, and `long long`; * The standard unsigned integer types: `unsigned char`, `unsigned short`, `unsigned int`, `unsigned long`, and `unsigned long long`; * Any additional integral types needed by the typedefs in the header [`<cstdint>`](../header/cstdint "cpp/header/cstdint"). Signed integer arithmetic is defined to use two's complement; there are no undefined results. #### Specializations for floating-point types When instantiated with one of the floating-point types `float`, `double`, and `long double`, `std::atomic_ref` provides additional atomic operations appropriate to floating-point types such as [`fetch_add`](atomic_ref/fetch_add "cpp/atomic/atomic ref/fetch add") and [`fetch_sub`](atomic_ref/fetch_sub "cpp/atomic/atomic ref/fetch sub"). No operations result in undefined behavior even if the result is not representable in the floating-point type. The [floating-point environment](../numeric/fenv "cpp/numeric/fenv") in effect may be different from the calling thread's floating-point environment. ### Member types | Member type | Definition | | --- | --- | | `value_type` | *see below* | | `difference_type` | `value_type` (only for `atomic_ref<*Integral*>` and `atomic_ref<*Floating*>` specializations) `[std::ptrdiff\_t](../types/ptrdiff_t "cpp/types/ptrdiff t")` (only for `atomic_ref<T*>` specializations) | For every `std::atomic_ref<X>` (whether or not specialized), `std::atomic_ref<X>::value_type` is `X`. `difference_type` is not defined in the primary `atomic_ref` template. ### Member functions | | | | --- | --- | | [(constructor)](atomic_ref/atomic_ref "cpp/atomic/atomic ref/atomic ref") | constructs an `atomic_ref` object (public member function) | | [operator=](atomic_ref/operator= "cpp/atomic/atomic ref/operator=") | stores a value into the object referenced by an `atomic_ref` object (public member function) | | [is\_lock\_free](atomic_ref/is_lock_free "cpp/atomic/atomic ref/is lock free") | checks if the `atomic_ref` object is lock-free (public member function) | | [store](atomic_ref/store "cpp/atomic/atomic ref/store") | atomically replaces the value of the referenced object with a non-atomic argument (public member function) | | [load](atomic_ref/load "cpp/atomic/atomic ref/load") | atomically obtains the value of the referenced object (public member function) | | [operator T](atomic_ref/operator_t "cpp/atomic/atomic ref/operator T") | loads a value from the referenced object (public member function) | | [exchange](atomic_ref/exchange "cpp/atomic/atomic ref/exchange") | atomically replaces the value of the referenced object and obtains the value held previously (public member function) | | [compare\_exchange\_weakcompare\_exchange\_strong](atomic_ref/compare_exchange "cpp/atomic/atomic ref/compare exchange") | atomically compares the value of the referenced object with non-atomic argument and performs atomic exchange if equal or atomic load if not (public member function) | | [wait](atomic_ref/wait "cpp/atomic/atomic ref/wait") (C++20) | blocks the thread until notified and the atomic value changes (public member function) | | [notify\_one](atomic_ref/notify_one "cpp/atomic/atomic ref/notify one") (C++20) | notifies at least one thread waiting on the atomic object (public member function) | | [notify\_all](atomic_ref/notify_all "cpp/atomic/atomic ref/notify all") (C++20) | notifies all threads blocked waiting on the atomic object (public member function) | | Constants | | [is\_always\_lock\_free](atomic_ref/is_always_lock_free "cpp/atomic/atomic ref/is always lock free") [static] | indicates that the type is always lock-free (public static member constant) | | [required\_alignment](atomic_ref/required_alignment "cpp/atomic/atomic ref/required alignment") [static] | indicates the required alignment of an object to be referenced by `atomic_ref` (public static member constant) | ### Specialized member functions | | | | --- | --- | | [fetch\_add](atomic_ref/fetch_add "cpp/atomic/atomic ref/fetch add") | atomically adds the argument to the value stored in the referenced object and obtains the value held previously (public member function) | | [fetch\_sub](atomic_ref/fetch_sub "cpp/atomic/atomic ref/fetch sub") | atomically subtracts the argument from the value stored in the referenced object and obtains the value held previously (public member function) | | [fetch\_and](atomic_ref/fetch_and "cpp/atomic/atomic ref/fetch and") | atomically performs bitwise AND between the argument and the value of the referenced object and obtains the value held previously (public member function) | | [fetch\_or](atomic_ref/fetch_or "cpp/atomic/atomic ref/fetch or") | atomically performs bitwise OR between the argument and the value of the referenced object and obtains the value held previously (public member function) | | [fetch\_xor](atomic_ref/fetch_xor "cpp/atomic/atomic ref/fetch xor") | atomically performs bitwise XOR between the argument and the value of the referenced object and obtains the value held previously (public member function) | | [operator++operator++(int)operator--operator--(int)](atomic_ref/operator_arith "cpp/atomic/atomic ref/operator arith") | atomically increments or decrements the referenced object by one (public member function) | | [operator+=operator-=operator&=operator|=operator^=](atomic_ref/operator_arith2 "cpp/atomic/atomic ref/operator arith2") | atomically adds, subtracts, or performs bitwise AND, OR, XOR with the referenced value (public member function) | ### Notes | [Feature-test](../utility/feature_test "cpp/utility/feature test") macro | | --- | | [`__cpp_lib_atomic_ref`](../feature_test#Library_features "cpp/feature test") | ### See also | | | | --- | --- | | [atomic](atomic "cpp/atomic/atomic") (C++11) | atomic class template and specializations for bool, integral, and pointer types (class template) | cpp std::atomic_init std::atomic\_init ================= | Defined in header `[<atomic>](../header/atomic "cpp/header/atomic")` | | | | --- | --- | --- | | ``` template< class T > void atomic_init( std::atomic<T>* obj, typename std::atomic<T>::value_type desired ) noexcept; ``` | | (since C++11) (deprecated in C++20) | | ``` template< class T > void atomic_init( volatile std::atomic<T>* obj, typename std::atomic<T>::value_type desired ) noexcept; ``` | | (since C++11) (deprecated in C++20) | Initializes the default-constructed atomic object `obj` with the value `desired`. The function is not atomic: concurrent access from another thread, even through an atomic operation, is a data race. If `obj` was not default-constructed, the behavior is undefined. If this function is called twice on the same `obj`, the behavior is undefined. ### Parameters | | | | | --- | --- | --- | | obj | - | pointer to an atomic object to initialize | | desired | - | the value to initialize atomic object with | ### Return value (none). ### Notes This function is provided for compatibility with C. If the compatibility is not required, `[std::atomic](atomic "cpp/atomic/atomic")` may be initialized through their non-default constructors. ### Example ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [P0558R1](https://wg21.link/P0558R1) | C++11 | exact type match required because `T` is deduced from multiple arguments | `T` is deduced from the `atomic` argument only | ### See also | | | | --- | --- | | [ATOMIC\_VAR\_INIT](atomic_var_init "cpp/atomic/ATOMIC VAR INIT") (C++11)(deprecated in C++20) | constant initialization of an atomic variable of static storage duration (function macro) | | [(constructor)](atomic/atomic "cpp/atomic/atomic/atomic") | constructs an atomic object (public member function of `std::atomic<T>`) | | [C documentation](https://en.cppreference.com/w/c/atomic/atomic_init "c/atomic/atomic init") for `atomic_init` | cpp std::atomic_load, std::atomic_load_explicit std::atomic\_load, std::atomic\_load\_explicit ============================================== | Defined in header `[<atomic>](../header/atomic "cpp/header/atomic")` | | | | --- | --- | --- | | | (1) | (since C++11) | | ``` template< class T > T atomic_load( const std::atomic<T>* obj ) noexcept; ``` | | | ``` template< class T > T atomic_load( const volatile std::atomic<T>* obj ) noexcept; ``` | | | | (2) | (since C++11) | | ``` template< class T > T atomic_load_explicit( const std::atomic<T>* obj, std::memory_order order ) noexcept; ``` | | | ``` template< class T > T atomic_load_explicit( const volatile std::atomic<T>* obj, std::memory_order order ) noexcept; ``` | | 1) Atomically obtains the value pointed to by `obj` as if by `obj->load()` 2) Atomically obtains the value pointed to by `obj` as if by `obj->load(order)` ### Parameters | | | | | --- | --- | --- | | obj | - | pointer to the atomic object to modify | | order | - | the memory synchronization ordering for this operation: only `[std::memory\_order\_relaxed](memory_order "cpp/atomic/memory order")`, `[std::memory\_order\_consume](memory_order "cpp/atomic/memory order")`, `[std::memory\_order\_acquire](memory_order "cpp/atomic/memory order")` and `[std::memory\_order\_seq\_cst](memory_order "cpp/atomic/memory order")` are permitted. | ### Return value The value that is held by the atomic object pointed to by `obj`. ### See also | | | | --- | --- | | [load](atomic/load "cpp/atomic/atomic/load") | atomically obtains the value of the atomic object (public member function of `std::atomic<T>`) | | [atomic\_storeatomic\_store\_explicit](atomic_store "cpp/atomic/atomic store") (C++11)(C++11) | atomically replaces the value of the atomic object with a non-atomic argument (function template) | | [memory\_order](memory_order "cpp/atomic/memory order") (C++11) | defines memory ordering constraints for the given atomic operation (enum) | | | | | --- | --- | | [std::atomic\_load(std::shared\_ptr) std::atomic\_load\_explicit(std::shared\_ptr)](../memory/shared_ptr/atomic "cpp/memory/shared ptr/atomic") (deprecated in C++20) | specializes atomic operations for std::shared\_ptr (function template) | | [C documentation](https://en.cppreference.com/w/c/atomic/atomic_load "c/atomic/atomic load") for `atomic_load, atomic_load_explicit` | cpp std::memory_order std::memory\_order ================== | Defined in header `[<atomic>](../header/atomic "cpp/header/atomic")` | | | | --- | --- | --- | | ``` typedef enum memory_order { memory_order_relaxed, memory_order_consume, memory_order_acquire, memory_order_release, memory_order_acq_rel, memory_order_seq_cst } memory_order; ``` | | (since C++11) (until C++20) | | ``` enum class memory_order : /*unspecified*/ { relaxed, consume, acquire, release, acq_rel, seq_cst }; inline constexpr memory_order memory_order_relaxed = memory_order::relaxed; inline constexpr memory_order memory_order_consume = memory_order::consume; inline constexpr memory_order memory_order_acquire = memory_order::acquire; inline constexpr memory_order memory_order_release = memory_order::release; inline constexpr memory_order memory_order_acq_rel = memory_order::acq_rel; inline constexpr memory_order memory_order_seq_cst = memory_order::seq_cst; ``` | | (since C++20) | `std::memory_order` specifies how memory accesses, including regular, non-atomic memory accesses, are to be ordered around an atomic operation. Absent any constraints on a multi-core system, when multiple threads simultaneously read and write to several variables, one thread can observe the values change in an order different from the order another thread wrote them. Indeed, the apparent order of changes can even differ among multiple reader threads. Some similar effects can occur even on uniprocessor systems due to compiler transformations allowed by the memory model. The default behavior of all atomic operations in the library provides for *sequentially consistent ordering* (see discussion below). That default can hurt performance, but the library's atomic operations can be given an additional `std::memory_order` argument to specify the exact constraints, beyond atomicity, that the compiler and processor must enforce for that operation. ### Constants | Defined in header `[<atomic>](../header/atomic "cpp/header/atomic")` | | --- | | Value | Explanation | | `memory_order_relaxed` | Relaxed operation: there are no synchronization or ordering constraints imposed on other reads or writes, only this operation's atomicity is guaranteed (see [Relaxed ordering](#Relaxed_ordering) below) | | `memory_order_consume` | A load operation with this memory order performs a *consume operation* on the affected memory location: no reads or writes in the current thread dependent on the value currently loaded can be reordered before this load. Writes to data-dependent variables in other threads that release the same atomic variable are visible in the current thread. On most platforms, this affects compiler optimizations only (see [Release-Consume ordering](#Release-Consume_ordering) below) | | `memory_order_acquire` | A load operation with this memory order performs the *acquire operation* on the affected memory location: no reads or writes in the current thread can be reordered before this load. All writes in other threads that release the same atomic variable are visible in the current thread (see [Release-Acquire ordering](#Release-Acquire_ordering) below) | | `memory_order_release` | A store operation with this memory order performs the *release operation*: no reads or writes in the current thread can be reordered after this store. All writes in the current thread are visible in other threads that acquire the same atomic variable (see [Release-Acquire ordering](#Release-Acquire_ordering) below) and writes that carry a dependency into the atomic variable become visible in other threads that consume the same atomic (see [Release-Consume ordering](#Release-Consume_ordering) below). | | `memory_order_acq_rel` | A read-modify-write operation with this memory order is both an *acquire operation* and a *release operation*. No memory reads or writes in the current thread can be reordered before the load, nor after the store. All writes in other threads that release the same atomic variable are visible before the modification and the modification is visible in other threads that acquire the same atomic variable. | | `memory_order_seq_cst` | A load operation with this memory order performs an *acquire operation*, a store performs a *release operation*, and read-modify-write performs both an *acquire operation* and a *release operation*, plus a single total order exists in which all threads observe all modifications in the same order (see [Sequentially-consistent ordering](#Sequentially-consistent_ordering) below) | ### Formal description Inter-thread synchronization and memory ordering determine how *evaluations* and *side effects* of expressions are ordered between different threads of execution. They are defined in the following terms: #### Sequenced-before Within the same thread, evaluation A may be *sequenced-before* evaluation B, as described in [evaluation order](../language/eval_order "cpp/language/eval order"). #### Carries dependency Within the same thread, evaluation A that is *sequenced-before* evaluation B may also carry a dependency into B (that is, B depends on A), if any of the following is true. 1) The value of A is used as an operand of B, **except** a) if B is a call to `[std::kill\_dependency](kill_dependency "cpp/atomic/kill dependency")` b) if A is the left operand of the built-in `&&`, `||`, `?:`, or `,` operators. 2) A writes to a scalar object M, B reads from M 3) A carries dependency into another evaluation X, and X carries dependency into B #### Modification order All modifications to any particular atomic variable occur in a total order that is specific to this one atomic variable. The following four requirements are guaranteed for all atomic operations: 1) **Write-write coherence**: If evaluation A that modifies some atomic M (a write) *happens-before* evaluation B that modifies M, then A appears earlier than B in the *modification order* of M 2) **Read-read coherence**: if a value computation A of some atomic M (a read) *happens-before* a value computation B on M, and if the value of A comes from a write X on M, then the value of B is either the value stored by X, or the value stored by a side effect Y on M that appears later than X in the *modification order* of M. 3) **Read-write coherence**: if a value computation A of some atomic M (a read) *happens-before* an operation B on M (a write), then the value of A comes from a side-effect (a write) X that appears earlier than B in the *modification order* of M 4) **Write-read coherence**: if a side effect (a write) X on an atomic object M *happens-before* a value computation (a read) B of M, then the evaluation B shall take its value from X or from a side effect Y that follows X in the modification order of M #### Release sequence After a *release operation* A is performed on an atomic object M, the longest continuous subsequence of the modification order of M that consists of. | | | | --- | --- | | 1) Writes performed by the same thread that performed A | (until C++20) | 2) Atomic read-modify-write operations made to M by any thread is known as *release sequence headed by A*. #### Dependency-ordered before Between threads, evaluation A is *dependency-ordered before* evaluation B if any of the following is true. 1) A performs a *release operation* on some atomic M, and, in a different thread, B performs a *consume operation* on the same atomic M, and B reads a value written by any part of the release sequence headed (until C++20) by A. 2) A is dependency-ordered before X and X carries a dependency into B. #### Inter-thread happens-before Between threads, evaluation A *inter-thread happens before* evaluation B if any of the following is true. 1) A *synchronizes-with* B 2) A is *dependency-ordered before* B 3) A *synchronizes-with* some evaluation X, and X is *sequenced-before* B 4) A is *sequenced-before* some evaluation X, and X *inter-thread happens-before* B 5) A *inter-thread happens-before* some evaluation X, and X *inter-thread happens-before* B #### Happens-before Regardless of threads, evaluation A *happens-before* evaluation B if any of the following is true: 1) A is *sequenced-before* B 2) A *inter-thread happens before* B The implementation is required to ensure that the *happens-before* relation is acyclic, by introducing additional synchronization if necessary (it can only be necessary if a consume operation is involved, see [Batty et al](http://www.cl.cam.ac.uk/~pes20/cpp/popl085ap-sewell.pdf)). If one evaluation modifies a memory location, and the other reads or modifies the same memory location, and if at least one of the evaluations is not an atomic operation, the behavior of the program is undefined (the program has a [data race](../language/memory_model "cpp/language/memory model")) unless there exists a *happens-before* relationship between these two evaluations. | | | | --- | --- | | Simply happens-before Regardless of threads, evaluation A *simply happens-before* evaluation B if any of the following is true: 1) A is *sequenced-before* B 2) A *synchronizes-with* B 3) A *simply happens-before* X, and X *simply happens-before* B Note: without consume operations, *simply happens-before* and *happens-before* relations are the same. | (since C++20) | #### Strongly happens-before Regardless of threads, evaluation A *strongly happens-before* evaluation B if any of the following is true: | | | | --- | --- | | 1) A is *sequenced-before* B 2) A *synchronizes-with* B 3) A *strongly happens-before* X, and X *strongly happens-before* B | (until C++20) | | 1) A is *sequenced-before* B 2) A *synchronizes with* B, and both A and B are sequentially consistent atomic operations 3) A is *sequenced-before* X, X *simply happens-before* Y, and Y is *sequenced-before* B 4) A *strongly happens-before* X, and X *strongly happens-before* B Note: informally, if A *strongly happens-before* B, then A appears to be evaluated before B in all contexts. Note: *strongly happens-before* excludes consume operations. | (since C++20) | #### Visible side-effects The side-effect A on a scalar M (a write) is *visible* with respect to value computation B on M (a read) if both of the following are true: 1) A *happens-before* B 2) There is no other side effect X to M where A *happens-before* X and X *happens-before* B If side-effect A is visible with respect to the value computation B, then the longest contiguous subset of the side-effects to M, in *modification order*, where B does not *happen-before* it is known as the *visible sequence of side-effects*. (the value of M, determined by B, will be the value stored by one of these side effects). Note: inter-thread synchronization boils down to preventing data races (by establishing happens-before relationships) and defining which side effects become visible under what conditions. #### Consume operation Atomic load with `memory_order_consume` or stronger is a consume operation. Note that `[std::atomic\_thread\_fence](atomic_thread_fence "cpp/atomic/atomic thread fence")` imposes stronger synchronization requirements than a consume operation. #### Acquire operation Atomic load with `memory_order_acquire` or stronger is an acquire operation. The lock() operation on a [Mutex](../named_req/mutex "cpp/named req/Mutex") is also an acquire operation. Note that `[std::atomic\_thread\_fence](atomic_thread_fence "cpp/atomic/atomic thread fence")` imposes stronger synchronization requirements than an acquire operation. #### Release operation Atomic store with `memory_order_release` or stronger is a release operation. The unlock() operation on a [Mutex](../named_req/mutex "cpp/named req/Mutex") is also a release operation. Note that `[std::atomic\_thread\_fence](atomic_thread_fence "cpp/atomic/atomic thread fence")` imposes stronger synchronization requirements than a release operation. ### Explanation #### Relaxed ordering Atomic operations tagged `memory_order_relaxed` are not synchronization operations; they do not impose an order among concurrent memory accesses. They only guarantee atomicity and modification order consistency. For example, with `x` and `y` initially zero, ``` // Thread 1: r1 = y.load(std::memory_order_relaxed); // A x.store(r1, std::memory_order_relaxed); // B // Thread 2: r2 = x.load(std::memory_order_relaxed); // C y.store(42, std::memory_order_relaxed); // D ``` is allowed to produce `r1 == r2 == 42` because, although A is *sequenced-before* B within thread 1 and C is *sequenced before* D within thread 2, nothing prevents D from appearing before A in the modification order of y, and B from appearing before C in the modification order of x. The side-effect of D on y could be visible to the load A in thread 1 while the side effect of B on x could be visible to the load C in thread 2. In particular, this may occur if D is completed before C in thread 2, either due to compiler reordering or at runtime. | | | | --- | --- | | Even with relaxed memory model, out-of-thin-air values are not allowed to circularly depend on their own computations, for example, with `x` and `y` initially zero, ``` // Thread 1: r1 = y.load(std::memory_order_relaxed); if (r1 == 42) x.store(r1, std::memory_order_relaxed); // Thread 2: r2 = x.load(std::memory_order_relaxed); if (r2 == 42) y.store(42, std::memory_order_relaxed); ``` is not allowed to produce `r1 == r2 == 42` since the store of 42 to y is only possible if the store to x stores 42, which circularly depends on the store to y storing 42. Note that until C++14, this was technically allowed by the specification, but not recommended for implementors. | (since C++14) | Typical use for relaxed memory ordering is incrementing counters, such as the reference counters of `[std::shared\_ptr](../memory/shared_ptr "cpp/memory/shared ptr")`, since this only requires atomicity, but not ordering or synchronization (note that decrementing the shared\_ptr counters requires acquire-release synchronization with the destructor). ``` #include <vector> #include <iostream> #include <thread> #include <atomic> std::atomic<int> cnt = {0}; void f() { for (int n = 0; n < 1000; ++n) { cnt.fetch_add(1, std::memory_order_relaxed); } } int main() { std::vector<std::thread> v; for (int n = 0; n < 10; ++n) { v.emplace_back(f); } for (auto& t : v) { t.join(); } std::cout << "Final counter value is " << cnt << '\n'; } ``` Output: ``` Final counter value is 10000 ``` #### Release-Acquire ordering If an atomic store in thread A is tagged `memory_order_release` and an atomic load in thread B from the same variable is tagged `memory_order_acquire`, all memory writes (non-atomic and relaxed atomic) that *happened-before* the atomic store from the point of view of thread A, become *visible side-effects* in thread B. That is, once the atomic load is completed, thread B is guaranteed to see everything thread A wrote to memory. This promise only holds if B actually returns the value that A stored, or a value from later in the release sequence. The synchronization is established only between the threads *releasing* and *acquiring* the same atomic variable. Other threads can see different order of memory accesses than either or both of the synchronized threads. On strongly-ordered systems — x86, SPARC TSO, IBM mainframe, etc. — release-acquire ordering is automatic for the majority of operations. No additional CPU instructions are issued for this synchronization mode; only certain compiler optimizations are affected (e.g., the compiler is prohibited from moving non-atomic stores past the atomic store-release or performing non-atomic loads earlier than the atomic load-acquire). On weakly-ordered systems (ARM, Itanium, PowerPC), special CPU load or memory fence instructions are used. Mutual exclusion locks, such as `[std::mutex](../thread/mutex "cpp/thread/mutex")` or [atomic spinlock](atomic_flag "cpp/atomic/atomic flag"), are an example of release-acquire synchronization: when the lock is released by thread A and acquired by thread B, everything that took place in the critical section (before the release) in the context of thread A has to be visible to thread B (after the acquire) which is executing the same critical section. ``` #include <thread> #include <atomic> #include <cassert> #include <string> std::atomic<std::string*> ptr; int data; void producer() { std::string* p = new std::string("Hello"); data = 42; ptr.store(p, std::memory_order_release); } void consumer() { std::string* p2; while (!(p2 = ptr.load(std::memory_order_acquire))) ; assert(*p2 == "Hello"); // never fires assert(data == 42); // never fires } int main() { std::thread t1(producer); std::thread t2(consumer); t1.join(); t2.join(); } ``` The following example demonstrates transitive release-acquire ordering across three threads, using a release sequence. ``` #include <thread> #include <atomic> #include <cassert> #include <vector> std::vector<int> data; std::atomic<int> flag = {0}; void thread_1() { data.push_back(42); flag.store(1, std::memory_order_release); } void thread_2() { int expected=1; // memory_order_relaxed is okay because this is an RMW, // and RMWs (with any ordering) following a release form a release sequence while (!flag.compare_exchange_strong(expected, 2, std::memory_order_relaxed)) { expected = 1; } } void thread_3() { while (flag.load(std::memory_order_acquire) < 2) ; // if we read the value 2 from the atomic flag, we see 42 in the vector assert(data.at(0) == 42); // will never fire } int main() { std::thread a(thread_1); std::thread b(thread_2); std::thread c(thread_3); a.join(); b.join(); c.join(); } ``` #### Release-Consume ordering If an atomic store in thread A is tagged `memory_order_release` and an atomic load in thread B from the same variable that read the stored value is tagged `memory_order_consume`, all memory writes (non-atomic and relaxed atomic) that *happened-before* the atomic store from the point of view of thread A, become *visible side-effects* within those operations in thread B into which the load operation *carries dependency*, that is, once the atomic load is completed, those operators and functions in thread B that use the value obtained from the load are guaranteed to see what thread A wrote to memory. The synchronization is established only between the threads *releasing* and *consuming* the same atomic variable. Other threads can see different order of memory accesses than either or both of the synchronized threads. On all mainstream CPUs other than DEC Alpha, dependency ordering is automatic, no additional CPU instructions are issued for this synchronization mode, only certain compiler optimizations are affected (e.g. the compiler is prohibited from performing speculative loads on the objects that are involved in the dependency chain). Typical use cases for this ordering involve read access to rarely written concurrent data structures (routing tables, configuration, security policies, firewall rules, etc) and publisher-subscriber situations with pointer-mediated publication, that is, when the producer publishes a pointer through which the consumer can access information: there is no need to make everything else the producer wrote to memory visible to the consumer (which may be an expensive operation on weakly-ordered architectures). An example of such scenario is [rcu\_dereference](https://en.wikipedia.org/wiki/Read-copy-update "enwiki:Read-copy-update"). See also `[std::kill\_dependency](kill_dependency "cpp/atomic/kill dependency")` and `[[[carries\_dependency](../language/attributes/carries_dependency "cpp/language/attributes/carries dependency")]]` for fine-grained dependency chain control. Note that currently (2/2015) no known production compilers track dependency chains: consume operations are lifted to acquire operations. | | | | --- | --- | | The specification of release-consume ordering is being revised, and the use of `memory_order_consume` is temporarily discouraged. | (since C++17) | This example demonstrates dependency-ordered synchronization for pointer-mediated publication: the integer data is not related to the pointer to string by a data-dependency relationship, thus its value is undefined in the consumer. ``` #include <thread> #include <atomic> #include <cassert> #include <string> std::atomic<std::string*> ptr; int data; void producer() { std::string* p = new std::string("Hello"); data = 42; ptr.store(p, std::memory_order_release); } void consumer() { std::string* p2; while (!(p2 = ptr.load(std::memory_order_consume))) ; assert(*p2 == "Hello"); // never fires: *p2 carries dependency from ptr assert(data == 42); // may or may not fire: data does not carry dependency from ptr } int main() { std::thread t1(producer); std::thread t2(consumer); t1.join(); t2.join(); } ``` #### Sequentially-consistent ordering Atomic operations tagged `memory_order_seq_cst` not only order memory the same way as release/acquire ordering (everything that *happened-before* a store in one thread becomes a *visible side effect* in the thread that did a load), but also establish a *single total modification order* of all atomic operations that are so tagged. | | | | --- | --- | | Formally, Each `memory_order_seq_cst` operation B that loads from atomic variable M, observes one of the following:* the result of the last operation A that modified M, which appears before B in the single total order * OR, if there was such an A, B may observe the result of some modification on M that is not `memory_order_seq_cst` and does not *happen-before* A * OR, if there wasn't such an A, B may observe the result of some unrelated modification of M that is not `memory_order_seq_cst` If there was a `memory_order_seq_cst` `[std::atomic\_thread\_fence](atomic_thread_fence "cpp/atomic/atomic thread fence")` operation X *sequenced-before* B, then B observes one of the following:* the last `memory_order_seq_cst` modification of M that appears before X in the single total order * some unrelated modification of M that appears later in M's modification order For a pair of atomic operations on M called A and B, where A writes and B reads M's value, if there are two `memory_order_seq_cst` `[std::atomic\_thread\_fence](atomic_thread_fence "cpp/atomic/atomic thread fence")`s X and Y, and if A is *sequenced-before* X, Y is *sequenced-before* B, and X appears before Y in the Single Total Order, then B observes either:* the effect of A * some unrelated modification of M that appears after A in M's modification order For a pair of atomic modifications of M called A and B, B occurs after A in M's modification order if.* there is a `memory_order_seq_cst` `[std::atomic\_thread\_fence](atomic_thread_fence "cpp/atomic/atomic thread fence")` X such that A is *sequenced-before* X and X appears before B in the Single Total Order * or, there is a `memory_order_seq_cst` `[std::atomic\_thread\_fence](atomic_thread_fence "cpp/atomic/atomic thread fence")` Y such that Y is *sequenced-before* B and A appears before Y in the Single Total Order * or, there are `memory_order_seq_cst` `[std::atomic\_thread\_fence](atomic_thread_fence "cpp/atomic/atomic thread fence")`s X and Y such that A is *sequenced-before* X, Y is *sequenced-before* B, and X appears before Y in the Single Total Order. Note that this means that: 1) as soon as atomic operations that are not tagged `memory_order_seq_cst` enter the picture, the sequential consistency is lost 2) the sequentially-consistent fences are only establishing total ordering for the fences themselves, not for the atomic operations in the general case (*sequenced-before* is not a cross-thread relationship, unlike *happens-before*) | (until C++20) | | Formally, An atomic operation A on some atomic object M is *coherence-ordered-before* another atomic operation B on M if any of the following is true: 1) A is a modification, and B reads the value stored by A 2) A precedes B in the *modification order* of M 3) A reads the value stored by an atomic modification X, X precedes B in the *modification order*, and A and B are not the same atomic read-modify-write operation 4) A is *coherence-ordered-before* X, and X is *coherence-ordered-before* B There is a single total order S on all `memory_order_seq_cst` operations, including fences, that satisfies the following constraints: 1) if A and B are `memory_order_seq_cst` operations, and A *strongly happens-before* B, then A precedes B in S 2) for every pair of atomic operations A and B on an object M, where A is *coherence-ordered-before* B: a) if A and B are both `memory_order_seq_cst` operations, then A precedes B in S b) if A is a `memory_order_seq_cst` operation, and B *happens-before* a `memory_order_seq_cst` fence Y, then A precedes Y in S c) if a `memory_order_seq_cst` fence X *happens-before* A, and B is a `memory_order_seq_cst` operation, then X precedes B in S d) if a `memory_order_seq_cst` fence X *happens-before* A, and B *happens-before* a `memory_order_seq_cst` fence Y, then X precedes Y in S The formal definition ensures that: 1) the single total order is consistent with the *modification order* of any atomic object 2) a `memory_order_seq_cst` load gets its value either from the last `memory_order_seq_cst` modification, or from some non-`memory_order_seq_cst` modification that does not *happen-before* preceding `memory_order_seq_cst` modifications The single total order might not be consistent with *happens-before*. This allows more efficient implementation of `memory_order_acquire` and `memory_order_release` on some CPUs. It can produce surprising results when `memory_order_acquire` and `memory_order_release` are mixed with `memory_order_seq_cst`. For example, with `x` and `y` initially zero, ``` // Thread 1: x.store(1, std::memory_order_seq_cst); // A y.store(1, std::memory_order_release); // B // Thread 2: r1 = y.fetch_add(1, std::memory_order_seq_cst); // C r2 = y.load(std::memory_order_relaxed); // D // Thread 3: y.store(3, std::memory_order_seq_cst); // E r3 = x.load(std::memory_order_seq_cst); // F ``` is allowed to produce `r1 == 1 && r2 == 3 && r3 == 0`, where A *happens-before* C, but C precedes A in the single total order C-E-F-A of `memory_order_seq_cst` (see [Lahav et al](https://plv.mpi-sws.org/scfix/paper.pdf)). Note that: 1) as soon as atomic operations that are not tagged `memory_order_seq_cst` enter the picture, the sequential consistency guarantee for the program is lost 2) in many cases, `memory_order_seq_cst` atomic operations are reorderable with respect to other atomic operations performed by the same thread | (since C++20) | Sequential ordering may be necessary for multiple producer-multiple consumer situations where all consumers must observe the actions of all producers occurring in the same order. Total sequential ordering requires a full memory fence CPU instruction on all multi-core systems. This may become a performance bottleneck since it forces the affected memory accesses to propagate to every core. This example demonstrates a situation where sequential ordering is necessary. Any other ordering may trigger the assert because it would be possible for the threads `c` and `d` to observe changes to the atomics `x` and `y` in opposite order. ``` #include <thread> #include <atomic> #include <cassert> std::atomic<bool> x = {false}; std::atomic<bool> y = {false}; std::atomic<int> z = {0}; void write_x() { x.store(true, std::memory_order_seq_cst); } void write_y() { y.store(true, std::memory_order_seq_cst); } void read_x_then_y() { while (!x.load(std::memory_order_seq_cst)) ; if (y.load(std::memory_order_seq_cst)) { ++z; } } void read_y_then_x() { while (!y.load(std::memory_order_seq_cst)) ; if (x.load(std::memory_order_seq_cst)) { ++z; } } int main() { std::thread a(write_x); std::thread b(write_y); std::thread c(read_x_then_y); std::thread d(read_y_then_x); a.join(); b.join(); c.join(); d.join(); assert(z.load() != 0); // will never happen } ``` ### Relationship with `volatile` Within a thread of execution, accesses (reads and writes) through [volatile glvalues](../language/cv "cpp/language/cv") cannot be reordered past observable side-effects (including other volatile accesses) that are *sequenced-before* or *sequenced-after* within the same thread, but this order is not guaranteed to be observed by another thread, since volatile access does not establish inter-thread synchronization. In addition, volatile accesses are not atomic (concurrent read and write is a [data race](../language/memory_model "cpp/language/memory model")) and do not order memory (non-volatile memory accesses may be freely reordered around the volatile access). One notable exception is Visual Studio, where, with default settings, every volatile write has release semantics and every volatile read has acquire semantics ([Microsoft Docs](https://docs.microsoft.com/en-us/cpp/cpp/volatile-cpp)), and thus volatiles may be used for inter-thread synchronization. Standard `volatile` semantics are not applicable to multithreaded programming, although they are sufficient for e.g. communication with a `[std::signal](../utility/program/signal "cpp/utility/program/signal")` handler that runs in the same thread when applied to `sig_atomic_t` variables. ### See also | | | --- | | [C documentation](https://en.cppreference.com/w/c/atomic/memory_order "c/atomic/memory order") for memory order | ### External links * [MOESI protocol](https://en.wikipedia.org/wiki/MOESI_protocol "enwiki:MOESI protocol") * [x86-TSO: A Rigorous and Usable Programmer’s Model for x86 Multiprocessors](http://www.cl.cam.ac.uk/~pes20/weakmemory/cacm.pdf) P. Sewell et. al., 2010 * [A Tutorial Introduction to the ARM and POWER Relaxed Memory Models](http://www.cl.cam.ac.uk/~pes20/ppc-supplemental/test7.pdf) P. Sewell et al, 2012 * [MESIF: A Two-Hop Cache Coherency Protocol for Point-to-Point Interconnects](https://researchspace.auckland.ac.nz/bitstream/handle/2292/11594/MESIF-2009.pdf?sequence=6) J.R. Goodman, H.H.J. Hum, 2009
programming_docs
cpp std::atomic_flag_wait, std::atomic_flag_wait_explicit std::atomic\_flag\_wait, std::atomic\_flag\_wait\_explicit ========================================================== | Defined in header `[<atomic>](../header/atomic "cpp/header/atomic")` | | | | --- | --- | --- | | | (1) | (since C++20) | | ``` void atomic_flag_wait( const atomic_flag* object, bool old ) noexcept; ``` | | | ``` void atomic_flag_wait( const volatile atomic_flag* object, bool old ) noexcept; ``` | | | | (2) | (since C++20) | | ``` void atomic_flag_wait_explicit( const atomic_flag* object, bool old, std::memory_order order ) noexcept; ``` | | | ``` void atomic_flag_wait_explicit( const volatile atomic_flag* object, bool old, std::memory_order order ) noexcept; ``` | | Performs atomic waiting operations. Compares `object->test([std::memory\_order\_seq\_cst](http://en.cppreference.com/w/cpp/atomic/memory_order))` or `object->test(order)` with `old`, and if they are equal then blocks until `*object` is notified by `std::atomic_flag::notify_one()` or `std::atomic_flag::notify_all()` (or the thread is unblocked spuriously). This is repeated until the values compare unequal. 1) Equivalent to `object->wait(old, [std::memory\_order\_seq\_cst](http://en.cppreference.com/w/cpp/atomic/memory_order))`. 2) Equivalent to `object->wait(old, order)`. These functions are guaranteed to return only if value has changed, even if underlying implementation unblocks spuriously. ### Parameters | | | | | --- | --- | --- | | object | - | pointer to the atomic flag to check and wait on | | old | - | the value to check the atomic flag no longer contains | | order | - | the memory synchronization ordering for this operation: must not be `std::memory_order::release` or `std::memory_order::acq_rel` | ### Return value (none). ### Notes This form of change-detection is often more efficient than simple polling or pure spinlocks. Due to the [ABA problem](https://en.wikipedia.org/wiki/ABA_problem), transient changes from `old` to another value and back to `old` might be missed, and not unblock. ### Example ### See also | | | | --- | --- | | [notify\_one](atomic_flag/notify_one "cpp/atomic/atomic flag/notify one") (C++20) | notifies at least one thread waiting on the atomic object (public member function of `std::atomic_flag`) | | [notify\_all](atomic_flag/notify_all "cpp/atomic/atomic flag/notify all") (C++20) | notifies all threads blocked waiting on the atomic object (public member function of `std::atomic_flag`) | | [atomic\_flag\_notify\_one](atomic_flag_notify_one "cpp/atomic/atomic flag notify one") (C++20) | notifies a thread blocked in atomic\_flag\_wait (function) | | [atomic\_flag\_notify\_all](atomic_flag_notify_all "cpp/atomic/atomic flag notify all") (C++20) | notifies all threads blocked in atomic\_flag\_wait (function) | cpp std::atomic_flag_test_and_set, std::atomic_flag_test_and_set_explicit std::atomic\_flag\_test\_and\_set, std::atomic\_flag\_test\_and\_set\_explicit ============================================================================== | Defined in header `[<atomic>](../header/atomic "cpp/header/atomic")` | | | | --- | --- | --- | | | (1) | (since C++11) | | ``` bool atomic_flag_test_and_set( volatile std::atomic_flag* p ) noexcept; ``` | | | ``` bool atomic_flag_test_and_set( std::atomic_flag* p ) noexcept; ``` | | | | (2) | (since C++11) | | ``` bool atomic_flag_test_and_set_explicit( volatile std::atomic_flag* p, std::memory_order order ) noexcept; ``` | | | ``` bool atomic_flag_test_and_set_explicit( std::atomic_flag* p, std::memory_order order ) noexcept; ``` | | Atomically changes the state of a `[std::atomic\_flag](atomic_flag "cpp/atomic/atomic flag")` pointed to by `p` to set (`true`) and returns the value it held before. ### Parameters | | | | | --- | --- | --- | | p | - | pointer to `[std::atomic\_flag](atomic_flag "cpp/atomic/atomic flag")` to access | | order | - | the memory synchronization order for this operation | ### Return value The value previously held by the flag pointed to by `p`. ### Possible implementation | First version | | --- | | ``` bool atomic_flag_test_and_set(volatile std::atomic_flag* p) { return p->test_and_set(); } ``` | | Second version | | ``` bool atomic_flag_test_and_set(std::atomic_flag* p) { return p->test_and_set(); } ``` | | Third version | | ``` bool atomic_flag_test_and_set_explicit(volatile std::atomic_flag* p, std::memory_order order) { return p->test_and_set(order); } ``` | | Fourth version | | ``` bool atomic_flag_test_and_set_explicit(std::atomic_flag* p, std::memory_order order) { return p->test_and_set(order); } ``` | ### Example A spinlock mutex can be implemented in userspace using an `atomic_flag`. ``` #include <thread> #include <vector> #include <iostream> #include <atomic> std::atomic_flag lock = ATOMIC_FLAG_INIT; void f(int n) { for (int cnt = 0; cnt < 100; ++cnt) { while(std::atomic_flag_test_and_set_explicit(&lock, std::memory_order_acquire)) ; // spin until the lock is acquired std::cout << "Output from thread " << n << '\n'; std::atomic_flag_clear_explicit(&lock, std::memory_order_release); } } int main() { std::vector<std::thread> v; for (int n = 0; n < 10; ++n) { v.emplace_back(f, n); } for (auto& t : v) { t.join(); } } ``` Output: ``` Output from thread 2 Output from thread 6 Output from thread 7 ...<exactly 1000 lines>... ``` ### See also | | | | --- | --- | | [atomic\_flag](atomic_flag "cpp/atomic/atomic flag") (C++11) | the lock-free boolean atomic type (class) | | [atomic\_flag\_clearatomic\_flag\_clear\_explicit](atomic_flag_clear "cpp/atomic/atomic flag clear") (C++11)(C++11) | atomically sets the value of the flag to `false` (function) | | [memory\_order](memory_order "cpp/atomic/memory order") (C++11) | defines memory ordering constraints for the given atomic operation (enum) | | [C documentation](https://en.cppreference.com/w/c/atomic/atomic_flag_test_and_set "c/atomic/atomic flag test and set") for `atomic_flag_test_and_set, atomic_flag_test_and_set_explicit` | cpp std::atomic_signal_fence std::atomic\_signal\_fence ========================== | Defined in header `[<atomic>](../header/atomic "cpp/header/atomic")` | | | | --- | --- | --- | | ``` extern "C" void atomic_signal_fence( std::memory_order order ) noexcept; ``` | | (since C++11) | Establishes memory synchronization ordering of non-atomic and relaxed atomic accesses, as instructed by `order`, between a thread and a signal handler executed on the same thread. This is equivalent to `[std::atomic\_thread\_fence](atomic_thread_fence "cpp/atomic/atomic thread fence")`, except no CPU instructions for memory ordering are issued. Only reordering of the instructions by the compiler is suppressed as `order` instructs. For example, a fence with release semantics prevents reads or writes from being moved past subsequent writes and a fence with acquire semantics prevents reads or writes from being moved ahead of preceding reads. ### Parameters | | | | | --- | --- | --- | | order | - | the memory ordering executed by this fence | ### Return value (none). ### Example ### See also | | | | --- | --- | | [memory\_order](memory_order "cpp/atomic/memory order") (C++11) | defines memory ordering constraints for the given atomic operation (enum) | | [atomic\_thread\_fence](atomic_thread_fence "cpp/atomic/atomic thread fence") (C++11) | generic memory order-dependent fence synchronization primitive (function) | | [C documentation](https://en.cppreference.com/w/c/atomic/atomic_signal_fence "c/atomic/atomic signal fence") for `atomic_signal_fence` | cpp std::atomic<T>::fetch_xor std::atomic<T>::fetch\_xor ========================== | | | | | --- | --- | --- | | | | (since C++11) (member only of `atomic<*Integral*>` template specialization) | | ``` T fetch_xor( T arg, std::memory_order order = std::memory_order_seq_cst ) noexcept; ``` | | | | ``` T fetch_xor( T arg, std::memory_order order = std::memory_order_seq_cst ) volatile noexcept; ``` | | | Atomically replaces the current value with the result of bitwise XOR of the value and `arg`. The operation is read-modify-write operation. Memory is affected according to the value of `order`. | | | | --- | --- | | The volatile-qualified version is deprecated if `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<T>::is\_always\_lock\_free` is `false`. | (since C++20) | ### Parameters | | | | | --- | --- | --- | | arg | - | the other argument of bitwise XOR | | order | - | memory order constraints to enforce | ### Return value The value immediately preceding the effects of this function in the [modification order](../memory_order#Modification_order "cpp/atomic/memory order") of `*this`. ### See also | | | | --- | --- | | [atomic\_fetch\_xoratomic\_fetch\_xor\_explicit](../atomic_fetch_xor "cpp/atomic/atomic fetch xor") (C++11)(C++11) | replaces the atomic object with the result of bitwise XOR with a non-atomic argument and obtains the previous value of the atomic (function template) | cpp std::atomic<T>::operator+=,-=,&=,|=,^= std::atomic<T>::operator+=,-=,&=,|=,^= ====================================== | | | | | --- | --- | --- | | member only of `atomic<*Integral*>`(C++11) and `atomic<*Floating*>`(C++20) template specializations | | | | | (1) | | | ``` T operator+=( T arg ) noexcept; ``` | | | ``` T operator+=( T arg ) volatile noexcept; ``` | | | member only of `atomic<T*>` template specialization | | | | | (1) | | | ``` T* operator+=( std::ptrdiff_t arg ) noexcept; ``` | | | ``` T* operator+=( std::ptrdiff_t arg ) volatile noexcept; ``` | | | member only of `atomic<*Integral*>`(C++11) and `atomic<*Floating*>`(C++20) template specializations | | | | | (2) | | | ``` T operator-=( T arg ) noexcept; ``` | | | ``` T operator-=( T arg ) volatile noexcept; ``` | | | member only of `atomic<T*>` template specialization | | | | | (2) | | | ``` T* operator-=( std::ptrdiff_t arg ) noexcept; ``` | | | ``` T* operator-=( std::ptrdiff_t arg ) volatile noexcept; ``` | | | member only of `atomic<*Integral*>` template specialization | | | | | (3) | | | ``` T operator&=( T arg ) noexcept; ``` | | | ``` T operator&=( T arg ) volatile noexcept; ``` | | | | (4) | | | ``` T operator|=( T arg ) noexcept; ``` | | | ``` T operator|=( T arg ) volatile noexcept; ``` | | | | (5) | | | ``` T operator^=( T arg ) noexcept; ``` | | | ``` T operator^=( T arg ) volatile noexcept; ``` | | Atomically replaces the current value with the result of computation involving the previous value and `arg`. The operation is read-modify-write operation. 1) Performs atomic addition. Equivalent to `fetch_add(arg)` + arg. 2) Performs atomic subtraction. Equivalent to `fetch_sub(arg)` - arg. 3) Performs atomic bitwise and. Equivalent to `fetch_and(arg)` & arg. 4) Performs atomic bitwise or. Equivalent to `fetch_or(arg)` | arg. 5) Performs atomic bitwise exclusive or. Equivalent to `fetch_xor(arg)` ^ arg. For signed `Integral` types, arithmetic is defined to use two’s complement representation. There are no undefined results. For `T*` types, the result may be an undefined address, but the operations otherwise have no undefined behavior. The program is ill-formed if `T` is not an object type. | | | | --- | --- | | For floating-point types, the [floating-point environment](../../numeric/fenv "cpp/numeric/fenv") in effect may be different from the calling thread's floating-point environment. The operation need not be conform to the corresponding `[std::numeric\_limits](../../types/numeric_limits "cpp/types/numeric limits")` traits but is encouraged to do so. If the result is not a representable value for its type, the result is unspecified but the operation otherwise has no undefined behavior. The volatile-qualified versions are deprecated if `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<T>::is\_always\_lock\_free` is `false`. | (since C++20) | ### Parameters | | | | | --- | --- | --- | | arg | - | the argument for the arithmetic operation | ### Return value The resulting value (that is, the result of applying the corresponding binary operator to the value immediately preceding the effects of the corresponding member function in the [modification order](../memory_order#Modification_order "cpp/atomic/memory order") of `*this`). ### Notes Unlike most compound assignment operators, the compound assignment operators for atomic types do not return a reference to their left-hand arguments. They return a copy of the stored value instead. ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [P0558R1](https://wg21.link/P0558R1) | C++11 | arithmetic permitted on pointers to *cv* void or function | made ill-formed | ### See also | | | | --- | --- | | [operator++operator++(int)operator--operator--(int)](operator_arith "cpp/atomic/atomic/operator arith") | increments or decrements the atomic value by one (public member function) | cpp std::atomic<T>::compare_exchange_weak, std::atomic<T>::compare_exchange_strong std::atomic<T>::compare\_exchange\_weak, std::atomic<T>::compare\_exchange\_strong ================================================================================== | | | | | --- | --- | --- | | | (1) | (since C++11) | | ``` bool compare_exchange_weak( T& expected, T desired, std::memory_order success, std::memory_order failure ) noexcept; ``` | | | ``` bool compare_exchange_weak( T& expected, T desired, std::memory_order success, std::memory_order failure ) volatile noexcept; ``` | | | | (2) | (since C++11) | | ``` bool compare_exchange_weak( T& expected, T desired, std::memory_order order = std::memory_order_seq_cst ) noexcept; ``` | | | ``` bool compare_exchange_weak( T& expected, T desired, std::memory_order order = std::memory_order_seq_cst ) volatile noexcept; ``` | | | | (3) | (since C++11) | | ``` bool compare_exchange_strong( T& expected, T desired, std::memory_order success, std::memory_order failure ) noexcept; ``` | | | ``` bool compare_exchange_strong( T& expected, T desired, std::memory_order success, std::memory_order failure ) volatile noexcept; ``` | | | | (4) | (since C++11) | | ``` bool compare_exchange_strong( T& expected, T desired, std::memory_order order = std::memory_order_seq_cst ) noexcept; ``` | | | ``` bool compare_exchange_strong( T& expected, T desired, std::memory_order order = std::memory_order_seq_cst ) volatile noexcept; ``` | | Atomically compares the [object representation](../../language/object "cpp/language/object") (until C++20)[value representation](../../language/object "cpp/language/object") (since C++20) of `*this` with that of `expected`, and if those are bitwise-equal, replaces the former with `desired` (performs read-modify-write operation). Otherwise, loads the actual value stored in `*this` into `expected` (performs load operation). The memory models for the read-modify-write and load operations are `success` and `failure` respectively. In the (2) and (4) versions `order` is used for both read-modify-write and load operations, except that `[std::memory\_order\_acquire](../memory_order "cpp/atomic/memory order")` and `[std::memory\_order\_relaxed](../memory_order "cpp/atomic/memory order")` are used for the load operation if `order == [std::memory\_order\_acq\_rel](http://en.cppreference.com/w/cpp/atomic/memory_order)`, or `order == [std::memory\_order\_release](http://en.cppreference.com/w/cpp/atomic/memory_order)` respectively. | | | | --- | --- | | The volatile-qualified versions are deprecated if `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<T>::is\_always\_lock\_free` is `false`. | (since C++20) | ### Parameters | | | | | --- | --- | --- | | expected | - | reference to the value expected to be found in the atomic object. Gets stored with the actual value of `*this` if the comparison fails. | | desired | - | the value to store in the atomic object if it is as expected | | success | - | the memory synchronization ordering for the read-modify-write operation if the comparison succeeds. All values are permitted. | | failure | - | the memory synchronization ordering for the load operation if the comparison fails. Cannot be `[std::memory\_order\_release](../memory_order "cpp/atomic/memory order")` or `[std::memory\_order\_acq\_rel](../memory_order "cpp/atomic/memory order")` and cannot specify stronger ordering than `success` (until C++17) | | order | - | the memory synchronization ordering for both operations | ### Return value `true` if the underlying atomic value was successfully changed, `false` otherwise. ### Notes The comparison and copying are bitwise (similar to `[std::memcmp](../../string/byte/memcmp "cpp/string/byte/memcmp")` and `[std::memcpy](../../string/byte/memcpy "cpp/string/byte/memcpy")`); no constructor, assignment operator, or comparison operator are used. The weak forms (1-2) of the functions are allowed to fail spuriously, that is, act as if `*this != expected` even if they are equal. When a compare-and-exchange is in a loop, the weak version will yield better performance on some platforms. When a weak compare-and-exchange would require a loop and a strong one would not, the strong one is preferable unless the object representation of `T` may include padding bits, (until C++20) trap bits, or offers multiple object representations for the same value (e.g. floating-point NaN). In those cases, weak compare-and-exchange typically works because it quickly converges on some stable object representation. For a union with bits that participate in the value representations of some members but not the others, compare-and-exchange might always fail because such padding bits have indeterminate values when they do not participate in the value representation of the active member. | | | | --- | --- | | Padding bits that never participate in an object's value representation are ignored. | (since C++20) | ### Example Compare-and-exchange operations are often used as basic building blocks of [lockfree](https://en.wikipedia.org/wiki/Non-blocking_algorithm "enwiki:Non-blocking algorithm") data structures. ``` #include <atomic> template<typename T> struct node { T data; node* next; node(const T& data) : data(data), next(nullptr) {} }; template<typename T> class stack { std::atomic<node<T>*> head; public: void push(const T& data) { node<T>* new_node = new node<T>(data); // put the current value of head into new_node->next new_node->next = head.load(std::memory_order_relaxed); // now make new_node the new head, but if the head // is no longer what's stored in new_node->next // (some other thread must have inserted a node just now) // then put that new head into new_node->next and try again while(!head.compare_exchange_weak(new_node->next, new_node, std::memory_order_release, std::memory_order_relaxed)) ; // the body of the loop is empty // Note: the above use is not thread-safe in at least // GCC prior to 4.8.3 (bug 60272), clang prior to 2014-05-05 (bug 18899) // MSVC prior to 2014-03-17 (bug 819819). The following is a workaround: // node<T>* old_head = head.load(std::memory_order_relaxed); // do { // new_node->next = old_head; // } while(!head.compare_exchange_weak(old_head, new_node, // std::memory_order_release, // std::memory_order_relaxed)); } }; int main() { stack<int> s; s.push(1); s.push(2); s.push(3); } ``` Demonstrates how compare\_exchange\_strong either changes the value of the atomic variable or the variable used for comparison. ``` #include <atomic> #include <iostream> std::atomic<int> ai; int tst_val= 4; int new_val= 5; bool exchanged= false; void valsout() { std::cout << "ai= " << ai << " tst_val= " << tst_val << " new_val= " << new_val << " exchanged= " << std::boolalpha << exchanged << "\n"; } int main() { ai= 3; valsout(); // tst_val != ai ==> tst_val is modified exchanged= ai.compare_exchange_strong( tst_val, new_val ); valsout(); // tst_val == ai ==> ai is modified exchanged= ai.compare_exchange_strong( tst_val, new_val ); valsout(); } ``` Output: ``` ai= 3 tst_val= 4 new_val= 5 exchanged= false ai= 3 tst_val= 3 new_val= 5 exchanged= false ai= 5 tst_val= 3 new_val= 5 exchanged= true ``` ### See also | | | | --- | --- | | [atomic\_compare\_exchange\_weakatomic\_compare\_exchange\_weak\_explicitatomic\_compare\_exchange\_strongatomic\_compare\_exchange\_strong\_explicit](../atomic_compare_exchange "cpp/atomic/atomic compare exchange") (C++11)(C++11)(C++11)(C++11) | atomically compares the value of the atomic object with non-atomic argument and performs atomic exchange if equal or atomic load if not (function template) |
programming_docs
cpp std::atomic<T>::load std::atomic<T>::load ==================== | | | | | --- | --- | --- | | | | (since C++11) | | ``` T load( std::memory_order order = std::memory_order_seq_cst ) const noexcept; ``` | | | | ``` T load( std::memory_order order = std::memory_order_seq_cst ) const volatile noexcept; ``` | | | Atomically loads and returns the current value of the atomic variable. Memory is affected according to the value of `order`. `order` must be one of `[std::memory\_order\_relaxed](../memory_order "cpp/atomic/memory order")`, `[std::memory\_order\_consume](../memory_order "cpp/atomic/memory order")`, `[std::memory\_order\_acquire](../memory_order "cpp/atomic/memory order")` or `[std::memory\_order\_seq\_cst](../memory_order "cpp/atomic/memory order")`. Otherwise the behavior is undefined. | | | | --- | --- | | The volatile-qualified version is deprecated if `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<T>::is\_always\_lock\_free` is `false`. | (since C++20) | ### Parameters | | | | | --- | --- | --- | | order | - | memory order constraints to enforce | ### Return value The current value of the atomic variable. ### See also | | | | --- | --- | | [operator T](operator_t "cpp/atomic/atomic/operator T") | loads a value from an atomic object (public member function) | | [atomic\_loadatomic\_load\_explicit](../atomic_load "cpp/atomic/atomic load") (C++11)(C++11) | atomically obtains the value stored in an atomic object (function template) | cpp std::atomic<T>::fetch_sub std::atomic<T>::fetch\_sub ========================== | | | | | --- | --- | --- | | member only of `atomic<*Integral*>`(C++11) and `atomic<*Floating*>`(C++20) template specializations | | | | | (1) | | | ``` T fetch_sub( T arg, std::memory_order order = std::memory_order_seq_cst ) noexcept; ``` | | | ``` T fetch_sub( T arg, std::memory_order order = std::memory_order_seq_cst ) volatile noexcept; ``` | | | member only of `atomic<T*>` template specialization | | | | | (2) | | | ``` T* fetch_sub( std::ptrdiff_t arg, std::memory_order order = std::memory_order_seq_cst ) noexcept; ``` | | | ``` T* fetch_sub( std::ptrdiff_t arg, std::memory_order order = std::memory_order_seq_cst ) volatile noexcept; ``` | | Atomically replaces the current value with the result of arithmetic subtraction of the value and `arg`. That is, it performs atomic post-decrement. The operation is read-modify-write operation. Memory is affected according to the value of `order`. For signed `Integral` types, arithmetic is defined to use two’s complement representation. There are no undefined results. For `T*` types, the result may be an undefined address, but the operation otherwise has no undefined behavior. The program is ill-formed if `T` is not an object type. | | | | --- | --- | | For floating-point types, the [floating-point environment](../../numeric/fenv "cpp/numeric/fenv") in effect may be different from the calling thread's floating-point environment. The operation need not be conform to the corresponding `[std::numeric\_limits](../../types/numeric_limits "cpp/types/numeric limits")` traits but is encouraged to do so. If the result is not a representable value for its type, the result is unspecified but the operation otherwise has no undefined behavior. The volatile-qualified versions are deprecated if `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<T>::is\_always\_lock\_free` is `false`. | (since C++20) | ### Parameters | | | | | --- | --- | --- | | arg | - | the other argument of arithmetic subtraction | | order | - | memory order constraints to enforce | ### Return value The value immediately preceding the effects of this function in the [modification order](../memory_order#Modification_order "cpp/atomic/memory order") of `*this`. ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [P0558R1](https://wg21.link/P0558R1) | C++11 | arithmetic permitted on pointers to *cv* void or function | made ill-formed | ### See also | | | | --- | --- | | [atomic\_fetch\_subatomic\_fetch\_sub\_explicit](../atomic_fetch_sub "cpp/atomic/atomic fetch sub") (C++11)(C++11) | subtracts a non-atomic value from an atomic object and obtains the previous value of the atomic (function template) | | [operator++operator++(int)operator--operator--(int)](operator_arith "cpp/atomic/atomic/operator arith") | increments or decrements the atomic value by one (public member function) | cpp std::atomic<T>::fetch_and std::atomic<T>::fetch\_and ========================== | | | | | --- | --- | --- | | | | (since C++11) (member only of `atomic<*Integral*>` template specialization) | | ``` T fetch_and( T arg, std::memory_order order = std::memory_order_seq_cst ) noexcept; ``` | | | | ``` T fetch_and( T arg, std::memory_order order = std::memory_order_seq_cst ) volatile noexcept; ``` | | | Atomically replaces the current value with the result of bitwise AND of the value and `arg`. The operation is read-modify-write operation. Memory is affected according to the value of `order`. | | | | --- | --- | | The volatile-qualified version is deprecated if `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<T>::is\_always\_lock\_free` is `false`. | (since C++20) | ### Parameters | | | | | --- | --- | --- | | arg | - | the other argument of bitwise AND | | order | - | memory order constraints to enforce | ### Return value The value immediately preceding the effects of this function in the [modification order](../memory_order#Modification_order "cpp/atomic/memory order") of `*this`. ### See also | | | | --- | --- | | [atomic\_fetch\_andatomic\_fetch\_and\_explicit](../atomic_fetch_and "cpp/atomic/atomic fetch and") (C++11)(C++11) | replaces the atomic object with the result of bitwise AND with a non-atomic argument and obtains the previous value of the atomic (function template) | cpp std::atomic<T>::is_lock_free std::atomic<T>::is\_lock\_free ============================== | | | | | --- | --- | --- | | | | (since C++11) | | ``` bool is_lock_free() const noexcept; ``` | | | | ``` bool is_lock_free() const volatile noexcept; ``` | | | Checks whether the atomic operations on all objects of this type are lock-free. ### Parameters (none). ### Return value `true` if the atomic operations on the objects of this type are lock-free, `false` otherwise. ### Notes All atomic types except for `[std::atomic\_flag](../atomic_flag "cpp/atomic/atomic flag")` may be implemented using mutexes or other locking operations, rather than using the lock-free atomic CPU instructions. Atomic types are also allowed to be *sometimes* lock-free, e.g. if only aligned memory accesses are naturally atomic on a given architecture, misaligned objects of the same type have to use locks. The C++ standard recommends (but does not require) that lock-free atomic operations are also address-free, that is, suitable for communication between processes using shared memory. ### Example ``` #include <iostream> #include <utility> #include <atomic> struct A { int a[100]; }; struct B { int x, y; }; int main() { std::cout << std::boolalpha << "std::atomic<A> is lock free? " << std::atomic<A>{}.is_lock_free() << '\n' << "std::atomic<B> is lock free? " << std::atomic<B>{}.is_lock_free() << '\n'; } ``` Possible output: ``` std::atomic<A> is lock free? false std::atomic<B> is lock free? true ``` ### See also | | | | --- | --- | | [atomic\_is\_lock\_free](../atomic_is_lock_free "cpp/atomic/atomic is lock free") (C++11) | checks if the atomic type's operations are lock-free (function template) | | [atomic\_is\_lock\_free(std::shared\_ptr)](../../memory/shared_ptr/atomic "cpp/memory/shared ptr/atomic") | specializes atomic operations for `[std::shared\_ptr](../../memory/shared_ptr "cpp/memory/shared ptr")` (function template) | | [is\_always\_lock\_free](is_always_lock_free "cpp/atomic/atomic/is always lock free") [static] (C++17) | indicates that the type is always lock-free (public static member constant) | cpp std::atomic<T>::fetch_or std::atomic<T>::fetch\_or ========================= | | | | | --- | --- | --- | | | | (since C++11) (member only of `atomic<*Integral*>` template specialization) | | ``` T fetch_or( T arg, std::memory_order order = std::memory_order_seq_cst ) noexcept; ``` | | | | ``` T fetch_or( T arg, std::memory_order order = std::memory_order_seq_cst ) volatile noexcept; ``` | | | Atomically replaces the current value with the result of bitwise OR of the value and `arg`. The operation is read-modify-write operation. Memory is affected according to the value of `order`. | | | | --- | --- | | The volatile-qualified version is deprecated if `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<T>::is\_always\_lock\_free` is `false`. | (since C++20) | ### Parameters | | | | | --- | --- | --- | | arg | - | the other argument of bitwise OR | | order | - | memory order constraints to enforce | ### Return value The value immediately preceding the effects of this function in the [modification order](../memory_order#Modification_order "cpp/atomic/memory order") of `*this`. ### See also | | | | --- | --- | | [atomic\_fetch\_oratomic\_fetch\_or\_explicit](../atomic_fetch_or "cpp/atomic/atomic fetch or") (C++11)(C++11) | replaces the atomic object with the result of bitwise OR with a non-atomic argument and obtains the previous value of the atomic (function template) | cpp std::atomic<T>::notify_one std::atomic<T>::notify\_one =========================== | | | | | --- | --- | --- | | | | (since C++20) | | ``` void notify_one() noexcept; ``` | | | | ``` void notify_one() volatile noexcept; ``` | | | Performs atomic notifying operations. If there is a thread blocked in atomic waiting operation (i.e. `wait()`) on `*this`, then unblocks *at least* one such thread; otherwise does nothing. ### Return value (none). ### Notes This form of change-detection is often more efficient than simple polling or pure spinlocks. ### Example ### See also | | | | --- | --- | | [wait](wait "cpp/atomic/atomic/wait") (C++20) | blocks the thread until notified and the atomic value changes (public member function) | | [atomic\_waitatomic\_wait\_explicit](../atomic_wait "cpp/atomic/atomic wait") (C++20)(C++20) | blocks the thread until notified and the atomic value changes (function template) | | [atomic\_notify\_one](../atomic_notify_one "cpp/atomic/atomic notify one") (C++20) | notifies a thread blocked in atomic\_wait (function template) | cpp std::atomic<T>::is_always_lock_free std::atomic<T>::is\_always\_lock\_free ====================================== | | | | | --- | --- | --- | | ``` static constexpr bool is_always_lock_free = /*implementation-defined*/; ``` | | (since C++17) | Equals `true` if this atomic type is always lock-free and `false` if it is never or sometimes lock-free. The value of this constant is consistent with both the macro `ATOMIC_xxx_LOCK_FREE`, where defined, with the member function `is_lock_free` and non-member function `[std::atomic\_is\_lock\_free](../atomic_is_lock_free "cpp/atomic/atomic is lock free")`. ### Notes There is no non-member function equivalent of this static member constant because non-member functions take pointers to atomic types, and therefore aren't as useful in [constant expressions](../../language/constant_expression "cpp/language/constant expression"). | [Feature-test](../../utility/feature_test "cpp/utility/feature test") macro | | --- | | [`__cpp_lib_atomic_is_always_lock_free`](../../feature_test#Library_features "cpp/feature test") | ### See also | | | | --- | --- | | [is\_lock\_free](is_lock_free "cpp/atomic/atomic/is lock free") | checks if the atomic object is lock-free (public member function) | | [atomic\_is\_lock\_free](../atomic_is_lock_free "cpp/atomic/atomic is lock free") (C++11) | checks if the atomic type's operations are lock-free (function template) | cpp std::atomic<T>::operator= std::atomic<T>::operator= ========================= | | | | | --- | --- | --- | | | (1) | (since C++11) | | ``` T operator=( T desired ) noexcept; ``` | | | ``` T operator=( T desired ) volatile noexcept; ``` | (since C++11) | | | (2) | (since C++11) | | ``` atomic& operator=( const atomic& ) = delete; ``` | | | ``` atomic& operator=( const atomic& ) volatile = delete; ``` | | 1) Atomically assigns the `desired` value to the atomic variable. Equivalent to `store(desired)`. The volatile-qualified version is deprecated if `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<T>::is\_always\_lock\_free` is `false`. (since C++20) 2) Atomic variables are not [CopyAssignable](../../named_req/copyassignable "cpp/named req/CopyAssignable"). ### Parameters | | | | | --- | --- | --- | | desired | - | value to assign | ### Return value `desired`. ### Notes Unlike most assignment operators, the assignment operators for atomic types do not return a reference to their left-hand arguments. They return a copy of the stored value instead. ### See also | | | | --- | --- | | [(constructor)](atomic "cpp/atomic/atomic/atomic") | constructs an atomic object (public member function) | cpp std::atomic<T>::atomic std::atomic<T>::atomic ====================== | | | | | --- | --- | --- | | | (1) | | | ``` atomic() noexcept = default; ``` | (since C++11) (until C++20) | | ``` constexpr atomic() noexcept(std::is_nothrow_default_constructible_v<T>); ``` | (since C++20) | | ``` constexpr atomic( T desired ) noexcept; ``` | (2) | (since C++11) | | ``` atomic( const atomic& ) = delete; ``` | (3) | (since C++11) | Constructs new atomic variable. | | | | --- | --- | | 1) The default constructor is trivial: no initialization takes place other than [zero initialization](../../language/zero_initialization "cpp/language/zero initialization") of static and thread-local objects. `[std::atomic\_init](../atomic_init "cpp/atomic/atomic init")` may be used to complete initialization. | (until C++20) | | 1) Value-initializes the underlying object (i.e. with `T()`). The initialization is not atomic. Use of the default constructor is ill-formed if `[std::is\_default\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_default_constructible)<T>` is `false`. | (since C++20) | 2) Initializes the underlying object with `desired`. The initialization is not atomic. 3) Atomic variables are not [CopyConstructible](../../named_req/copyconstructible "cpp/named req/CopyConstructible"). ### Parameters | | | | | --- | --- | --- | | desired | - | value to initialize with | ### Notes | | | | --- | --- | | The default-initialized `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<T>` does not contain a `T` object, and its only valid uses are destruction and initialization by `[std::atomic\_init](../atomic_init "cpp/atomic/atomic init")`, see [LWG 2334](https://cplusplus.github.io/LWG/issue2334). | (until C++20) | cpp std::atomic<T>::operator++,++(int),--,--(int) std::atomic<T>::operator++,++(int),--,--(int) ============================================= | | | | | --- | --- | --- | | ``` T operator++() noexcept; T operator++() volatile noexcept; ``` | (1) | (member only of `atomic<*Integral*>` template specialization)(since C++11) | | ``` T* operator++() noexcept; T* operator++() volatile noexcept; ``` | (1) | (member only of `atomic<T*>` template specialization)(since C++11) | | ``` T operator++( int ) noexcept; T operator++( int ) volatile noexcept; ``` | (2) | (member only of `atomic<*Integral*>` template specialization)(since C++11) | | ``` T* operator++( int ) noexcept; T* operator++( int ) volatile noexcept; ``` | (2) | (member only of `atomic<T*>` template specialization)(since C++11) | | ``` T operator--() noexcept; T operator--() volatile noexcept; ``` | (3) | (member only of `atomic<*Integral*>` template specialization)(since C++11) | | ``` T* operator--() noexcept; T* operator--() volatile noexcept; ``` | (3) | (member only of `atomic<T*>` template specialization)(since C++11) | | ``` T operator--( int ) noexcept; T operator--( int ) volatile noexcept; ``` | (4) | (member only of `atomic<*Integral*>` template specialization)(since C++11) | | ``` T* operator--( int ) noexcept; T* operator--( int ) volatile noexcept; ``` | (4) | (member only of `atomic<T*>` template specialization)(since C++11) | Atomically increments or decrements the current value. The operation is read-modify-write operation. 1) Performs atomic pre-increment. Equivalent to `fetch_add(1)+1`. 2) Performs atomic post-increment. Equivalent to `fetch_add(1)`. 3) Performs atomic pre-decrement. Equivalent to `fetch_sub(1)-1` 4) Performs atomic post-decrement. Equivalent to `fetch_sub(1)`. For signed `Integral` types, arithmetic is defined to use two’s complement representation. There are no undefined results. For `T*` types, the result may be an undefined address, but the operations otherwise have no undefined behavior. The program is ill-formed if `T` is not an object type. | | | | --- | --- | | The volatile-qualified versions are deprecated if `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<T>::is\_always\_lock\_free` is `false`. | (since C++20) | ### Parameters (none). ### Return value 1,3) The value of the atomic variable after the modification. Formally, the result of incrementing/decrementing the value immediately preceding the effects of this function in the [modification order](../memory_order#Modification_order "cpp/atomic/memory order") of `*this`. 2,4) The value of the atomic variable before the modification. Formally, the value immediately preceding the effects of this function in the [modification order](../memory_order#Modification_order "cpp/atomic/memory order") of `*this`. ### Notes Unlike most pre-increment and pre-decrement operators, the pre-increment and pre-decrement operators for atomic types do not return a reference to the modified object. They return a copy of the stored value instead. ### Example ``` #include <atomic> #include <chrono> #include <iomanip> #include <iostream> #include <mutex> #include <random> #include <thread> std::atomic<int> atomic_count{0}; std::atomic<int> atomic_writes{0}; constexpr int global_max_count{72}; constexpr int writes_per_line{8}; constexpr int max_delay{100}; template<int Max> int random_value() { static std::uniform_int_distribution<int> distr{1, Max}; static std::random_device engine; static std::mt19937 noise{engine()}; static std::mutex rand_mutex; std::lock_guard μ{rand_mutex}; return distr(noise); } int main() { auto work = [](const char id) { for (int count{}; (count = ++atomic_count) <= global_max_count;) { std::this_thread::sleep_for( std::chrono::milliseconds(random_value<max_delay>())); bool new_line{false}; if (++atomic_writes % writes_per_line == 0) { new_line = true; } // print thread `id` and `count` value { static std::mutex cout_mutex; std::lock_guard m{cout_mutex}; std::cout << "[" << id << "] " << std::setw(3) << count << " │ " << (new_line ? "\n" : "") << std::flush; } } }; std::jthread j1(work, 'A'), j2(work, 'B'), j3(work, 'C'), j4(work, 'D'); } ``` Possible output: ``` [B] 3 │ [D] 1 │ [C] 2 │ [D] 6 │ [A] 4 │ [B] 5 │ [B] 10 │ [D] 8 │ [C] 7 │ [A] 9 │ [A] 14 │ [B] 11 │ [D] 12 │ [C] 13 │ [A] 15 │ [C] 18 │ [D] 17 │ [B] 16 │ [C] 20 │ [C] 23 │ [D] 21 │ [A] 19 │ [C] 24 │ [B] 22 │ [A] 26 │ [C] 27 │ [D] 25 │ [C] 30 │ [B] 28 │ [D] 31 │ [A] 29 │ [C] 32 │ [B] 33 │ [D] 34 │ [B] 37 │ [B] 39 │ [B] 40 │ [A] 35 │ [C] 36 │ [C] 43 │ [D] 38 │ [A] 42 │ [B] 41 │ [A] 46 │ [B] 47 │ [C] 44 │ [A] 48 │ [D] 45 │ [C] 50 │ [D] 52 │ [B] 49 │ [D] 54 │ [C] 53 │ [A] 51 │ [B] 55 │ [D] 56 │ [D] 60 │ [A] 58 │ [C] 57 │ [D] 61 │ [C] 63 │ [B] 59 │ [D] 64 │ [C] 65 │ [A] 62 │ [D] 67 │ [B] 66 │ [C] 68 │ [D] 70 │ [C] 72 │ [B] 71 │ [A] 69 │ ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [P0558R1](https://wg21.link/P0558R1) | C++11 | arithmetic permitted on pointers to *cv* void or function | made ill-formed | ### See also | | | | --- | --- | | [fetch\_add](fetch_add "cpp/atomic/atomic/fetch add") | atomically adds the argument to the value stored in the atomic object and obtains the value held previously (public member function) | | [fetch\_sub](fetch_sub "cpp/atomic/atomic/fetch sub") | atomically subtracts the argument from the value stored in the atomic object and obtains the value held previously (public member function) | | [operator+=operator-=operator&=operator|=operator^=](operator_arith2 "cpp/atomic/atomic/operator arith2") | adds, subtracts, or performs bitwise AND, OR, XOR with the atomic value (public member function) |
programming_docs
cpp std::atomic<T>::store std::atomic<T>::store ===================== | | | | | --- | --- | --- | | | | (since C++11) | | ``` void store( T desired, std::memory_order order = std::memory_order_seq_cst ) noexcept; ``` | | | | ``` void store( T desired, std::memory_order order = std::memory_order_seq_cst ) volatile noexcept; ``` | | | Atomically replaces the current value with `desired`. Memory is affected according to the value of `order`. `order` must be one of `[std::memory\_order\_relaxed](../memory_order "cpp/atomic/memory order")`, `[std::memory\_order\_release](../memory_order "cpp/atomic/memory order")` or `[std::memory\_order\_seq\_cst](../memory_order "cpp/atomic/memory order")`. Otherwise the behavior is undefined. | | | | --- | --- | | The volatile-qualified version is deprecated if `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<T>::is\_always\_lock\_free` is `false`. | (since C++20) | ### Parameters | | | | | --- | --- | --- | | desired | - | the value to store into the atomic variable | | order | - | memory order constraints to enforce | ### Return value (none). ### See also | | | | --- | --- | | [operator=](operator= "cpp/atomic/atomic/operator=") | stores a value into an atomic object (public member function) | | [atomic\_storeatomic\_store\_explicit](../atomic_store "cpp/atomic/atomic store") (C++11)(C++11) | atomically replaces the value of the atomic object with a non-atomic argument (function template) | cpp std::atomic<T>::fetch_add std::atomic<T>::fetch\_add ========================== | | | | | --- | --- | --- | | member only of `atomic<*Integral*>`(C++11) and `atomic<*Floating*>`(C++20) template specializations | | | | | (1) | | | ``` T fetch_add( T arg, std::memory_order order = std::memory_order_seq_cst ) noexcept; ``` | | | ``` T fetch_add( T arg, std::memory_order order = std::memory_order_seq_cst ) volatile noexcept; ``` | | | member only of `atomic<T*>` template specialization | | | | | (2) | | | ``` T* fetch_add( std::ptrdiff_t arg, std::memory_order order = std::memory_order_seq_cst ) noexcept; ``` | | | ``` T* fetch_add( std::ptrdiff_t arg, std::memory_order order = std::memory_order_seq_cst ) volatile noexcept; ``` | | Atomically replaces the current value with the result of arithmetic addition of the value and `arg`. That is, it performs atomic post-increment. The operation is read-modify-write operation. Memory is affected according to the value of `order`. For signed `Integral` types, arithmetic is defined to use two’s complement representation. There are no undefined results. For `T*` types, the result may be an undefined address, but the operation otherwise has no undefined behavior. The program is ill-formed if `T` is not an object type. | | | | --- | --- | | For floating-point types, the [floating-point environment](../../numeric/fenv "cpp/numeric/fenv") in effect may be different from the calling thread's floating-point environment. The operation need not conform to the corresponding `[std::numeric\_limits](../../types/numeric_limits "cpp/types/numeric limits")` traits but is encouraged to do so. If the result is not a representable value for its type, the result is unspecified but the operation otherwise has no undefined behavior. The volatile-qualified versions are deprecated if `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<T>::is\_always\_lock\_free` is `false`. | (since C++20) | ### Parameters | | | | | --- | --- | --- | | arg | - | the other argument of arithmetic addition | | order | - | memory order constraints to enforce | ### Return value The value immediately preceding the effects of this function in the [modification order](../memory_order#Modification_order "cpp/atomic/memory order") of `*this`. ### Example ``` #include <iostream> #include <thread> #include <atomic> #include <array> std::atomic<long long> data{10}; std::array<long long, 5> return_values{}; void do_work(int thread_num) { long long val = data.fetch_add(1, std::memory_order_relaxed); return_values[thread_num] = val; } int main() { { std::jthread th0{do_work, 0}; std::jthread th1{do_work, 1}; std::jthread th2{do_work, 2}; std::jthread th3{do_work, 3}; std::jthread th4{do_work, 4}; } std::cout << "Result : " << data << '\n'; for (long long val : return_values) { std::cout << "Seen return value : " << val << std::endl; } } ``` Possible output: ``` Result : 15 Seen return value : 11 Seen return value : 10 Seen return value : 14 Seen return value : 12 Seen return value : 13 ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [P0558R1](https://wg21.link/P0558R1) | C++11 | arithmetic permitted on pointers to *cv* void or function | made ill-formed | ### See also | | | | --- | --- | | [atomic\_fetch\_addatomic\_fetch\_add\_explicit](../atomic_fetch_add "cpp/atomic/atomic fetch add") (C++11)(C++11) | adds a non-atomic value to an atomic object and obtains the previous value of the atomic (function template) | | [operator++operator++(int)operator--operator--(int)](operator_arith "cpp/atomic/atomic/operator arith") | increments or decrements the atomic value by one (public member function) | cpp std::atomic<T>::operator T std::atomic<T>::operator T ========================== | | | | | --- | --- | --- | | | | (since C++11) | | ``` operator T() const noexcept; ``` | | | | ``` operator T() const volatile noexcept; ``` | | | Atomically loads and returns the current value of the atomic variable. Equivalent to `load()`. | | | | --- | --- | | The volatile-qualified version is deprecated if `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<T>::is\_always\_lock\_free` is `false`. | (since C++20) | ### Parameters (none). ### Return value The current value of the atomic variable. ### See also | | | | --- | --- | | [load](load "cpp/atomic/atomic/load") | atomically obtains the value of the atomic object (public member function) | cpp std::atomic<T>::notify_all std::atomic<T>::notify\_all =========================== | | | | | --- | --- | --- | | | | (since C++20) | | ``` void notify_all() noexcept; ``` | | | | ``` void notify_all() volatile noexcept; ``` | | | Performs atomic notifying operations. Unblocks all threads blocked in atomic waiting operations (i.e. `wait()`) on `*this`, if there are any; otherwise does nothing. ### Return value (none). ### Notes This form of change-detection is often more efficient than simple polling or pure spinlocks. ### Example ### See also | | | | --- | --- | | [wait](wait "cpp/atomic/atomic/wait") (C++20) | blocks the thread until notified and the atomic value changes (public member function) | | [atomic\_waitatomic\_wait\_explicit](../atomic_wait "cpp/atomic/atomic wait") (C++20)(C++20) | blocks the thread until notified and the atomic value changes (function template) | | [atomic\_notify\_one](../atomic_notify_one "cpp/atomic/atomic notify one") (C++20) | notifies a thread blocked in atomic\_wait (function template) | cpp std::atomic<T>::wait std::atomic<T>::wait ==================== | | | | | --- | --- | --- | | | | (since C++20) | | ``` void wait( T old, std::memory_order order = std::memory_order::seq_cst ) const noexcept; ``` | | | | ``` void wait( T old, std::memory_order order = std::memory_order::seq_cst ) const volatile noexcept; ``` | | | Performs atomic waiting operations. Behaves as if it repeatedly performs the following steps: * Compare the [value representation](../../language/object "cpp/language/object") of `this->load(order)` with that of `old`. + If those are equal, then blocks until `*this` is notified by `notify_one()` or `notify_all()`, or the thread is unblocked spuriously. + Otherwise, returns. These functions are guaranteed to return only if value has changed, even if underlying implementation unblocks spuriously. ### Parameters | | | | | --- | --- | --- | | old | - | the value to check the `atomic`'s object no longer contains | | order | - | the memory synchronization ordering for this operation: must not be `std::memory_order::release` or `std::memory_order::acq_rel` | ### Return value (none). ### Notes This form of change-detection is often more efficient than simple polling or pure spinlocks. Due to the [ABA problem](https://en.wikipedia.org/wiki/ABA_problem), transient changes from `old` to another value and back to `old` might be missed, and not unblock. The comparison is bitwise (similar to `[std::memcmp](../../string/byte/memcmp "cpp/string/byte/memcmp")`); no comparison operator is used. Padding bits that never participate in an object's value representation are ignored. ### Example ### See also | | | | --- | --- | | [notify\_one](notify_one "cpp/atomic/atomic/notify one") (C++20) | notifies at least one thread waiting on the atomic object (public member function) | | [notify\_all](notify_all "cpp/atomic/atomic/notify all") (C++20) | notifies all threads blocked waiting on the atomic object (public member function) | | [atomic\_notify\_one](../atomic_notify_one "cpp/atomic/atomic notify one") (C++20) | notifies a thread blocked in atomic\_wait (function template) | | [atomic\_notify\_all](../atomic_notify_all "cpp/atomic/atomic notify all") (C++20) | notifies all threads blocked in atomic\_wait (function template) | cpp std::atomic<T>::exchange std::atomic<T>::exchange ======================== | | | | | --- | --- | --- | | | | (since C++11) | | ``` T exchange( T desired, std::memory_order order = std::memory_order_seq_cst ) noexcept; ``` | (1) | | | ``` T exchange( T desired, std::memory_order order = std::memory_order_seq_cst ) volatile noexcept; ``` | (2) | | Atomically replaces the underlying value with `desired`. The operation is read-modify-write operation. Memory is affected according to the value of `order`. | | | | --- | --- | | The volatile-qualified version (2) is deprecated if `[std::atomic](http://en.cppreference.com/w/cpp/atomic/atomic)<T>::is\_always\_lock\_free` is `false`. | (since C++20) | ### Parameters | | | | | --- | --- | --- | | desired | - | value to assign | | order | - | memory order constraints to enforce | ### Return value The value of the atomic variable before the call. ### Example ``` #include <algorithm> #include <atomic> #include <cstddef> #include <iostream> #include <syncstream> #include <thread> #include <vector> int main(){ const std::size_t ThreadNumber = 5; const int Sum = 5; std::atomic<int> atom{0}; std::atomic<int> counter{0}; // lambda as thread proc auto lambda = [&](const int id){ for (int next = 0; next < Sum;){ // each thread is writing a value from its own knowledge const int current = atom.exchange(next); counter++; // sync writing to prevent from interrupting by other threads std::osyncstream(std::cout) << '#' << id << " (" << std::this_thread::get_id() << ") wrote " << next << " replacing the old value " << current << '\n'; next = std::max(current, next) + 1; } }; std::vector<std::thread> v; for (std::size_t i = 0; i < ThreadNumber; ++i){ v.emplace_back(lambda, i); } for (auto& tr : v){ tr.join(); } std::cout << ThreadNumber << " threads adding 0 to " << Sum << " takes total " << counter << " times\n"; } ``` Possible output: ``` #1 (140552371918592) wrote 0 replacing the old value 0 #2 (140552363525888) wrote 0 replacing the old value 0 #1 (140552371918592) wrote 1 replacing the old value 0 #1 (140552371918592) wrote 2 replacing the old value 1 #2 (140552363525888) wrote 1 replacing the old value 1 #1 (140552371918592) wrote 3 replacing the old value 2 #1 (140552371918592) wrote 4 replacing the old value 2 #2 (140552363525888) wrote 2 replacing the old value 3 #2 (140552363525888) wrote 4 replacing the old value 0 #3 (140552355133184) wrote 0 replacing the old value 4 #0 (140552380311296) wrote 0 replacing the old value 0 #0 (140552380311296) wrote 1 replacing the old value 4 #4 (140552346740480) wrote 0 replacing the old value 1 #4 (140552346740480) wrote 2 replacing the old value 0 #4 (140552346740480) wrote 3 replacing the old value 2 #4 (140552346740480) wrote 4 replacing the old value 3 5 threads adding 0 to 5 takes total 16 times ``` ### See also | | | | --- | --- | | [atomic\_exchangeatomic\_exchange\_explicit](../atomic_exchange "cpp/atomic/atomic exchange") (C++11)(C++11) | atomically replaces the value of the atomic object with non-atomic argument and returns the old value of the atomic (function template) | | [exchange](../../utility/exchange "cpp/utility/exchange") (C++14) | replaces the argument with a new value and returns its previous value (function template) | cpp std::atomic_flag::test_and_set std::atomic\_flag::test\_and\_set ================================= | Defined in header `[<atomic>](../../header/atomic "cpp/header/atomic")` | | | | --- | --- | --- | | ``` bool test_and_set(std::memory_order order = std::memory_order_seq_cst) volatile noexcept; ``` | (1) | (since C++11) | | ``` bool test_and_set(std::memory_order order = std::memory_order_seq_cst) noexcept; ``` | (2) | (since C++11) | Atomically changes the state of a `[std::atomic\_flag](../atomic_flag "cpp/atomic/atomic flag")` to set (`true`) and returns the value it held before. ### Parameters | | | | | --- | --- | --- | | order | - | the memory synchronization ordering for this operation | ### See also | | | | --- | --- | | [clear](clear "cpp/atomic/atomic flag/clear") | atomically sets flag to `false` (public member function) | | [atomic\_flag\_test\_and\_setatomic\_flag\_test\_and\_set\_explicit](../atomic_flag_test_and_set "cpp/atomic/atomic flag test and set") (C++11)(C++11) | atomically sets the flag to `true` and returns its previous value (function) | | [memory\_order](../memory_order "cpp/atomic/memory order") (C++11) | defines memory ordering constraints for the given atomic operation (enum) | cpp std::atomic_flag::notify_one std::atomic\_flag::notify\_one ============================== | | | | | --- | --- | --- | | | | (since C++20) | | ``` void notify_one() noexcept; ``` | | | | ``` void notify_one() volatile noexcept; ``` | | | Performs atomic notifying operations. If there is a thread blocked in atomic waiting operation (i.e. `wait()`) on `*this`, then unblocks *at least* one such thread; otherwise does nothing. ### Return value (none). ### Notes This form of change-detection is often more efficient than simple polling or pure spinlocks. ### Example ### See also | | | | --- | --- | | [wait](wait "cpp/atomic/atomic flag/wait") (C++20) | blocks the thread until notified and the atomic value changes (public member function) | | [atomic\_flag\_waitatomic\_flag\_wait\_explicit](../atomic_flag_wait "cpp/atomic/atomic flag wait") (C++20)(C++20) | blocks the thread until notified and the flag changes (function) | | [atomic\_flag\_notify\_one](../atomic_flag_notify_one "cpp/atomic/atomic flag notify one") (C++20) | notifies a thread blocked in atomic\_flag\_wait (function) | cpp std::atomic_flag::test std::atomic\_flag::test ======================= | | | | | --- | --- | --- | | | | (since C++20) | | ``` bool test( std::memory_order order = std::memory_order::seq_cst ) const volatile noexcept; ``` | | | | ``` bool test( std::memory_order order = std::memory_order::seq_cst ) const noexcept; ``` | | | Atomically reads the value of the `*this` and returns the value. ### Parameters | | | | | --- | --- | --- | | order | - | the memory synchronization ordering for this operation: must not be `std::memory_order::release` or `std::memory_order::acq_rel` | ### Return value The value atomically read. ### Example ### See also | | | | --- | --- | | [atomic\_flag\_testatomic\_flag\_test\_explicit](../atomic_flag_test "cpp/atomic/atomic flag test") (C++20)(C++20) | atomically returns the value of the flag (function) | cpp std::atomic_flag::operator= std::atomic\_flag::operator= ============================ | Defined in header `[<atomic>](../../header/atomic "cpp/header/atomic")` | | | | --- | --- | --- | | ``` atomic_flag& operator=( const atomic_flag& ) = delete; ``` | (1) | (since C++11) | | ``` atomic_flag& operator=( const atomic_flag& ) volatile = delete; ``` | (2) | (since C++11) | `[std::atomic\_flag](../atomic_flag "cpp/atomic/atomic flag")` is not assignable, its assignment operators are deleted. cpp std::atomic_flag::clear std::atomic\_flag::clear ======================== | Defined in header `[<atomic>](../../header/atomic "cpp/header/atomic")` | | | | --- | --- | --- | | ``` void clear( std::memory_order order = std::memory_order_seq_cst ) volatile noexcept; ``` | (1) | (since C++11) | | ``` void clear( std::memory_order order = std::memory_order_seq_cst ) noexcept; ``` | (2) | (since C++11) | Atomically changes the state of a `[std::atomic\_flag](../atomic_flag "cpp/atomic/atomic flag")` to clear (`false`). ### Parameters | | | | | --- | --- | --- | | order | - | the memory synchronization ordering for this operation (cannot be `[std::memory\_order\_consume](../memory_order "cpp/atomic/memory order")`, `[std::memory\_order\_acquire](../memory_order "cpp/atomic/memory order")`, or `[std::memory\_order\_acq\_rel](../memory_order "cpp/atomic/memory order")`) | ### See also | | | | --- | --- | | [test\_and\_set](test_and_set "cpp/atomic/atomic flag/test and set") | atomically sets the flag to `true` and obtains its previous value (public member function) | | [atomic\_flag\_clearatomic\_flag\_clear\_explicit](../atomic_flag_clear "cpp/atomic/atomic flag clear") (C++11)(C++11) | atomically sets the value of the flag to `false` (function) | | [memory\_order](../memory_order "cpp/atomic/memory order") (C++11) | defines memory ordering constraints for the given atomic operation (enum) | cpp std::atomic_flag::atomic_flag std::atomic\_flag::atomic\_flag =============================== | Defined in header `[<atomic>](../../header/atomic "cpp/header/atomic")` | | | | --- | --- | --- | | | (1) | | | ``` atomic_flag() noexcept = default; ``` | (since C++11) (until C++20) | | ``` constexpr atomic_flag() noexcept; ``` | (since C++20) | | ``` atomic_flag( const atomic_flag& ) = delete; ``` | (2) | (since C++11) | Constructs a new `[std::atomic\_flag](../atomic_flag "cpp/atomic/atomic flag")`. | | | | --- | --- | | 1) Trivial default constructor, initializes `[std::atomic\_flag](../atomic_flag "cpp/atomic/atomic flag")` to unspecified state. | (until C++20) | | 1) Initializes `[std::atomic\_flag](../atomic_flag "cpp/atomic/atomic flag")` to clear state. | (since C++20) | 2) The copy constructor is deleted; `[std::atomic\_flag](../atomic_flag "cpp/atomic/atomic flag")` is not copyable. In addition, `[std::atomic\_flag](../atomic_flag "cpp/atomic/atomic flag")` can be value-initialized to clear state with the expression `[ATOMIC\_FLAG\_INIT](../atomic_flag_init "cpp/atomic/ATOMIC FLAG INIT")`. For an `atomic_flag` with static [storage duration](../../language/storage_duration#Storage_duration "cpp/language/storage duration"), this guarantees [static initialization](../../language/initialization#Static_initialization "cpp/language/initialization"): the flag can be used in constructors of static objects. This macro is deprecated. (since C++20). ### See also | | | | --- | --- | | [ATOMIC\_FLAG\_INIT](../atomic_flag_init "cpp/atomic/ATOMIC FLAG INIT") (C++11) | initializes an `[std::atomic\_flag](../atomic_flag "cpp/atomic/atomic flag")` to `false` (macro constant) |
programming_docs
cpp std::atomic_flag::notify_all std::atomic\_flag::notify\_all ============================== | | | | | --- | --- | --- | | | | (since C++20) | | ``` void notify_all() noexcept; ``` | | | | ``` void notify_all() volatile noexcept; ``` | | | Performs atomic notifying operations. Unblocks all threads blocked in atomic waiting operations (i.e. `wait()`) on `*this`, if there are any; otherwise does nothing. ### Return value (none). ### Notes This form of change-detection is often more efficient than simple polling or pure spinlocks. ### Example ### See also | | | | --- | --- | | [wait](wait "cpp/atomic/atomic flag/wait") (C++20) | blocks the thread until notified and the atomic value changes (public member function) | | [atomic\_flag\_waitatomic\_flag\_wait\_explicit](../atomic_flag_wait "cpp/atomic/atomic flag wait") (C++20)(C++20) | blocks the thread until notified and the flag changes (function) | | [atomic\_flag\_notify\_one](../atomic_flag_notify_one "cpp/atomic/atomic flag notify one") (C++20) | notifies a thread blocked in atomic\_flag\_wait (function) | cpp std::atomic_flag::wait std::atomic\_flag::wait ======================= | | | | | --- | --- | --- | | | | (since C++20) | | ``` void wait( bool old, std::memory_order order = std::memory_order::seq_cst ) const noexcept; ``` | | | | ``` void wait( bool old, std::memory_order order = std::memory_order::seq_cst ) const volatile noexcept; ``` | | | Performs atomic waiting operations. Behaves as if it repeatedly performs the following steps: * Compare `this->test(order)` with that of `old`. + If those are equal, then blocks until `*this` is notified by `notify_one()` or `notify_all()`, or the thread is unblocked spuriously. + Otherwise, returns. These functions are guaranteed to return only if value has changed, even if underlying implementation unblocks spuriously. ### Parameters | | | | | --- | --- | --- | | old | - | the value to check the `atomic_flag`'s object no longer contains | | order | - | the memory synchronization ordering for this operation: must not be `std::memory_order::release` or `std::memory_order::acq_rel` | ### Return value (none). ### Notes This form of change-detection is often more efficient than simple polling or pure spinlocks. Due to the [ABA problem](https://en.wikipedia.org/wiki/ABA_problem), transient changes from `old` to another value and back to `old` might be missed, and not unblock. ### Example ### See also | | | | --- | --- | | [notify\_one](notify_one "cpp/atomic/atomic flag/notify one") (C++20) | notifies at least one thread waiting on the atomic object (public member function) | | [notify\_all](notify_all "cpp/atomic/atomic flag/notify all") (C++20) | notifies all threads blocked waiting on the atomic object (public member function) | | [atomic\_flag\_notify\_one](../atomic_flag_notify_one "cpp/atomic/atomic flag notify one") (C++20) | notifies a thread blocked in atomic\_flag\_wait (function) | | [atomic\_flag\_notify\_all](../atomic_flag_notify_all "cpp/atomic/atomic flag notify all") (C++20) | notifies all threads blocked in atomic\_flag\_wait (function) | cpp std::atomic_ref<T>::fetch_xor std::atomic\_ref<T>::fetch\_xor =============================== | | | | | --- | --- | --- | | ``` T fetch_xor( T arg, std::memory_order order = std::memory_order_seq_cst ) const noexcept; ``` | | (since C++20) (member only of `atomic_ref<*Integral*>` template specialization) | Atomically replaces the current value of the referenced object with the result of bitwise XOR of the value and `arg`. This operation is a read-modify-write operation. Memory is affected according to the value of `order`. ### Parameters | | | | | --- | --- | --- | | arg | - | the other argument of bitwise XOR | | order | - | memory order constraints to enforce | ### Return value The value of the referenced object, immediately preceding the effects of this function. cpp std::atomic_ref<T>::operator+=,-=,&=,|=,^= std::atomic\_ref<T>::operator+=,-=,&=,|=,^= =========================================== | | | | | --- | --- | --- | | member only of `atomic_ref<*Integral*>` and `atomic_ref<*Floating*>` template specializations | | | | ``` T operator+=( T arg ) const noexcept; ``` | (1) | | | member only of `atomic_ref<T*>` template specialization | | | | ``` T* operator+=( std::ptrdiff_t arg ) const noexcept; ``` | (1) | | | member only of `atomic_ref<*Integral*>` and `atomic_ref<*Floating*>` template specializations | | | | ``` T operator-=( T arg ) const noexcept; ``` | (1) | | | member only of `atomic_ref<T*>` template specialization | | | | ``` T* operator-=( std::ptrdiff_t arg ) const noexcept; ``` | (1) | | | member only of `atomic_ref<*Integral*>` template specialization | | | | ``` T operator&=( T arg ) const noexcept; ``` | (3) | | | ``` T operator|=( T arg ) const noexcept; ``` | (4) | | | ``` T operator^=( T arg ) const noexcept; ``` | (5) | | Atomically replaces the current value of the referenced object with the result of computation involving the previous value and `arg`. These operations are read-modify-write operations. 1) Performs atomic addition. Equivalent to `return fetch_add(arg) + arg;`. 2) Performs atomic subtraction. Equivalent to `return fetch_sub(arg) - arg;`. 3) Performs atomic bitwise and. Equivalent to `return fetch_and(arg) & arg;`. 4) Performs atomic bitwise or. Equivalent to `return fetch_or(arg) | arg;`. 5) Performs atomic bitwise exclusive or. Equivalent to `return fetch_xor(arg) ^ arg;`. For signed integral types, arithmetic is defined to use two’s complement representation. There are no undefined results. For floating-point types, the [floating-point environment](../../numeric/fenv "cpp/numeric/fenv") in effect may be different from the calling thread's floating-point environment. The operation need not be conform to the corresponding `[std::numeric\_limits](../../types/numeric_limits "cpp/types/numeric limits")` traits but is encouraged to do so. If the result is not a representable value for its type, the result is unspecified but the operation otherwise has no undefined behavior. For `T*` types, the result may be an undefined address, but the operations otherwise have no undefined behavior. The program is ill-formed if `T` is not an object type. ### Parameters | | | | | --- | --- | --- | | arg | - | the argument for the arithmetic operation | ### Return value The resulting value (that is, the result of applying the corresponding binary operator to the value immediately preceding the effects of the corresponding member function). ### Notes Unlike most compound assignment operators, the compound assignment operators for `atomic_ref` do not return a reference to their left-hand arguments. They return a copy of the stored value instead. ### See also | | | | --- | --- | | [operator++operator++(int)operator--operator--(int)](operator_arith "cpp/atomic/atomic ref/operator arith") | atomically increments or decrements the referenced object by one (public member function) | cpp std::atomic_ref<T>::compare_exchange_weak, std::atomic_ref<T>::compare_exchange_strong std::atomic\_ref<T>::compare\_exchange\_weak, std::atomic\_ref<T>::compare\_exchange\_strong ============================================================================================ | | | | | --- | --- | --- | | ``` bool compare_exchange_weak( T& expected, T desired, std::memory_order success, std::memory_order failure ) const noexcept; ``` | (1) | (since C++20) | | ``` bool compare_exchange_weak( T& expected, T desired, std::memory_order order = std::memory_order_seq_cst ) const noexcept; ``` | (2) | (since C++20) | | ``` bool compare_exchange_strong( T& expected, T desired, std::memory_order success, std::memory_order failure ) const noexcept; ``` | (3) | (since C++20) | | ``` bool compare_exchange_strong( T& expected, T desired, std::memory_order order = std::memory_order_seq_cst ) const noexcept; ``` | (4) | (since C++20) | Atomically compares the [value representation](../../language/object "cpp/language/object") of the referenced object with that of `expected`, and if those are bitwise-equal, replaces the former with `desired` (performs a read-modify-write operation). Otherwise, loads the actual value stored in the referenced object into `expected` (performs a load operation). The memory models for the read-modify-write and load operations are `success` and `failure` respectively. In the (2) and (4) versions `order` is used for both read-modify-write and load operations, except that `[std::memory\_order\_acquire](../memory_order "cpp/atomic/memory order")` and `[std::memory\_order\_relaxed](../memory_order "cpp/atomic/memory order")` are used for the load operation if `order == [std::memory\_order\_acq\_rel](http://en.cppreference.com/w/cpp/atomic/memory_order)`, or `order == [std::memory\_order\_release](http://en.cppreference.com/w/cpp/atomic/memory_order)` respectively. ### Parameters | | | | | --- | --- | --- | | expected | - | reference to the value expected to be found in the object referenced by the `atomic_ref` object | | desired | - | the value to store in the referenced object if it is as expected | | success | - | the memory synchronization ordering for the read-modify-write operation if the comparison succeeds. All values are permitted. | | failure | - | the memory synchronization ordering for the load operation if the comparison fails. Cannot be `[std::memory\_order\_release](../memory_order "cpp/atomic/memory order")` or `[std::memory\_order\_acq\_rel](../memory_order "cpp/atomic/memory order")` | | order | - | the memory synchronization ordering for both operations | ### Return value `true` if the referenced object was successfully changed, `false` otherwise. ### Notes The comparison and copying are bitwise (similar to `[std::memcmp](../../string/byte/memcmp "cpp/string/byte/memcmp")` and `[std::memcpy](../../string/byte/memcpy "cpp/string/byte/memcpy")`); no constructor, assignment operator, or comparison operator are used. The weak forms (1-2) of the functions are allowed to fail spuriously, that is, act as if `*this != expected` even if they are equal. When a compare-and-exchange is in a loop, the weak version will yield better performance on some platforms. When a weak compare-and-exchange would require a loop and a strong one would not, the strong one is preferable unless the object representation of `T` may include trap bits, or offers multiple object representations for the same value (e.g. floating-point NaN). In those cases, weak compare-and-exchange typically works because it quickly converges on some stable object representation. For a union with bits that participate in the value representations of some members but not the others, compare-and-exchange might always fail because such padding bits have indeterminate values when they do not participate in the value representation of the active member. Padding bits that never participate in an object's value representation are ignored. ### Example cpp std::atomic_ref<T>::load std::atomic\_ref<T>::load ========================= | | | | | --- | --- | --- | | ``` T load( std::memory_order order = std::memory_order_seq_cst ) const noexcept; ``` | | (since C++20) | Atomically loads and returns the current value of the referenced object. Memory is affected according to the value of `order`. `order` must be one of `[std::memory\_order\_relaxed](../memory_order "cpp/atomic/memory order")`, `[std::memory\_order\_consume](../memory_order "cpp/atomic/memory order")`, `[std::memory\_order\_acquire](../memory_order "cpp/atomic/memory order")` or `[std::memory\_order\_seq\_cst](../memory_order "cpp/atomic/memory order")`. Otherwise the behavior is undefined. ### Parameters | | | | | --- | --- | --- | | order | - | memory order constraints to enforce | ### Return value The current value of the referenced object. ### See also | | | | --- | --- | | [operator T](operator_t "cpp/atomic/atomic ref/operator T") | loads a value from the referenced object (public member function) | cpp std::atomic_ref<T>::fetch_sub std::atomic\_ref<T>::fetch\_sub =============================== | | | | | --- | --- | --- | | member only of `atomic_ref<*Integral*>` and `atomic_ref<*Floating*>` template specializations | | | | ``` T fetch_sub( T arg, std::memory_order order = std::memory_order_seq_cst ) const noexcept; ``` | (1) | | | member only of `atomic_ref<T*>` template specialization | | | | ``` T* fetch_sub( std::ptrdiff_t arg, std::memory_order order = std::memory_order_seq_cst ) const noexcept; ``` | (2) | | Atomically replaces the current value of the referenced object with the result of arithmetic subtraction of the value and `arg`. This operation is a read-modify-write operation. Memory is affected according to the value of `order`. For signed integral types, arithmetic is defined to use two’s complement representation. There are no undefined results. For floating-point types, the [floating-point environment](../../numeric/fenv "cpp/numeric/fenv") in effect may be different from the calling thread's floating-point environment. The operation need not be conform to the corresponding `[std::numeric\_limits](../../types/numeric_limits "cpp/types/numeric limits")` traits but is encouraged to do so. If the result is not a representable value for its type, the result is unspecified but the operation otherwise has no undefined behavior. For `T*` types, the result may be an undefined address, but the operation otherwise has no undefined behavior. The program is ill-formed if `T` is not an object type. ### Parameters | | | | | --- | --- | --- | | arg | - | the other argument of arithmetic subtraction | | order | - | memory order constraints to enforce | ### Return value The value of the referenced object, immediately preceding the effects of this function. ### Example cpp std::atomic_ref<T>::fetch_and std::atomic\_ref<T>::fetch\_and =============================== | | | | | --- | --- | --- | | ``` T fetch_and( T arg, std::memory_order order = std::memory_order_seq_cst ) const noexcept; ``` | | (since C++20) (member only of `atomic_ref<*Integral*>` template specialization) | Atomically replaces the current value of the referenced object with the result of bitwise AND of the value and `arg`. This operation is a read-modify-write operation. Memory is affected according to the value of `order`. ### Parameters | | | | | --- | --- | --- | | arg | - | the other argument of bitwise AND | | order | - | memory order constraints to enforce | ### Return value The value of the referenced object, immediately preceding the effects of this function. cpp std::atomic_ref<T>::is_lock_free std::atomic\_ref<T>::is\_lock\_free =================================== | | | | | --- | --- | --- | | ``` bool is_lock_free() const noexcept; ``` | | (since C++20) | Checks whether the atomic operations on this object are lock-free. ### Parameters (none). ### Return value `true` if the atomic operations on this object are lock-free, `false` otherwise. ### Notes All atomic types except for `[std::atomic\_flag](../atomic_flag "cpp/atomic/atomic flag")` may be implemented using mutexes or other locking operations, rather than using the lock-free atomic CPU instructions. Atomic types are also allowed to be *sometimes* lock-free, e.g. if only aligned memory accesses are naturally atomic on a given architecture, misaligned objects of the same type have to use locks. The C++ standard recommends (but does not require) that lock-free atomic operations are also address-free, that is, suitable for communication between processes using shared memory. ### Example ### See also | | | | --- | --- | | [is\_always\_lock\_free](is_always_lock_free "cpp/atomic/atomic ref/is always lock free") [static] | indicates that the type is always lock-free (public static member constant) | cpp std::atomic_ref<T>::fetch_or std::atomic\_ref<T>::fetch\_or ============================== | | | | | --- | --- | --- | | ``` T fetch_or( T arg, std::memory_order order = std::memory_order_seq_cst ) const noexcept; ``` | | (since C++20) (member only of `atomic_ref<*Integral*>` template specialization) | Atomically replaces the current value of the referenced object with the result of bitwise OR of the value and `arg`. This operation is a read-modify-write operation. Memory is affected according to the value of `order`. ### Parameters | | | | | --- | --- | --- | | arg | - | the other argument of bitwise OR | | order | - | memory order constraints to enforce | ### Return value The value of the referenced object, immediately preceding the effects of this function. cpp std::atomic_ref<T>::notify_one std::atomic\_ref<T>::notify\_one ================================ | | | | | --- | --- | --- | | | | (since C++20) | | ``` void notify_one() const noexcept; ``` | | | | ``` void notify_one() const volatile noexcept; ``` | | | Performs atomic notifying operations. If there is a thread blocked in atomic waiting operation (i.e. `wait()`) on `*this`, then unblocks *at least* one such thread; otherwise does nothing. ### Return value (none). ### Notes This form of change-detection is often more efficient than simple polling or pure spinlocks. ### Example ### See also | | | | --- | --- | | [wait](wait "cpp/atomic/atomic ref/wait") (C++20) | blocks the thread until notified and the atomic value changes (public member function) | | [atomic\_waitatomic\_wait\_explicit](../atomic_wait "cpp/atomic/atomic wait") (C++20)(C++20) | blocks the thread until notified and the atomic value changes (function template) | | [atomic\_notify\_one](../atomic_notify_one "cpp/atomic/atomic notify one") (C++20) | notifies a thread blocked in atomic\_wait (function template) | cpp std::atomic_ref<T>::required_alignment std::atomic\_ref<T>::required\_alignment ======================================== | | | | | --- | --- | --- | | ``` static constexpr std::size_t required_alignment= /*implementation-defined*/; ``` | | (since C++20) | The value of `required_alignment` is the required alignment for an object to be referenced by an atomic reference, which is at least `alignof(T)`. ### Notes Hardware could require that an object to be referenced by an `atomic_ref<T>` have stricter alignment than other `T` objects, and whether operations on an `atomic_ref` are lock-free can depend on the alignment of the referenced object. cpp std::atomic_ref<T>::is_always_lock_free std::atomic\_ref<T>::is\_always\_lock\_free =========================================== | | | | | --- | --- | --- | | ``` static constexpr bool is_always_lock_free = /*implementation-defined*/; ``` | | (since C++20) | Equals `true` if the operations on this `atomic_ref` type is always lock-free and `false` if it is never or sometimes lock-free. The value of this constant is consistent with the result of member function `is_lock_free`. ### See also | | | | --- | --- | | [is\_lock\_free](is_lock_free "cpp/atomic/atomic ref/is lock free") | checks if the `atomic_ref` object is lock-free (public member function) |
programming_docs
cpp std::atomic_ref<T>::operator= std::atomic\_ref<T>::operator= ============================== | | | | | --- | --- | --- | | ``` T operator=( T desired ) const noexcept; ``` | (1) | | | ``` atomic_ref& operator=( const atomic_ref& ) = delete; ``` | (2) | | 1) Atomically assigns a value `desired` to the referenced object. Equivalent to `store(desired)`. 2) `atomic_ref` is not [CopyAssignable](../../named_req/copyassignable "cpp/named req/CopyAssignable"). ### Parameters | | | | | --- | --- | --- | | desired | - | value to assign | ### Return value `desired`. ### Notes Unlike most assignment operators, the assignment operator for `atomic_ref` does not return a reference to its left-hand argument. It returns a copy of the stored value instead. ### See also | | | | --- | --- | | [(constructor)](atomic_ref "cpp/atomic/atomic ref/atomic ref") | constructs an `atomic_ref` object (public member function) | cpp std::atomic_ref<T>::operator++,++(int),--,--(int) std::atomic\_ref<T>::operator++,++(int),--,--(int) ================================================== | | | | | --- | --- | --- | | member only of `atomic_ref<*Integral*>` and `atomic_ref<T*>` template specializations | | | | ``` value_type operator++() const noexcept; ``` | (1) | (since C++20) | | ``` value_type operator++(int) const noexcept; ``` | (2) | (since C++20) | | ``` value_type operator--() const noexcept; ``` | (3) | (since C++20) | | ``` value_type operator--(int) const noexcept; ``` | (4) | (since C++20) | Atomically increments or decrements the current value of the referenced object. These operations are read-modify-write operations. 1) Performs atomic pre-increment. Equivalent to `return fetch_add(1) + 1;`. 2) Performs atomic post-increment. Equivalent to `return fetch_add(1);`. 3) Performs atomic pre-decrement. Equivalent to `return fetch_sub(1) - 1;` 4) Performs atomic post-decrement. Equivalent to `return fetch_sub(1);`. For signed `Integral` types, arithmetic is defined to use two’s complement representation. There are no undefined results. For `T*` types, the result may be an undefined address, but the operations otherwise have no undefined behavior. The program is ill-formed if `T` is not an object type. ### Parameters (none). ### Return value 1,3) The value of the referenced object after the modification. 2,4) The value of the referenced object before the modification. ### Notes Unlike most pre-increment and pre-decrement operators, the pre-increment and pre-decrement operators for `atomic_ref` do not return a reference to the modified object. They return a copy of the stored value instead. ### See also | | | | --- | --- | | [fetch\_add](fetch_add "cpp/atomic/atomic ref/fetch add") | atomically adds the argument to the value stored in the referenced object and obtains the value held previously (public member function) | | [fetch\_sub](fetch_sub "cpp/atomic/atomic ref/fetch sub") | atomically subtracts the argument from the value stored in the referenced object and obtains the value held previously (public member function) | | [operator+=operator-=operator&=operator|=operator^=](operator_arith2 "cpp/atomic/atomic ref/operator arith2") | atomically adds, subtracts, or performs bitwise AND, OR, XOR with the referenced value (public member function) | cpp std::atomic_ref<T>::store std::atomic\_ref<T>::store ========================== | | | | | --- | --- | --- | | ``` void store( T desired, std::memory_order order = std::memory_order_seq_cst ) const noexcept; ``` | | (since C++20) | Atomically replaces the current value of the referenced object with `desired`. Memory is affected according to the value of `order`. `order` must be one of `[std::memory\_order\_relaxed](../memory_order "cpp/atomic/memory order")`, `[std::memory\_order\_release](../memory_order "cpp/atomic/memory order")` or `[std::memory\_order\_seq\_cst](../memory_order "cpp/atomic/memory order")`. Otherwise the behavior is undefined. ### Parameters | | | | | --- | --- | --- | | desired | - | the value to store into the referenced object | | order | - | memory order constraints to enforce | ### Return value (none). ### See also | | | | --- | --- | | [operator=](operator= "cpp/atomic/atomic ref/operator=") | stores a value into the object referenced by an `atomic_ref` object (public member function) | cpp std::atomic_ref<T>::atomic_ref std::atomic\_ref<T>::atomic\_ref ================================ | | | | | --- | --- | --- | | ``` explicit atomic_ref( T& obj ); ``` | (1) | (since C++20) | | ``` atomic_ref( const atomic_ref& ref ) noexcept; ``` | (2) | (since C++20) | Constructs a new `atomic_ref` object. 1) Constructs an `atomic_ref` object referencing the object `obj`. The behavior is undefined if `obj` is not aligned to [`required_alignment`](required_alignment "cpp/atomic/atomic ref/required alignment"). 2) Constructs an `atomic_ref` object referencing the object referenced by `ref`. ### Parameters | | | | | --- | --- | --- | | obj | - | object to reference | | ref | - | another `atomic_ref` object to copy from | ### Example The program increments the values in a container using several threads. Then the final sum is printed. Non-atomic access may "loss" the results of some operations due to data-races. ``` #include <atomic> #include <thread> #include <vector> #include <numeric> #include <iostream> int main() { using Data = std::vector<char>; auto inc_atomically = [](Data& data) { for (Data::value_type& x : data) { auto xx = std::atomic_ref<Data::value_type>(x); ++xx; // atomic read-modify-write } }; auto inc_directly = [](Data& data) { for (Data::value_type& x : data) ++x; }; auto test_run = [](const auto Fun) { Data data(10'000'000); { std::jthread j1 {Fun, std::ref(data)}; std::jthread j2 {Fun, std::ref(data)}; std::jthread j3 {Fun, std::ref(data)}; std::jthread j4 {Fun, std::ref(data)}; } std::cout << "sum = " << std::accumulate(cbegin(data), cend(data), 0) << '\n'; }; test_run(inc_atomically); test_run(inc_directly); } ``` Possible output: ``` sum = 40000000 sum = 39994973 ``` cpp std::atomic_ref<T>::fetch_add std::atomic\_ref<T>::fetch\_add =============================== | | | | | --- | --- | --- | | member only of `atomic_ref<*Integral*>` and `atomic_ref<*Floating*>` template specializations | | | | ``` T fetch_add( T arg, std::memory_order order = std::memory_order_seq_cst ) const noexcept; ``` | (1) | | | member only of `atomic_ref<T*>` template specialization | | | | ``` T* fetch_add( std::ptrdiff_t arg, std::memory_order order = std::memory_order_seq_cst ) const noexcept; ``` | (2) | | Atomically replaces the current value of the referenced object with the result of arithmetic addition of the value and `arg`. This operation is a read-modify-write operation. Memory is affected according to the value of `order`. For signed integral types, arithmetic is defined to use two’s complement representation. There are no undefined results. For floating-point types, the [floating-point environment](../../numeric/fenv "cpp/numeric/fenv") in effect may be different from the calling thread's floating-point environment. The operation need not be conform to the corresponding `[std::numeric\_limits](../../types/numeric_limits "cpp/types/numeric limits")` traits but is encouraged to do so. If the result is not a representable value for its type, the result is unspecified but the operation otherwise has no undefined behavior. For `T*` types, the result may be an undefined address, but the operation otherwise has no undefined behavior. The program is ill-formed if `T` is not an object type. ### Parameters | | | | | --- | --- | --- | | arg | - | the other argument of arithmetic addition | | order | - | memory order constraints to enforce | ### Return value The value of the referenced object, immediately preceding the effects of this function. ### Example cpp std::atomic_ref<T>::operator T std::atomic\_ref<T>::operator T =============================== | | | | | --- | --- | --- | | ``` operator T() const noexcept; ``` | | (since C++20) | Atomically loads and returns the current value of the referenced object. Equivalent to `load()`. ### Parameters (none). ### Return value The current value of the referenced object. ### See also | | | | --- | --- | | [load](load "cpp/atomic/atomic ref/load") | atomically obtains the value of the referenced object (public member function) | cpp std::atomic_ref<T>::notify_all std::atomic\_ref<T>::notify\_all ================================ | | | | | --- | --- | --- | | | | (since C++20) | | ``` void notify_all() const noexcept; ``` | | | | ``` void notify_all() const volatile noexcept; ``` | | | Performs atomic notifying operations. Unblocks all threads blocked in atomic waiting operations (i.e. `wait()`) on `*this`, if there are any; otherwise does nothing. ### Return value (none). ### Notes This form of change-detection is often more efficient than simple polling or pure spinlocks. ### Example ### See also | | | | --- | --- | | [wait](wait "cpp/atomic/atomic ref/wait") (C++20) | blocks the thread until notified and the atomic value changes (public member function) | | [atomic\_waitatomic\_wait\_explicit](../atomic_wait "cpp/atomic/atomic wait") (C++20)(C++20) | blocks the thread until notified and the atomic value changes (function template) | | [atomic\_notify\_one](../atomic_notify_one "cpp/atomic/atomic notify one") (C++20) | notifies a thread blocked in atomic\_wait (function template) | cpp std::atomic_ref<T>::wait std::atomic\_ref<T>::wait ========================= | | | | | --- | --- | --- | | | | (since C++20) | | ``` void wait( T old, std::memory_order order = std::memory_order::seq_cst ) const noexcept; ``` | | | | ``` void wait( T old, std::memory_order order = std::memory_order::seq_cst ) const volatile noexcept; ``` | | | Performs atomic waiting operations. Behaves as if it repeatedly performs the following steps: * Compare the [value representation](../../language/object "cpp/language/object") of `this->load(order)` with that of `old`. + If those are equal, then blocks until `*this` is notified by `notify_one()` or `notify_all()`, or the thread is unblocked spuriously. + Otherwise, returns. These functions are guaranteed to return only if value has changed, even if underlying implementation unblocks spuriously. ### Parameters | | | | | --- | --- | --- | | old | - | the value to check the `atomic_ref`'s object no longer contains | | order | - | the memory synchronization ordering for this operation: must not be `std::memory_order::release` or `std::memory_order::acq_rel` | ### Return value (none). ### Notes This form of change-detection is often more efficient than simple polling or pure spinlocks. Due to the [ABA problem](https://en.wikipedia.org/wiki/ABA_problem), transient changes from `old` to another value and back to `old` might be missed, and not unblock. The comparison is bitwise (similar to `[std::memcmp](../../string/byte/memcmp "cpp/string/byte/memcmp")`); no comparison operator is used. Padding bits that never participate in an object's value representation are ignored. ### Example ### See also | | | | --- | --- | | [notify\_one](notify_one "cpp/atomic/atomic ref/notify one") (C++20) | notifies at least one thread waiting on the atomic object (public member function) | | [notify\_all](notify_all "cpp/atomic/atomic ref/notify all") (C++20) | notifies all threads blocked waiting on the atomic object (public member function) | | [atomic\_notify\_one](../atomic_notify_one "cpp/atomic/atomic notify one") (C++20) | notifies a thread blocked in atomic\_wait (function template) | | [atomic\_notify\_all](../atomic_notify_all "cpp/atomic/atomic notify all") (C++20) | notifies all threads blocked in atomic\_wait (function template) | cpp std::atomic_ref<T>::exchange std::atomic\_ref<T>::exchange ============================= | | | | | --- | --- | --- | | ``` T exchange( T desired, std::memory_order order = std::memory_order_seq_cst ) const noexcept; ``` | | (since C++20) | Atomically replaces the value of the referenced object with `desired`. The operation is a read-modify-write operation. Memory is affected according to the value of `order`. ### Parameters | | | | | --- | --- | --- | | desired | - | value to assign | | order | - | memory order constraints to enforce | ### Return value The value of the referenced object before the call. cpp std::multiset std::multiset ============= | Defined in header `[<set>](../header/set "cpp/header/set")` | | | | --- | --- | --- | | ``` template< class Key, class Compare = std::less<Key>, class Allocator = std::allocator<Key> > class multiset; ``` | (1) | | | ``` namespace pmr { template <class Key, class Compare = std::less<Key>> using multiset = std::multiset<Key, Compare, std::pmr::polymorphic_allocator<Key>>; } ``` | (2) | (since C++17) | `std::multiset` is an associative container that contains a sorted set of objects of type Key. Unlike set, multiple keys with equivalent values are allowed. Sorting is done using the key comparison function Compare. Search, insertion, and removal operations have logarithmic complexity. Everywhere the standard library uses the [Compare](../named_req/compare "cpp/named req/Compare") requirements, equivalence is determined by using the equivalence relation as described on [Compare](../named_req/compare "cpp/named req/Compare"). In imprecise terms, two objects `a` and `b` are considered equivalent if neither compares less than the other: `!comp(a, b) && !comp(b, a)`. The order of the elements that compare equivalent is the order of insertion and does not change. (since C++11). `std::multiset` meets the requirements of [Container](../named_req/container "cpp/named req/Container"), [AllocatorAwareContainer](../named_req/allocatorawarecontainer "cpp/named req/AllocatorAwareContainer"), [AssociativeContainer](../named_req/associativecontainer "cpp/named req/AssociativeContainer") and [ReversibleContainer](../named_req/reversiblecontainer "cpp/named req/ReversibleContainer"). ### Member types | Member type | Definition | | --- | --- | | `key_type` | `Key` | | `value_type` | `Key` | | `size_type` | Unsigned integer type (usually `[std::size\_t](../types/size_t "cpp/types/size t")`) | | `difference_type` | Signed integer type (usually `[std::ptrdiff\_t](../types/ptrdiff_t "cpp/types/ptrdiff t")`) | | `key_compare` | `Compare` | | `value_compare` | `Compare` | | `allocator_type` | `Allocator` | | `reference` | `value_type&` | | `const_reference` | `const value_type&` | | `pointer` | | | | | --- | --- | | `Allocator::pointer` | (until C++11) | | `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<Allocator>::pointer` | (since C++11) | | | `const_pointer` | | | | | --- | --- | | `Allocator::const_pointer` | (until C++11) | | `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<Allocator>::const\_pointer` | (since C++11) | | | `iterator` | Constant [LegacyBidirectionalIterator](../named_req/bidirectionaliterator "cpp/named req/BidirectionalIterator") to `value_type` | | `const_iterator` | [LegacyBidirectionalIterator](../named_req/bidirectionaliterator "cpp/named req/BidirectionalIterator") to `const value_type` | | `reverse_iterator` | `[std::reverse\_iterator](http://en.cppreference.com/w/cpp/iterator/reverse_iterator)<iterator>` | | `const_reverse_iterator` | `[std::reverse\_iterator](http://en.cppreference.com/w/cpp/iterator/reverse_iterator)<const_iterator>` | | `node_type` (since C++17) | a specialization of [node handle](node_handle "cpp/container/node handle") representing a container node | ### Member functions | | | | --- | --- | | [(constructor)](multiset/multiset "cpp/container/multiset/multiset") | constructs the `multiset` (public member function) | | [(destructor)](multiset/~multiset "cpp/container/multiset/~multiset") | destructs the `multiset` (public member function) | | [operator=](multiset/operator= "cpp/container/multiset/operator=") | assigns values to the container (public member function) | | [get\_allocator](multiset/get_allocator "cpp/container/multiset/get allocator") | returns the associated allocator (public member function) | | Iterators | | [begin cbegin](multiset/begin "cpp/container/multiset/begin") (C++11) | returns an iterator to the beginning (public member function) | | [end cend](multiset/end "cpp/container/multiset/end") (C++11) | returns an iterator to the end (public member function) | | [rbegincrbegin](multiset/rbegin "cpp/container/multiset/rbegin") (C++11) | returns a reverse iterator to the beginning (public member function) | | [rendcrend](multiset/rend "cpp/container/multiset/rend") (C++11) | returns a reverse iterator to the end (public member function) | | Capacity | | [empty](multiset/empty "cpp/container/multiset/empty") | checks whether the container is empty (public member function) | | [size](multiset/size "cpp/container/multiset/size") | returns the number of elements (public member function) | | [max\_size](multiset/max_size "cpp/container/multiset/max size") | returns the maximum possible number of elements (public member function) | | Modifiers | | [clear](multiset/clear "cpp/container/multiset/clear") | clears the contents (public member function) | | [insert](multiset/insert "cpp/container/multiset/insert") | inserts elements or nodes (since C++17) (public member function) | | [emplace](multiset/emplace "cpp/container/multiset/emplace") (C++11) | constructs element in-place (public member function) | | [emplace\_hint](multiset/emplace_hint "cpp/container/multiset/emplace hint") (C++11) | constructs elements in-place using a hint (public member function) | | [erase](multiset/erase "cpp/container/multiset/erase") | erases elements (public member function) | | [swap](multiset/swap "cpp/container/multiset/swap") | swaps the contents (public member function) | | [extract](multiset/extract "cpp/container/multiset/extract") (C++17) | extracts nodes from the container (public member function) | | [merge](multiset/merge "cpp/container/multiset/merge") (C++17) | splices nodes from another container (public member function) | | Lookup | | [count](multiset/count "cpp/container/multiset/count") | returns the number of elements matching specific key (public member function) | | [find](multiset/find "cpp/container/multiset/find") | finds element with specific key (public member function) | | [contains](multiset/contains "cpp/container/multiset/contains") (C++20) | checks if the container contains element with specific key (public member function) | | [equal\_range](multiset/equal_range "cpp/container/multiset/equal range") | returns range of elements matching a specific key (public member function) | | [lower\_bound](multiset/lower_bound "cpp/container/multiset/lower bound") | returns an iterator to the first element *not less* than the given key (public member function) | | [upper\_bound](multiset/upper_bound "cpp/container/multiset/upper bound") | returns an iterator to the first element *greater* than the given key (public member function) | | Observers | | [key\_comp](multiset/key_comp "cpp/container/multiset/key comp") | returns the function that compares keys (public member function) | | [value\_comp](multiset/value_comp "cpp/container/multiset/value comp") | returns the function that compares keys in objects of type value\_type (public member function) | ### Non-member functions | | | | --- | --- | | [operator==operator!=operator<operator<=operator>operator>=operator<=>](multiset/operator_cmp "cpp/container/multiset/operator cmp") (removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(C++20) | lexicographically compares the values in the multiset (function template) | | [std::swap(std::multiset)](multiset/swap2 "cpp/container/multiset/swap2") | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | | [erase\_if(std::multiset)](multiset/erase_if "cpp/container/multiset/erase if") (C++20) | Erases all elements satisfying specific criteria (function template) | ### [Deduction guides](multiset/deduction_guides "cpp/container/multiset/deduction guides")(since C++17) ### Notes The member types `iterator` and `const_iterator` may be aliases to the same type. This means defining a pair of function overloads using the two types as parameter types may violate the [One Definition Rule](../language/definition#One_Definition_Rule "cpp/language/definition"). Since `iterator` is convertible to `const_iterator`, a single function with a `const_iterator` as parameter type will work instead. ### Defect Reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 103](https://cplusplus.github.io/LWG/issue103) | C++98 | iterator allows modification of keys | iterator made constant |
programming_docs
cpp std::vector std::vector =========== | Defined in header `[<vector>](../header/vector "cpp/header/vector")` | | | | --- | --- | --- | | ``` template< class T, class Allocator = std::allocator<T> > class vector; ``` | (1) | | | ``` namespace pmr { template< class T > using vector = std::vector<T, std::pmr::polymorphic_allocator<T>>; } ``` | (2) | (since C++17) | 1) `std::vector` is a sequence container that encapsulates dynamic size arrays. 2) `std::pmr::vector` is an alias template that uses a [polymorphic allocator](../memory/polymorphic_allocator "cpp/memory/polymorphic allocator"). The elements are stored contiguously, which means that elements can be accessed not only through iterators, but also using offsets to regular pointers to elements. This means that a pointer to an element of a vector may be passed to any function that expects a pointer to an element of an array. The storage of the vector is handled automatically, being expanded and contracted as needed. Vectors usually occupy more space than static arrays, because more memory is allocated to handle future growth. This way a vector does not need to reallocate each time an element is inserted, but only when the additional memory is exhausted. The total amount of allocated memory can be queried using `[capacity()](vector/capacity "cpp/container/vector/capacity")` function. Extra memory can be returned to the system via a call to `[shrink\_to\_fit()](vector/shrink_to_fit "cpp/container/vector/shrink to fit")`. (since C++11). Reallocations are usually costly operations in terms of performance. The `[reserve()](vector/reserve "cpp/container/vector/reserve")` function can be used to eliminate reallocations if the number of elements is known beforehand. The complexity (efficiency) of common operations on vectors is as follows: * Random access - constant 𝓞(1) * Insertion or removal of elements at the end - amortized constant 𝓞(1) * Insertion or removal of elements - linear in the distance to the end of the vector 𝓞(n) `std::vector` (for `T` other than `bool`) meets the requirements of [Container](../named_req/container "cpp/named req/Container"), [AllocatorAwareContainer](../named_req/allocatorawarecontainer "cpp/named req/AllocatorAwareContainer"), [SequenceContainer](../named_req/sequencecontainer "cpp/named req/SequenceContainer") , [ContiguousContainer](../named_req/contiguouscontainer "cpp/named req/ContiguousContainer") (since C++17) and [ReversibleContainer](../named_req/reversiblecontainer "cpp/named req/ReversibleContainer"). | | | | --- | --- | | Member functions of `std::vector` are `constexpr`: it is possible to create and use `std::vector` objects in the evaluation of a constant expression. However, `std::vector` objects generally cannot be `constexpr`, because any dynamically allocated storage must be released in the same evaluation of constant expression. | (since C++20) | ### Template parameters | | | | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | T | - | The type of the elements. | | | | --- | --- | | `T` must meet the requirements of [CopyAssignable](../named_req/copyassignable "cpp/named req/CopyAssignable") and [CopyConstructible](../named_req/copyconstructible "cpp/named req/CopyConstructible"). | (until C++11) | | The requirements that are imposed on the elements depend on the actual operations performed on the container. Generally, it is required that element type is a complete type and meets the requirements of [Erasable](../named_req/erasable "cpp/named req/Erasable"), but many member functions impose stricter requirements. | (since C++11)(until C++17) | | The requirements that are imposed on the elements depend on the actual operations performed on the container. Generally, it is required that element type meets the requirements of [Erasable](../named_req/erasable "cpp/named req/Erasable"), but many member functions impose stricter requirements. This container (but not its members) can be instantiated with an incomplete element type if the allocator satisfies the [allocator completeness requirements](../named_req/allocator#Allocator_completeness_requirements "cpp/named req/Allocator"). | [Feature-test](../utility/feature_test "cpp/utility/feature test") macro | | --- | | [`__cpp_lib_incomplete_container_elements`](../feature_test#Library_features "cpp/feature test") | | (since C++17) | | | Allocator | - | An allocator that is used to acquire/release memory and to construct/destroy the elements in that memory. The type must meet the requirements of [Allocator](../named_req/allocator "cpp/named req/Allocator"). The behavior is undefined (until C++20)The program is ill-formed (since C++20) if `Allocator::value_type` is not the same as `T`. | ### Specializations The standard library provides a specialization of `std::vector` for the type `bool`, which may be optimized for space efficiency. | | | | --- | --- | | [vector<bool>](vector_bool "cpp/container/vector bool") | space-efficient dynamic bitset (class template specialization) | ### Iterator invalidation | Operations | Invalidated | | --- | --- | | All read only operations | Never | | `[swap](vector/swap "cpp/container/vector/swap")`, `[std::swap](../algorithm/swap "cpp/algorithm/swap")` | `[end()](vector/end "cpp/container/vector/end")` | | `[clear](vector/clear "cpp/container/vector/clear")`, `[operator=](vector/operator= "cpp/container/vector/operator=")`, `[assign](vector/assign "cpp/container/vector/assign")` | Always | | `[reserve](vector/reserve "cpp/container/vector/reserve")`, `[shrink\_to\_fit](vector/shrink_to_fit "cpp/container/vector/shrink to fit")` | If the vector changed capacity, all of them. If not, none. | | `[erase](vector/erase "cpp/container/vector/erase")` | Erased elements and all elements after them (including `[end()](vector/end "cpp/container/vector/end")`) | | `[push\_back](vector/push_back "cpp/container/vector/push back")`, `[emplace\_back](vector/emplace_back "cpp/container/vector/emplace back")` | If the vector changed capacity, all of them. If not, only `[end()](vector/end "cpp/container/vector/end")`. | | `[insert](vector/insert "cpp/container/vector/insert")`, `[emplace](vector/emplace "cpp/container/vector/emplace")` | If the vector changed capacity, all of them. If not, only those at or after the insertion point (including `[end()](vector/end "cpp/container/vector/end")`). | | `[resize](vector/resize "cpp/container/vector/resize")` | If the vector changed capacity, all of them. If not, only `[end()](vector/end "cpp/container/vector/end")` and any elements erased. | | `[pop\_back](vector/pop_back "cpp/container/vector/pop back")` | The element erased and `[end()](vector/end "cpp/container/vector/end")`. | ### Member types | Member type | Definition | | --- | --- | | `value_type` | `T` | | `allocator_type` | `Allocator` | | `size_type` | Unsigned integer type (usually `[std::size\_t](../types/size_t "cpp/types/size t")`) | | `difference_type` | Signed integer type (usually `[std::ptrdiff\_t](../types/ptrdiff_t "cpp/types/ptrdiff t")`) | | `reference` | `value_type&` | | `const_reference` | `const value_type&` | | `pointer` | | | | | --- | --- | | `Allocator::pointer` | (until C++11) | | `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<Allocator>::pointer` | (since C++11) | | | `const_pointer` | | | | | --- | --- | | `Allocator::const_pointer` | (until C++11) | | `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<Allocator>::const\_pointer` | (since C++11) | | | `iterator` | | | | | --- | --- | | [LegacyRandomAccessIterator](../named_req/randomaccessiterator "cpp/named req/RandomAccessIterator") and [LegacyContiguousIterator](../named_req/contiguousiterator "cpp/named req/ContiguousIterator") to `value_type`. | (until C++20) | | [LegacyRandomAccessIterator](../named_req/randomaccessiterator "cpp/named req/RandomAccessIterator"), [`contiguous_iterator`](../iterator/contiguous_iterator "cpp/iterator/contiguous iterator"), and [ConstexprIterator](../named_req/constexpriterator "cpp/named req/ConstexprIterator") to `value_type`. | (since C++20) | | | `const_iterator` | | | | | --- | --- | | [LegacyRandomAccessIterator](../named_req/randomaccessiterator "cpp/named req/RandomAccessIterator") and [LegacyContiguousIterator](../named_req/contiguousiterator "cpp/named req/ContiguousIterator") to `const value_type`. | (until C++20) | | [LegacyRandomAccessIterator](../named_req/randomaccessiterator "cpp/named req/RandomAccessIterator"), [`contiguous_iterator`](../iterator/contiguous_iterator "cpp/iterator/contiguous iterator"), and [ConstexprIterator](../named_req/constexpriterator "cpp/named req/ConstexprIterator") to `const value_type`. | (since C++20) | | | `reverse_iterator` | `[std::reverse\_iterator](http://en.cppreference.com/w/cpp/iterator/reverse_iterator)<iterator>` | | `const_reverse_iterator` | `[std::reverse\_iterator](http://en.cppreference.com/w/cpp/iterator/reverse_iterator)<const_iterator>` | ### Member functions | | | | --- | --- | | [(constructor)](vector/vector "cpp/container/vector/vector") | constructs the `vector` (public member function) | | [(destructor)](vector/~vector "cpp/container/vector/~vector") | destructs the `vector` (public member function) | | [operator=](vector/operator= "cpp/container/vector/operator=") | assigns values to the container (public member function) | | [assign](vector/assign "cpp/container/vector/assign") | assigns values to the container (public member function) | | [get\_allocator](vector/get_allocator "cpp/container/vector/get allocator") | returns the associated allocator (public member function) | | Element access | | [at](vector/at "cpp/container/vector/at") | access specified element with bounds checking (public member function) | | [operator[]](vector/operator_at "cpp/container/vector/operator at") | access specified element (public member function) | | [front](vector/front "cpp/container/vector/front") | access the first element (public member function) | | [back](vector/back "cpp/container/vector/back") | access the last element (public member function) | | [data](vector/data "cpp/container/vector/data") | direct access to the underlying array (public member function) | | Iterators | | [begin cbegin](vector/begin "cpp/container/vector/begin") (C++11) | returns an iterator to the beginning (public member function) | | [end cend](vector/end "cpp/container/vector/end") (C++11) | returns an iterator to the end (public member function) | | [rbegincrbegin](vector/rbegin "cpp/container/vector/rbegin") (C++11) | returns a reverse iterator to the beginning (public member function) | | [rendcrend](vector/rend "cpp/container/vector/rend") (C++11) | returns a reverse iterator to the end (public member function) | | Capacity | | [empty](vector/empty "cpp/container/vector/empty") | checks whether the container is empty (public member function) | | [size](vector/size "cpp/container/vector/size") | returns the number of elements (public member function) | | [max\_size](vector/max_size "cpp/container/vector/max size") | returns the maximum possible number of elements (public member function) | | [reserve](vector/reserve "cpp/container/vector/reserve") | reserves storage (public member function) | | [capacity](vector/capacity "cpp/container/vector/capacity") | returns the number of elements that can be held in currently allocated storage (public member function) | | [shrink\_to\_fit](vector/shrink_to_fit "cpp/container/vector/shrink to fit") (C++11) | reduces memory usage by freeing unused memory (public member function) | | Modifiers | | [clear](vector/clear "cpp/container/vector/clear") | clears the contents (public member function) | | [insert](vector/insert "cpp/container/vector/insert") | inserts elements (public member function) | | [emplace](vector/emplace "cpp/container/vector/emplace") (C++11) | constructs element in-place (public member function) | | [erase](vector/erase "cpp/container/vector/erase") | erases elements (public member function) | | [push\_back](vector/push_back "cpp/container/vector/push back") | adds an element to the end (public member function) | | [emplace\_back](vector/emplace_back "cpp/container/vector/emplace back") (C++11) | constructs an element in-place at the end (public member function) | | [pop\_back](vector/pop_back "cpp/container/vector/pop back") | removes the last element (public member function) | | [resize](vector/resize "cpp/container/vector/resize") | changes the number of elements stored (public member function) | | [swap](vector/swap "cpp/container/vector/swap") | swaps the contents (public member function) | ### Non-member functions | | | | --- | --- | | [operator==operator!=operator<operator<=operator>operator>=operator<=>](vector/operator_cmp "cpp/container/vector/operator cmp") (removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(C++20) | lexicographically compares the values in the vector (function template) | | [std::swap(std::vector)](vector/swap2 "cpp/container/vector/swap2") | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | | [erase(std::vector)erase\_if(std::vector)](vector/erase2 "cpp/container/vector/erase2") (C++20) | Erases all elements satisfying specific criteria (function template) | ### [Deduction guides](vector/deduction_guides "cpp/container/vector/deduction guides")(since C++17) ### Example ``` #include <iostream> #include <vector> int main() { // Create a vector containing integers std::vector<int> v = { 7, 5, 16, 8 }; // Add two more integers to vector v.push_back(25); v.push_back(13); // Print out the vector std::cout << "v = { "; for (int n : v) { std::cout << n << ", "; } std::cout << "}; \n"; } ``` Output: ``` v = { 7, 5, 16, 8, 25, 13, }; ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 69](https://cplusplus.github.io/LWG/issue69) | C++98 | contiguity of the storage for elements of `vector` was not required | required | | [LWG 464](https://cplusplus.github.io/LWG/issue464) | C++98 | access to the underlying storage of an empty `vector` resulted in UB | `data` function provided | cpp std::map std::map ======== | Defined in header `[<map>](../header/map "cpp/header/map")` | | | | --- | --- | --- | | ``` template< class Key, class T, class Compare = std::less<Key>, class Allocator = std::allocator<std::pair<const Key, T> > > class map; ``` | (1) | | | ``` namespace pmr { template <class Key, class T, class Compare = std::less<Key>> using map = std::map<Key, T, Compare, std::pmr::polymorphic_allocator<std::pair<const Key,T>>> } ``` | (2) | (since C++17) | `std::map` is a sorted associative container that contains key-value pairs with unique keys. Keys are sorted by using the comparison function `Compare`. Search, removal, and insertion operations have logarithmic complexity. Maps are usually implemented as [red-black trees](https://en.wikipedia.org/wiki/Red%E2%80%93black_tree "enwiki:Red–black tree"). Everywhere the standard library uses the [Compare](../named_req/compare "cpp/named req/Compare") requirements, uniqueness is determined by using the equivalence relation. In imprecise terms, two objects `a` and `b` are considered equivalent (not unique) if neither compares less than the other: `!comp(a, b) && !comp(b, a)`. `std::map` meets the requirements of [Container](../named_req/container "cpp/named req/Container"), [AllocatorAwareContainer](../named_req/allocatorawarecontainer "cpp/named req/AllocatorAwareContainer"), [AssociativeContainer](../named_req/associativecontainer "cpp/named req/AssociativeContainer") and [ReversibleContainer](../named_req/reversiblecontainer "cpp/named req/ReversibleContainer"). ### Member types | Member type | Definition | | --- | --- | | `key_type` | `Key` | | `mapped_type` | `T` | | `value_type` | `[std::pair](http://en.cppreference.com/w/cpp/utility/pair)<const Key, T>` | | `size_type` | Unsigned integer type (usually `[std::size\_t](../types/size_t "cpp/types/size t")`) | | `difference_type` | Signed integer type (usually `[std::ptrdiff\_t](../types/ptrdiff_t "cpp/types/ptrdiff t")`) | | `key_compare` | `Compare` | | `allocator_type` | `Allocator` | | `reference` | `value_type&` | | `const_reference` | `const value_type&` | | `pointer` | | | | | --- | --- | | `Allocator::pointer` | (until C++11) | | `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<Allocator>::pointer` | (since C++11) | | | `const_pointer` | | | | | --- | --- | | `Allocator::const_pointer` | (until C++11) | | `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<Allocator>::const\_pointer` | (since C++11) | | | `iterator` | [LegacyBidirectionalIterator](../named_req/bidirectionaliterator "cpp/named req/BidirectionalIterator") to `value_type` | | `const_iterator` | [LegacyBidirectionalIterator](../named_req/bidirectionaliterator "cpp/named req/BidirectionalIterator") to `const value_type` | | `reverse_iterator` | `[std::reverse\_iterator](http://en.cppreference.com/w/cpp/iterator/reverse_iterator)<iterator>` | | `const_reverse_iterator` | `[std::reverse\_iterator](http://en.cppreference.com/w/cpp/iterator/reverse_iterator)<const_iterator>` | | `node_type` (since C++17) | a specialization of [node handle](node_handle "cpp/container/node handle") representing a container node | | `insert_return_type` (since C++17) | type describing the result of inserting a `node_type`, a specialization of `template <class Iter, class NodeType> struct /*unspecified*/ { Iter position; bool inserted; NodeType node; };` instantiated with template arguments `iterator` and `node_type`. | ### Member classes | | | | --- | --- | | [value\_compare](map/value_compare "cpp/container/map/value compare") | compares objects of type `value_type` (class) | ### Member functions | | | | --- | --- | | [(constructor)](map/map "cpp/container/map/map") | constructs the `map` (public member function) | | [(destructor)](map/~map "cpp/container/map/~map") | destructs the `map` (public member function) | | [operator=](map/operator= "cpp/container/map/operator=") | assigns values to the container (public member function) | | [get\_allocator](map/get_allocator "cpp/container/map/get allocator") | returns the associated allocator (public member function) | | Element access | | [at](map/at "cpp/container/map/at") | access specified element with bounds checking (public member function) | | [operator[]](map/operator_at "cpp/container/map/operator at") | access or insert specified element (public member function) | | Iterators | | [begin cbegin](map/begin "cpp/container/map/begin") (C++11) | returns an iterator to the beginning (public member function) | | [end cend](map/end "cpp/container/map/end") (C++11) | returns an iterator to the end (public member function) | | [rbegincrbegin](map/rbegin "cpp/container/map/rbegin") (C++11) | returns a reverse iterator to the beginning (public member function) | | [rendcrend](map/rend "cpp/container/map/rend") (C++11) | returns a reverse iterator to the end (public member function) | | Capacity | | [empty](map/empty "cpp/container/map/empty") | checks whether the container is empty (public member function) | | [size](map/size "cpp/container/map/size") | returns the number of elements (public member function) | | [max\_size](map/max_size "cpp/container/map/max size") | returns the maximum possible number of elements (public member function) | | Modifiers | | [clear](map/clear "cpp/container/map/clear") | clears the contents (public member function) | | [insert](map/insert "cpp/container/map/insert") | inserts elements or nodes (since C++17) (public member function) | | [insert\_or\_assign](map/insert_or_assign "cpp/container/map/insert or assign") (C++17) | inserts an element or assigns to the current element if the key already exists (public member function) | | [emplace](map/emplace "cpp/container/map/emplace") (C++11) | constructs element in-place (public member function) | | [emplace\_hint](map/emplace_hint "cpp/container/map/emplace hint") (C++11) | constructs elements in-place using a hint (public member function) | | [try\_emplace](map/try_emplace "cpp/container/map/try emplace") (C++17) | inserts in-place if the key does not exist, does nothing if the key exists (public member function) | | [erase](map/erase "cpp/container/map/erase") | erases elements (public member function) | | [swap](map/swap "cpp/container/map/swap") | swaps the contents (public member function) | | [extract](map/extract "cpp/container/map/extract") (C++17) | extracts nodes from the container (public member function) | | [merge](map/merge "cpp/container/map/merge") (C++17) | splices nodes from another container (public member function) | | Lookup | | [count](map/count "cpp/container/map/count") | returns the number of elements matching specific key (public member function) | | [find](map/find "cpp/container/map/find") | finds element with specific key (public member function) | | [contains](map/contains "cpp/container/map/contains") (C++20) | checks if the container contains element with specific key (public member function) | | [equal\_range](map/equal_range "cpp/container/map/equal range") | returns range of elements matching a specific key (public member function) | | [lower\_bound](map/lower_bound "cpp/container/map/lower bound") | returns an iterator to the first element *not less* than the given key (public member function) | | [upper\_bound](map/upper_bound "cpp/container/map/upper bound") | returns an iterator to the first element *greater* than the given key (public member function) | | Observers | | [key\_comp](map/key_comp "cpp/container/map/key comp") | returns the function that compares keys (public member function) | | [value\_comp](map/value_comp "cpp/container/map/value comp") | returns the function that compares keys in objects of type value\_type (public member function) | ### Non-member functions | | | | --- | --- | | [operator==operator!=operator<operator<=operator>operator>=operator<=>](map/operator_cmp "cpp/container/map/operator cmp") (removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(C++20) | lexicographically compares the values in the map (function template) | | [std::swap(std::map)](map/swap2 "cpp/container/map/swap2") | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | | [erase\_if(std::map)](map/erase_if "cpp/container/map/erase if") (C++20) | Erases all elements satisfying specific criteria (function template) | ### [Deduction guides](map/deduction_guides "cpp/container/map/deduction guides") (since C++17) ### Example ``` #include <iostream> #include <map> #include <string> #include <string_view> void print_map(std::string_view comment, const std::map<std::string, int>& m) { std::cout << comment ; // iterate using C++17 facilities for (const auto& [key, value] : m) { std::cout << '[' << key << "] = " << value << "; "; } // C++11 alternative: // for (const auto& n : m) { // std::cout << n.first << " = " << n.second << "; "; // } // C++98 alternative // for (std::map<std::string, int>::const_iterator it = m.begin(); it != m.end(); it++) { // std::cout << it->first << " = " << it->second << "; "; // } std::cout << '\n'; } int main() { // Create a map of three (strings, int) pairs std::map<std::string, int> m { {"CPU", 10}, {"GPU", 15}, {"RAM", 20}, }; print_map("1) Initial map: ", m); m["CPU"] = 25; // update an existing value m["SSD"] = 30; // insert a new value print_map("2) Updated map: ", m); // using operator[] with non-existent key always performs an insert std::cout << "3) m[UPS] = " << m["UPS"] << '\n'; print_map("4) Updated map: ", m); m.erase("GPU"); print_map("5) After erase: ", m); std::erase_if(m, [](const auto& pair){ return pair.second > 25; }); print_map("6) After erase: ", m); std::cout << "7) m.size() = " << m.size() << '\n'; m.clear(); std::cout << std::boolalpha << "8) Map is empty: " << m.empty() << '\n'; } ``` Output: ``` 1) Initial map: [CPU] = 10; [GPU] = 15; [RAM] = 20; 2) Updated map: [CPU] = 25; [GPU] = 15; [RAM] = 20; [SSD] = 30; 3) m[UPS] = 0 4) Updated map: [CPU] = 25; [GPU] = 15; [RAM] = 20; [SSD] = 30; [UPS] = 0; 5) After erase: [CPU] = 25; [RAM] = 20; [SSD] = 30; [UPS] = 0; 6) After erase: [CPU] = 25; [RAM] = 20; [UPS] = 0; 7) m.size() = 3 8) Map is empty: true ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 464](https://cplusplus.github.io/LWG/issue464) | C++98 | accessing a const `map` by key was inconvenient | `at` function provided | ### See also | | | | --- | --- | | [unordered\_map](unordered_map "cpp/container/unordered map") (C++11) | collection of key-value pairs, hashed by keys, keys are unique (class template) |
programming_docs
cpp std::forward_list std::forward\_list ================== | Defined in header `[<forward\_list>](../header/forward_list "cpp/header/forward list")` | | | | --- | --- | --- | | ``` template< class T, class Allocator = std::allocator<T> > class forward_list; ``` | (1) | (since C++11) | | ``` namespace pmr { template <class T> using forward_list = std::forward_list<T, std::pmr::polymorphic_allocator<T>>; } ``` | (2) | (since C++17) | `std::forward_list` is a container that supports fast insertion and removal of elements from anywhere in the container. Fast random access is not supported. It is implemented as a singly-linked list. Compared to `[std::list](list "cpp/container/list")` this container provides more space efficient storage when bidirectional iteration is not needed. Adding, removing and moving the elements within the list, or across several lists, does not invalidate the iterators currently referring to other elements in the list. However, an iterator or reference referring to an element is invalidated when the corresponding element is removed (via `[erase\_after](forward_list/erase_after "cpp/container/forward list/erase after")`) from the list. `std::forward_list` meets the requirements of [Container](../named_req/container "cpp/named req/Container") (except for the `size` member function and that `operator==`'s complexity is always linear), [AllocatorAwareContainer](../named_req/allocatorawarecontainer "cpp/named req/AllocatorAwareContainer") and [SequenceContainer](../named_req/sequencecontainer "cpp/named req/SequenceContainer"). ### Template parameters | | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | --- | | T | - | The type of the elements. | | | | --- | --- | | The requirements that are imposed on the elements depend on the actual operations performed on the container. Generally, it is required that element type is a complete type and meets the requirements of [Erasable](../named_req/erasable "cpp/named req/Erasable"), but many member functions impose stricter requirements. | (until C++17) | | The requirements that are imposed on the elements depend on the actual operations performed on the container. Generally, it is required that element type meets the requirements of [Erasable](../named_req/erasable "cpp/named req/Erasable"), but many member functions impose stricter requirements. This container (but not its members) can be instantiated with an incomplete element type if the allocator satisfies the [allocator completeness requirements](../named_req/allocator#Allocator_completeness_requirements "cpp/named req/Allocator"). | [Feature-test](../utility/feature_test "cpp/utility/feature test") macro | | --- | | [`__cpp_lib_incomplete_container_elements`](../feature_test#Library_features "cpp/feature test") | | (since C++17) | | | Allocator | - | An allocator that is used to acquire/release memory and to construct/destroy the elements in that memory. The type must meet the requirements of [Allocator](../named_req/allocator "cpp/named req/Allocator"). The behavior is undefined (until C++20)The program is ill-formed (since C++20) if `Allocator::value_type` is not the same as `T`. | ### Member types | Member type | Definition | | --- | --- | | `value_type` | `T` | | `allocator_type` | `Allocator` | | `size_type` | Unsigned integer type (usually `[std::size\_t](../types/size_t "cpp/types/size t")`) | | `difference_type` | Signed integer type (usually `[std::ptrdiff\_t](../types/ptrdiff_t "cpp/types/ptrdiff t")`) | | `reference` | `value_type&` | | `const_reference` | `const value_type&` | | `pointer` | `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<Allocator>::pointer` | | `const_pointer` | `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<Allocator>::const\_pointer` | | `iterator` | [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator") to `value_type` | | `const_iterator` | [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator") to `const value_type` | ### Member functions | | | | --- | --- | | [(constructor)](forward_list/forward_list "cpp/container/forward list/forward list") (C++11) | constructs the `forward_list` (public member function) | | [(destructor)](forward_list/~forward_list "cpp/container/forward list/~forward list") (C++11) | destructs the `forward_list` (public member function) | | [operator=](forward_list/operator= "cpp/container/forward list/operator=") (C++11) | assigns values to the container (public member function) | | [assign](forward_list/assign "cpp/container/forward list/assign") (C++11) | assigns values to the container (public member function) | | [get\_allocator](forward_list/get_allocator "cpp/container/forward list/get allocator") (C++11) | returns the associated allocator (public member function) | | Element access | | [front](forward_list/front "cpp/container/forward list/front") (C++11) | access the first element (public member function) | | Iterators | | [before\_begincbefore\_begin](forward_list/before_begin "cpp/container/forward list/before begin") (C++11) | returns an iterator to the element before beginning (public member function) | | [begin cbegin](forward_list/begin "cpp/container/forward list/begin") (C++11) | returns an iterator to the beginning (public member function) | | [end cend](forward_list/end "cpp/container/forward list/end") (C++11) | returns an iterator to the end (public member function) | | Capacity | | [empty](forward_list/empty "cpp/container/forward list/empty") (C++11) | checks whether the container is empty (public member function) | | [max\_size](forward_list/max_size "cpp/container/forward list/max size") (C++11) | returns the maximum possible number of elements (public member function) | | Modifiers | | [clear](forward_list/clear "cpp/container/forward list/clear") (C++11) | clears the contents (public member function) | | [insert\_after](forward_list/insert_after "cpp/container/forward list/insert after") (C++11) | inserts elements after an element (public member function) | | [emplace\_after](forward_list/emplace_after "cpp/container/forward list/emplace after") (C++11) | constructs elements in-place after an element (public member function) | | [erase\_after](forward_list/erase_after "cpp/container/forward list/erase after") (C++11) | erases an element after an element (public member function) | | [push\_front](forward_list/push_front "cpp/container/forward list/push front") (C++11) | inserts an element to the beginning (public member function) | | [emplace\_front](forward_list/emplace_front "cpp/container/forward list/emplace front") (C++11) | constructs an element in-place at the beginning (public member function) | | [pop\_front](forward_list/pop_front "cpp/container/forward list/pop front") (C++11) | removes the first element (public member function) | | [resize](forward_list/resize "cpp/container/forward list/resize") (C++11) | changes the number of elements stored (public member function) | | [swap](forward_list/swap "cpp/container/forward list/swap") (C++11) | swaps the contents (public member function) | | Operations | | [merge](forward_list/merge "cpp/container/forward list/merge") (C++11) | merges two sorted lists (public member function) | | [splice\_after](forward_list/splice_after "cpp/container/forward list/splice after") (C++11) | moves elements from another `forward_list` (public member function) | | [removeremove\_if](forward_list/remove "cpp/container/forward list/remove") (C++11) | removes elements satisfying specific criteria (public member function) | | [reverse](forward_list/reverse "cpp/container/forward list/reverse") (C++11) | reverses the order of the elements (public member function) | | [unique](forward_list/unique "cpp/container/forward list/unique") (C++11) | removes consecutive duplicate elements (public member function) | | [sort](forward_list/sort "cpp/container/forward list/sort") (C++11) | sorts the elements (public member function) | ### Non-member functions | | | | --- | --- | | [operator==operator!=operator<operator<=operator>operator>=operator<=>](forward_list/operator_cmp "cpp/container/forward list/operator cmp") (removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(C++20) | lexicographically compares the values in the forward\_list (function template) | | [std::swap(std::forward\_list)](forward_list/swap2 "cpp/container/forward list/swap2") (C++11) | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | | [erase(std::forward\_list)erase\_if(std::forward\_list)](forward_list/erase2 "cpp/container/forward list/erase2") (C++20) | Erases all elements satisfying specific criteria (function template) | ### [Deduction guides](forward_list/deduction_guides "cpp/container/forward list/deduction guides")(since C++17) cpp std::list std::list ========= | Defined in header `[<list>](../header/list "cpp/header/list")` | | | | --- | --- | --- | | ``` template< class T, class Allocator = std::allocator<T> > class list; ``` | (1) | | | ``` namespace pmr { template <class T> using list = std::list<T, std::pmr::polymorphic_allocator<T>>; } ``` | (2) | (since C++17) | `std::list` is a container that supports constant time insertion and removal of elements from anywhere in the container. Fast random access is not supported. It is usually implemented as a doubly-linked list. Compared to `[std::forward\_list](forward_list "cpp/container/forward list")` this container provides bidirectional iteration capability while being less space efficient. Adding, removing and moving the elements within the list or across several lists does not invalidate the iterators or references. An iterator is invalidated only when the corresponding element is deleted. `std::list` meets the requirements of [Container](../named_req/container "cpp/named req/Container"), [AllocatorAwareContainer](../named_req/allocatorawarecontainer "cpp/named req/AllocatorAwareContainer"), [SequenceContainer](../named_req/sequencecontainer "cpp/named req/SequenceContainer") and [ReversibleContainer](../named_req/reversiblecontainer "cpp/named req/ReversibleContainer"). ### Template parameters | | | | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | T | - | The type of the elements. | | | | --- | --- | | `T` must meet the requirements of [CopyAssignable](../named_req/copyassignable "cpp/named req/CopyAssignable") and [CopyConstructible](../named_req/copyconstructible "cpp/named req/CopyConstructible"). | (until C++11) | | The requirements that are imposed on the elements depend on the actual operations performed on the container. Generally, it is required that element type is a complete type and meets the requirements of [Erasable](../named_req/erasable "cpp/named req/Erasable"), but many member functions impose stricter requirements. | (since C++11)(until C++17) | | The requirements that are imposed on the elements depend on the actual operations performed on the container. Generally, it is required that element type meets the requirements of [Erasable](../named_req/erasable "cpp/named req/Erasable"), but many member functions impose stricter requirements. This container (but not its members) can be instantiated with an incomplete element type if the allocator satisfies the [allocator completeness requirements](../named_req/allocator#Allocator_completeness_requirements "cpp/named req/Allocator"). | [Feature-test](../utility/feature_test "cpp/utility/feature test") macro | | --- | | [`__cpp_lib_incomplete_container_elements`](../feature_test#Library_features "cpp/feature test") | | (since C++17) | | | Allocator | - | An allocator that is used to acquire/release memory and to construct/destroy the elements in that memory. The type must meet the requirements of [Allocator](../named_req/allocator "cpp/named req/Allocator"). The behavior is undefined (until C++20)The program is ill-formed (since C++20) if `Allocator::value_type` is not the same as `T`. | ### Member types | Member type | Definition | | --- | --- | | `value_type` | `T` | | `allocator_type` | `Allocator` | | `size_type` | Unsigned integer type (usually `[std::size\_t](../types/size_t "cpp/types/size t")`) | | `difference_type` | Signed integer type (usually `[std::ptrdiff\_t](../types/ptrdiff_t "cpp/types/ptrdiff t")`) | | `reference` | `value_type&` | | `const_reference` | `const value_type&` | | `pointer` | | | | | --- | --- | | `Allocator::pointer` | (until C++11) | | `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<Allocator>::pointer` | (since C++11) | | | `const_pointer` | | | | | --- | --- | | `Allocator::const_pointer` | (until C++11) | | `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<Allocator>::const\_pointer` | (since C++11) | | | `iterator` | [LegacyBidirectionalIterator](../named_req/bidirectionaliterator "cpp/named req/BidirectionalIterator") to `value_type` | | `const_iterator` | [LegacyBidirectionalIterator](../named_req/bidirectionaliterator "cpp/named req/BidirectionalIterator") to `const value_type` | | `reverse_iterator` | `[std::reverse\_iterator](http://en.cppreference.com/w/cpp/iterator/reverse_iterator)<iterator>` | | `const_reverse_iterator` | `[std::reverse\_iterator](http://en.cppreference.com/w/cpp/iterator/reverse_iterator)<const_iterator>` | ### Member functions | | | | --- | --- | | [(constructor)](list/list "cpp/container/list/list") | constructs the `list` (public member function) | | [(destructor)](list/~list "cpp/container/list/~list") | destructs the `list` (public member function) | | [operator=](list/operator= "cpp/container/list/operator=") | assigns values to the container (public member function) | | [assign](list/assign "cpp/container/list/assign") | assigns values to the container (public member function) | | [get\_allocator](list/get_allocator "cpp/container/list/get allocator") | returns the associated allocator (public member function) | | Element access | | [front](list/front "cpp/container/list/front") | access the first element (public member function) | | [back](list/back "cpp/container/list/back") | access the last element (public member function) | | Iterators | | [begin cbegin](list/begin "cpp/container/list/begin") (C++11) | returns an iterator to the beginning (public member function) | | [end cend](list/end "cpp/container/list/end") (C++11) | returns an iterator to the end (public member function) | | [rbegincrbegin](list/rbegin "cpp/container/list/rbegin") (C++11) | returns a reverse iterator to the beginning (public member function) | | [rendcrend](list/rend "cpp/container/list/rend") (C++11) | returns a reverse iterator to the end (public member function) | | Capacity | | [empty](list/empty "cpp/container/list/empty") | checks whether the container is empty (public member function) | | [size](list/size "cpp/container/list/size") | returns the number of elements (public member function) | | [max\_size](list/max_size "cpp/container/list/max size") | returns the maximum possible number of elements (public member function) | | Modifiers | | [clear](list/clear "cpp/container/list/clear") | clears the contents (public member function) | | [insert](list/insert "cpp/container/list/insert") | inserts elements (public member function) | | [emplace](list/emplace "cpp/container/list/emplace") (C++11) | constructs element in-place (public member function) | | [erase](list/erase "cpp/container/list/erase") | erases elements (public member function) | | [push\_back](list/push_back "cpp/container/list/push back") | adds an element to the end (public member function) | | [emplace\_back](list/emplace_back "cpp/container/list/emplace back") (C++11) | constructs an element in-place at the end (public member function) | | [pop\_back](list/pop_back "cpp/container/list/pop back") | removes the last element (public member function) | | [push\_front](list/push_front "cpp/container/list/push front") | inserts an element to the beginning (public member function) | | [emplace\_front](list/emplace_front "cpp/container/list/emplace front") (C++11) | constructs an element in-place at the beginning (public member function) | | [pop\_front](list/pop_front "cpp/container/list/pop front") | removes the first element (public member function) | | [resize](list/resize "cpp/container/list/resize") | changes the number of elements stored (public member function) | | [swap](list/swap "cpp/container/list/swap") | swaps the contents (public member function) | | Operations | | [merge](list/merge "cpp/container/list/merge") | merges two sorted lists (public member function) | | [splice](list/splice "cpp/container/list/splice") | moves elements from another `list` (public member function) | | [removeremove\_if](list/remove "cpp/container/list/remove") | removes elements satisfying specific criteria (public member function) | | [reverse](list/reverse "cpp/container/list/reverse") | reverses the order of the elements (public member function) | | [unique](list/unique "cpp/container/list/unique") | removes consecutive duplicate elements (public member function) | | [sort](list/sort "cpp/container/list/sort") | sorts the elements (public member function) | ### Non-member functions | | | | --- | --- | | [operator==operator!=operator<operator<=operator>operator>=operator<=>](list/operator_cmp "cpp/container/list/operator cmp") (removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(C++20) | lexicographically compares the values in the list (function template) | | [std::swap(std::list)](list/swap2 "cpp/container/list/swap2") | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | | [erase(std::list)erase\_if(std::list)](list/erase2 "cpp/container/list/erase2") (C++20) | Erases all elements satisfying specific criteria (function template) | ### [Deduction guides](list/deduction_guides "cpp/container/list/deduction guides")(since C++17) ### Example ``` #include <algorithm> #include <iostream> #include <list> int main() { // Create a list containing integers std::list<int> l = { 7, 5, 16, 8 }; // Add an integer to the front of the list l.push_front(25); // Add an integer to the back of the list l.push_back(13); // Insert an integer before 16 by searching auto it = std::find(l.begin(), l.end(), 16); if (it != l.end()) { l.insert(it, 42); } // Print out the list std::cout << "l = { "; for (int n : l) { std::cout << n << ", "; } std::cout << "};\n"; } ``` Output: ``` l = { 25, 7, 5, 42, 16, 8, 13, }; ``` cpp std::queue std::queue ========== | Defined in header `[<queue>](../header/queue "cpp/header/queue")` | | | | --- | --- | --- | | ``` template< class T, class Container = std::deque<T> > class queue; ``` | | | The `std::queue` class is a container adaptor that gives the programmer the functionality of a queue - specifically, a FIFO (first-in, first-out) data structure. The class template acts as a wrapper to the underlying container - only a specific set of functions is provided. The queue pushes the elements on the back of the underlying container and pops them from the front. ### Template parameters | | | | | --- | --- | --- | | T | - | The type of the stored elements. The behavior is undefined if `T` is not the same type as `Container::value_type`. (since C++17) | | Container | - | The type of the underlying container to use to store the elements. The container must satisfy the requirements of [SequenceContainer](../named_req/sequencecontainer "cpp/named req/SequenceContainer"). Additionally, it must provide the following functions with the usual semantics: * `back()` * `front()` * `push_back()` * `pop_front()` The standard containers `[std::deque](deque "cpp/container/deque")` and `[std::list](list "cpp/container/list")` satisfy these requirements. | ### Member types | Member type | Definition | | --- | --- | | `container_type` | `Container` | | `value_type` | `Container::value_type` | | `size_type` | `Container::size_type` | | `reference` | `Container::reference` | | `const_reference` | `Container::const_reference` | ### Member functions | | | | --- | --- | | [(constructor)](queue/queue "cpp/container/queue/queue") | constructs the `queue` (public member function) | | [(destructor)](queue/~queue "cpp/container/queue/~queue") | destructs the `queue` (public member function) | | [operator=](queue/operator= "cpp/container/queue/operator=") | assigns values to the container adaptor (public member function) | | Element access | | [front](queue/front "cpp/container/queue/front") | access the first element (public member function) | | [back](queue/back "cpp/container/queue/back") | access the last element (public member function) | | Capacity | | [empty](queue/empty "cpp/container/queue/empty") | checks whether the underlying container is empty (public member function) | | [size](queue/size "cpp/container/queue/size") | returns the number of elements (public member function) | | Modifiers | | [push](queue/push "cpp/container/queue/push") | inserts element at the end (public member function) | | [emplace](queue/emplace "cpp/container/queue/emplace") (C++11) | constructs element in-place at the end (public member function) | | [pop](queue/pop "cpp/container/queue/pop") | removes the first element (public member function) | | [swap](queue/swap "cpp/container/queue/swap") (C++11) | swaps the contents (public member function) | | Member objects | | Container c | the underlying container (protected member object) | ### Non-member functions | | | | --- | --- | | [operator==operator!=operator<operator<=operator>operator>=operator<=>](queue/operator_cmp "cpp/container/queue/operator cmp") (C++20) | lexicographically compares the values in the queue (function template) | | [std::swap(std::queue)](queue/swap2 "cpp/container/queue/swap2") (C++11) | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | ### Helper classes | | | | --- | --- | | [std::uses\_allocator<std::queue>](queue/uses_allocator "cpp/container/queue/uses allocator") (C++11) | specializes the `[std::uses\_allocator](../memory/uses_allocator "cpp/memory/uses allocator")` type trait (class template specialization) | ### [Deduction guides](queue/deduction_guides "cpp/container/queue/deduction guides")(since C++17) ### See also | | | | --- | --- | | [deque](deque "cpp/container/deque") | double-ended queue (class template) |
programming_docs
cpp std::priority_queue std::priority\_queue ==================== | Defined in header `[<queue>](../header/queue "cpp/header/queue")` | | | | --- | --- | --- | | ``` template< class T, class Container = std::vector<T>, class Compare = std::less<typename Container::value_type> > class priority_queue; ``` | | | A priority queue is a container adaptor that provides constant time lookup of the largest (by default) element, at the expense of logarithmic insertion and extraction. A user-provided `Compare` can be supplied to change the ordering, e.g. using `[std::greater](http://en.cppreference.com/w/cpp/utility/functional/greater)<T>` would cause the smallest element to appear as the `[top()](priority_queue/top "cpp/container/priority queue/top")`. Working with a `priority_queue` is similar to managing a [heap](../algorithm/make_heap "cpp/algorithm/make heap") in some random access container, with the benefit of not being able to accidentally invalidate the heap. ### Template parameters | | | | | --- | --- | --- | | T | - | The type of the stored elements. The behavior is undefined if `T` is not the same type as `Container::value_type`. (since C++17) | | Container | - | The type of the underlying container to use to store the elements. The container must satisfy the requirements of [SequenceContainer](../named_req/sequencecontainer "cpp/named req/SequenceContainer"), and its iterators must satisfy the requirements of [LegacyRandomAccessIterator](../named_req/randomaccessiterator "cpp/named req/RandomAccessIterator"). Additionally, it must provide the following functions with the usual semantics: * `front()` * `push_back()` * `pop_back()` The standard containers `[std::vector](vector "cpp/container/vector")` and `[std::deque](deque "cpp/container/deque")` satisfy these requirements. | | Compare | - | A [Compare](../named_req/compare "cpp/named req/Compare") type providing a strict weak ordering. Note that the [Compare](../named_req/compare "cpp/named req/Compare") parameter is defined such that it returns `true` if its first argument comes *before* its second argument in a weak ordering. But because the priority queue outputs largest elements first, the elements that "come before" are actually output last. That is, the front of the queue contains the "last" element according to the weak ordering imposed by [Compare](../named_req/compare "cpp/named req/Compare"). | ### Member types | Member type | Definition | | --- | --- | | `container_type` | `Container` | | `value_compare` | `Compare` | | `value_type` | `Container::value_type` | | `size_type` | `Container::size_type` | | `reference` | `Container::reference` | | `const_reference` | `Container::const_reference` | ### Member functions | | | | --- | --- | | [(constructor)](priority_queue/priority_queue "cpp/container/priority queue/priority queue") | constructs the `priority_queue` (public member function) | | [(destructor)](priority_queue/~priority_queue "cpp/container/priority queue/~priority queue") | destructs the `priority_queue` (public member function) | | [operator=](priority_queue/operator= "cpp/container/priority queue/operator=") | assigns values to the container adaptor (public member function) | | Element access | | [top](priority_queue/top "cpp/container/priority queue/top") | accesses the top element (public member function) | | Capacity | | [empty](priority_queue/empty "cpp/container/priority queue/empty") | checks whether the underlying container is empty (public member function) | | [size](priority_queue/size "cpp/container/priority queue/size") | returns the number of elements (public member function) | | Modifiers | | [push](priority_queue/push "cpp/container/priority queue/push") | inserts element and sorts the underlying container (public member function) | | [emplace](priority_queue/emplace "cpp/container/priority queue/emplace") (C++11) | constructs element in-place and sorts the underlying container (public member function) | | [pop](priority_queue/pop "cpp/container/priority queue/pop") | removes the top element (public member function) | | [swap](priority_queue/swap "cpp/container/priority queue/swap") (C++11) | swaps the contents (public member function) | | Member objects | | Container c | the underlying container (protected member object) | | Compare comp | the comparison function object (protected member object) | ### Non-member functions | | | | --- | --- | | [std::swap(std::priority\_queue)](priority_queue/swap2 "cpp/container/priority queue/swap2") (C++11) | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | ### Helper classes | | | | --- | --- | | [std::uses\_allocator<std::priority\_queue>](priority_queue/uses_allocator "cpp/container/priority queue/uses allocator") (C++11) | specializes the `[std::uses\_allocator](../memory/uses_allocator "cpp/memory/uses allocator")` type trait (class template specialization) | ### [Deduction guides](priority_queue/deduction_guides "cpp/container/priority queue/deduction guides") (since C++17) ### Example ``` #include <functional> #include <queue> #include <vector> #include <iostream> #include <string_view> template<typename T> void print(std::string_view name, T const& q) { std::cout << name << ": \t"; for (auto const& n : q) std::cout << n << ' '; std::cout << '\n'; } template<typename Q> void print_queue(std::string_view name, Q q) { // NB: q is passed by value because there is no way to traverse // priority_queue's content without erasing the queue. for (std::cout << name << ": \t"; !q.empty(); q.pop()) std::cout << q.top() << ' '; std::cout << '\n'; } int main() { const auto data = {1,8,5,6,3,4,0,9,7,2}; print("data", data); std::priority_queue<int> q1; // Max priority queue for(int n : data) q1.push(n); print_queue("q1", q1); // Min priority queue // std::greater<int> makes the max priority queue act as a min priority queue std::priority_queue<int, std::vector<int>, std::greater<int>> minq1(data.begin(), data.end()); print_queue("minq1", minq1); // Second way to define a min priority queue std::priority_queue minq2(data.begin(), data.end(), std::greater<int>()); print_queue("minq2", minq2); // Using a custom function object to compare elements. struct { bool operator() (const int l, const int r) const { return l > r; } } customLess; std::priority_queue minq3(data.begin(), data.end(), customLess); print_queue("minq3", minq3); // Using lambda to compare elements. auto cmp = [](int left, int right) { return (left ^ 1) < (right ^ 1); }; std::priority_queue<int, std::vector<int>, decltype(cmp)> q5(cmp); for(int n : data) q5.push(n); print_queue("q5", q5); } ``` Output: ``` data: 1 8 5 6 3 4 0 9 7 2 q1: 9 8 7 6 5 4 3 2 1 0 minq1: 0 1 2 3 4 5 6 7 8 9 minq2: 0 1 2 3 4 5 6 7 8 9 minq3: 0 1 2 3 4 5 6 7 8 9 q5: 8 9 6 7 4 5 2 3 0 1 ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 2684](https://cplusplus.github.io/LWG/issue2684) | C++98 | `priority_queue` takes a comparator but lacked member typedef for it | added | cpp std::unordered_multimap std::unordered\_multimap ======================== | Defined in header `[<unordered\_map>](../header/unordered_map "cpp/header/unordered map")` | | | | --- | --- | --- | | ``` template< class Key, class T, class Hash = std::hash<Key>, class KeyEqual = std::equal_to<Key>, class Allocator = std::allocator< std::pair<const Key, T> > > class unordered_multimap; ``` | (1) | (since C++11) | | ``` namespace pmr { template <class Key, class T, class Hash = std::hash<Key>, class Pred = std::equal_to<Key>> using unordered_multimap = std::unordered_multimap<Key, T, Hash, Pred, std::pmr::polymorphic_allocator<std::pair<const Key,T>>>; } ``` | (2) | (since C++17) | Unordered multimap is an unordered associative container that supports equivalent keys (an unordered\_multimap may contain multiple copies of each key value) and that associates values of another type with the keys. The unordered\_multimap class supports forward iterators. Search, insertion, and removal have average constant-time complexity. Internally, the elements are not sorted in any particular order, but organized into buckets. Which bucket an element is placed into depends entirely on the hash of its key. This allows fast access to individual elements, since once the hash is computed, it refers to the exact bucket the element is placed into. The iteration order of this container is not required to be stable (so, for example, `[std::equal](../algorithm/equal "cpp/algorithm/equal")` cannot be used to compare two `std::unordered_multimap`s), except that every group of elements whose keys compare *equivalent* (compare equal with `[key\_eq()](unordered_multimap/key_eq "cpp/container/unordered multimap/key eq")` as the comparator) forms a contiguous subrange in the iteration order, also accessible with `[equal\_range()](unordered_multimap/equal_range "cpp/container/unordered multimap/equal range")`. `std::unordered_multimap` meets the requirements of [Container](../named_req/container "cpp/named req/Container"), [AllocatorAwareContainer](../named_req/allocatorawarecontainer "cpp/named req/AllocatorAwareContainer"), [UnorderedAssociativeContainer](../named_req/unorderedassociativecontainer "cpp/named req/UnorderedAssociativeContainer"). ### Member types | Member type | Definition | | --- | --- | | `key_type` | `Key` | | `mapped_type` | `T` | | `value_type` | `[std::pair](http://en.cppreference.com/w/cpp/utility/pair)<const Key, T>` | | `size_type` | Unsigned integer type (usually `[std::size\_t](../types/size_t "cpp/types/size t")`) | | `difference_type` | Signed integer type (usually `[std::ptrdiff\_t](../types/ptrdiff_t "cpp/types/ptrdiff t")`) | | `hasher` | `Hash` | | `key_equal` | `KeyEqual` | | `allocator_type` | `Allocator` | | `reference` | `value_type&` | | `const_reference` | `const value_type&` | | `pointer` | `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<Allocator>::pointer` | | `const_pointer` | `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<Allocator>::const\_pointer` | | `iterator` | [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator") to `value_type` | | `const_iterator` | [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator") to `const value_type` | | `local_iterator` | An iterator type whose category, value, difference, pointer and reference types are the same as `iterator`. This iterator can be used to iterate through a single bucket but not across buckets | | `const_local_iterator` | An iterator type whose category, value, difference, pointer and reference types are the same as `const_iterator`. This iterator can be used to iterate through a single bucket but not across buckets | | `node_type` (since C++17) | a specialization of [node handle](node_handle "cpp/container/node handle") representing a container node | ### Member functions | | | | --- | --- | | [(constructor)](unordered_multimap/unordered_multimap "cpp/container/unordered multimap/unordered multimap") (C++11) | constructs the `unordered_multimap` (public member function) | | [(destructor)](unordered_multimap/~unordered_multimap "cpp/container/unordered multimap/~unordered multimap") (C++11) | destructs the `unordered_multimap` (public member function) | | [operator=](unordered_multimap/operator= "cpp/container/unordered multimap/operator=") (C++11) | assigns values to the container (public member function) | | [get\_allocator](unordered_multimap/get_allocator "cpp/container/unordered multimap/get allocator") (C++11) | returns the associated allocator (public member function) | | Iterators | | [begin cbegin](unordered_multimap/begin "cpp/container/unordered multimap/begin") (C++11) | returns an iterator to the beginning (public member function) | | [end cend](unordered_multimap/end "cpp/container/unordered multimap/end") (C++11) | returns an iterator to the end (public member function) | | Capacity | | [empty](unordered_multimap/empty "cpp/container/unordered multimap/empty") (C++11) | checks whether the container is empty (public member function) | | [size](unordered_multimap/size "cpp/container/unordered multimap/size") (C++11) | returns the number of elements (public member function) | | [max\_size](unordered_multimap/max_size "cpp/container/unordered multimap/max size") (C++11) | returns the maximum possible number of elements (public member function) | | Modifiers | | [clear](unordered_multimap/clear "cpp/container/unordered multimap/clear") (C++11) | clears the contents (public member function) | | [insert](unordered_multimap/insert "cpp/container/unordered multimap/insert") (C++11) | inserts elements or nodes (since C++17) (public member function) | | [emplace](unordered_multimap/emplace "cpp/container/unordered multimap/emplace") (C++11) | constructs element in-place (public member function) | | [emplace\_hint](unordered_multimap/emplace_hint "cpp/container/unordered multimap/emplace hint") (C++11) | constructs elements in-place using a hint (public member function) | | [erase](unordered_multimap/erase "cpp/container/unordered multimap/erase") (C++11) | erases elements (public member function) | | [swap](unordered_multimap/swap "cpp/container/unordered multimap/swap") (C++11) | swaps the contents (public member function) | | [extract](unordered_multimap/extract "cpp/container/unordered multimap/extract") (C++17) | extracts nodes from the container (public member function) | | [merge](unordered_multimap/merge "cpp/container/unordered multimap/merge") (C++17) | splices nodes from another container (public member function) | | Lookup | | [count](unordered_multimap/count "cpp/container/unordered multimap/count") (C++11) | returns the number of elements matching specific key (public member function) | | [find](unordered_multimap/find "cpp/container/unordered multimap/find") (C++11) | finds element with specific key (public member function) | | [contains](unordered_multimap/contains "cpp/container/unordered multimap/contains") (C++20) | checks if the container contains element with specific key (public member function) | | [equal\_range](unordered_multimap/equal_range "cpp/container/unordered multimap/equal range") (C++11) | returns range of elements matching a specific key (public member function) | | Bucket interface | | [begin(size\_type) cbegin(size\_type)](unordered_multimap/begin2 "cpp/container/unordered multimap/begin2") (C++11) | returns an iterator to the beginning of the specified bucket (public member function) | | [end(size\_type) cend(size\_type)](unordered_multimap/end2 "cpp/container/unordered multimap/end2") (C++11) | returns an iterator to the end of the specified bucket (public member function) | | [bucket\_count](unordered_multimap/bucket_count "cpp/container/unordered multimap/bucket count") (C++11) | returns the number of buckets (public member function) | | [max\_bucket\_count](unordered_multimap/max_bucket_count "cpp/container/unordered multimap/max bucket count") (C++11) | returns the maximum number of buckets (public member function) | | [bucket\_size](unordered_multimap/bucket_size "cpp/container/unordered multimap/bucket size") (C++11) | returns the number of elements in specific bucket (public member function) | | [bucket](unordered_multimap/bucket "cpp/container/unordered multimap/bucket") (C++11) | returns the bucket for specific key (public member function) | | Hash policy | | [load\_factor](unordered_multimap/load_factor "cpp/container/unordered multimap/load factor") (C++11) | returns average number of elements per bucket (public member function) | | [max\_load\_factor](unordered_multimap/max_load_factor "cpp/container/unordered multimap/max load factor") (C++11) | manages maximum average number of elements per bucket (public member function) | | [rehash](unordered_multimap/rehash "cpp/container/unordered multimap/rehash") (C++11) | reserves at least the specified number of buckets and regenerates the hash table (public member function) | | [reserve](unordered_multimap/reserve "cpp/container/unordered multimap/reserve") (C++11) | reserves space for at least the specified number of elements and regenerates the hash table (public member function) | | Observers | | [hash\_function](unordered_multimap/hash_function "cpp/container/unordered multimap/hash function") (C++11) | returns function used to hash the keys (public member function) | | [key\_eq](unordered_multimap/key_eq "cpp/container/unordered multimap/key eq") (C++11) | returns the function used to compare keys for equality (public member function) | ### Non-member functions | | | | --- | --- | | [operator==operator!=](unordered_multimap/operator_cmp "cpp/container/unordered multimap/operator cmp") (removed in C++20) | compares the values in the unordered\_multimap (function template) | | [std::swap(std::unordered\_multimap)](unordered_multimap/swap2 "cpp/container/unordered multimap/swap2") (C++11) | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | | [erase\_if(std::unordered\_multimap)](unordered_multimap/erase_if "cpp/container/unordered multimap/erase if") (C++20) | Erases all elements satisfying specific criteria (function template) | ### [Deduction guides](unordered_multimap/deduction_guides "cpp/container/unordered multimap/deduction guides")(since C++17) cpp std::unordered_set std::unordered\_set =================== | Defined in header `[<unordered\_set>](../header/unordered_set "cpp/header/unordered set")` | | | | --- | --- | --- | | ``` template< class Key, class Hash = std::hash<Key>, class KeyEqual = std::equal_to<Key>, class Allocator = std::allocator<Key> > class unordered_set; ``` | (1) | (since C++11) | | ``` namespace pmr { template <class Key, class Hash = std::hash<Key>, class Pred = std::equal_to<Key>> using unordered_set = std::unordered_set<Key, Hash, Pred, std::pmr::polymorphic_allocator<Key>>; } ``` | (2) | (since C++17) | Unordered set is an associative container that contains a set of unique objects of type Key. Search, insertion, and removal have average constant-time complexity. Internally, the elements are not sorted in any particular order, but organized into buckets. Which bucket an element is placed into depends entirely on the hash of its value. This allows fast access to individual elements, since once a hash is computed, it refers to the exact bucket the element is placed into. Container elements may not be modified (even by non const iterators) since modification could change an element's hash and corrupt the container. `std::unordered_set` meets the requirements of [Container](../named_req/container "cpp/named req/Container"), [AllocatorAwareContainer](../named_req/allocatorawarecontainer "cpp/named req/AllocatorAwareContainer"), [UnorderedAssociativeContainer](../named_req/unorderedassociativecontainer "cpp/named req/UnorderedAssociativeContainer"). ### Iterator invalidation | Operations | Invalidated | | --- | --- | | All read only operations, `[swap](unordered_set/swap "cpp/container/unordered set/swap")`, `[std::swap](../algorithm/swap "cpp/algorithm/swap")` | Never | | `[clear](unordered_set/clear "cpp/container/unordered set/clear")`, `[rehash](unordered_set/rehash "cpp/container/unordered set/rehash")`, `[reserve](unordered_set/reserve "cpp/container/unordered set/reserve")`, `[operator=](unordered_set/operator= "cpp/container/unordered set/operator=")` | Always | | `[insert](unordered_set/insert "cpp/container/unordered set/insert")`, `[emplace](unordered_set/emplace "cpp/container/unordered set/emplace")`, `[emplace\_hint](unordered_set/emplace_hint "cpp/container/unordered set/emplace hint")` | Only if causes rehash | | `[erase](unordered_set/erase "cpp/container/unordered set/erase")` | Only to the element erased | #### Notes * The swap functions do not invalidate any of the iterators inside the container, but they do invalidate the iterator marking the end of the swap region. * References and pointers to data stored in the container are only invalidated by erasing that element, even when the corresponding iterator is invalidated. * After container move assignment, unless elementwise move assignment is forced by incompatible allocators, references, pointers, and iterators (other than the end iterator) to moved-from container remain valid, but refer to elements that are now in \*this. ### Member types | Member type | Definition | | --- | --- | | `key_type` | `Key` | | `value_type` | `Key` | | `size_type` | Unsigned integer type (usually `[std::size\_t](../types/size_t "cpp/types/size t")`) | | `difference_type` | Signed integer type (usually `[std::ptrdiff\_t](../types/ptrdiff_t "cpp/types/ptrdiff t")`) | | `hasher` | `Hash` | | `key_equal` | `KeyEqual` | | `allocator_type` | `Allocator` | | `reference` | `value_type&` | | `const_reference` | `const value_type&` | | `pointer` | `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<Allocator>::pointer` | | `const_pointer` | `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<Allocator>::const\_pointer` | | `iterator` | Constant [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator") to `value_type` | | `const_iterator` | [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator") to `const value_type` | | `local_iterator` | An iterator type whose category, value, difference, pointer and reference types are the same as `iterator`. This iterator can be used to iterate through a single bucket but not across buckets | | `const_local_iterator` | An iterator type whose category, value, difference, pointer and reference types are the same as `const_iterator`. This iterator can be used to iterate through a single bucket but not across buckets | | `node_type` (since C++17) | a specialization of [node handle](node_handle "cpp/container/node handle") representing a container node | | `insert_return_type` (since C++17) | type describing the result of inserting a `node_type`, a specialization of `template <class Iter, class NodeType> struct /*unspecified*/ { Iter position; bool inserted; NodeType node; };` instantiated with template arguments `iterator` and `node_type`. | ### Member functions | | | | --- | --- | | [(constructor)](unordered_set/unordered_set "cpp/container/unordered set/unordered set") (C++11) | constructs the `unordered_set` (public member function) | | [(destructor)](unordered_set/~unordered_set "cpp/container/unordered set/~unordered set") (C++11) | destructs the `unordered_set` (public member function) | | [operator=](unordered_set/operator= "cpp/container/unordered set/operator=") (C++11) | assigns values to the container (public member function) | | [get\_allocator](unordered_set/get_allocator "cpp/container/unordered set/get allocator") (C++11) | returns the associated allocator (public member function) | | Iterators | | [begin cbegin](unordered_set/begin "cpp/container/unordered set/begin") (C++11) | returns an iterator to the beginning (public member function) | | [end cend](unordered_set/end "cpp/container/unordered set/end") (C++11) | returns an iterator to the end (public member function) | | Capacity | | [empty](unordered_set/empty "cpp/container/unordered set/empty") (C++11) | checks whether the container is empty (public member function) | | [size](unordered_set/size "cpp/container/unordered set/size") (C++11) | returns the number of elements (public member function) | | [max\_size](unordered_set/max_size "cpp/container/unordered set/max size") (C++11) | returns the maximum possible number of elements (public member function) | | Modifiers | | [clear](unordered_set/clear "cpp/container/unordered set/clear") (C++11) | clears the contents (public member function) | | [insert](unordered_set/insert "cpp/container/unordered set/insert") (C++11) | inserts elements or nodes (since C++17) (public member function) | | [emplace](unordered_set/emplace "cpp/container/unordered set/emplace") (C++11) | constructs element in-place (public member function) | | [emplace\_hint](unordered_set/emplace_hint "cpp/container/unordered set/emplace hint") (C++11) | constructs elements in-place using a hint (public member function) | | [erase](unordered_set/erase "cpp/container/unordered set/erase") (C++11) | erases elements (public member function) | | [swap](unordered_set/swap "cpp/container/unordered set/swap") (C++11) | swaps the contents (public member function) | | [extract](unordered_set/extract "cpp/container/unordered set/extract") (C++17) | extracts nodes from the container (public member function) | | [merge](unordered_set/merge "cpp/container/unordered set/merge") (C++17) | splices nodes from another container (public member function) | | Lookup | | [count](unordered_set/count "cpp/container/unordered set/count") (C++11) | returns the number of elements matching specific key (public member function) | | [find](unordered_set/find "cpp/container/unordered set/find") (C++11) | finds element with specific key (public member function) | | [contains](unordered_set/contains "cpp/container/unordered set/contains") (C++20) | checks if the container contains element with specific key (public member function) | | [equal\_range](unordered_set/equal_range "cpp/container/unordered set/equal range") (C++11) | returns range of elements matching a specific key (public member function) | | Bucket interface | | [begin(size\_type) cbegin(size\_type)](unordered_set/begin2 "cpp/container/unordered set/begin2") (C++11) | returns an iterator to the beginning of the specified bucket (public member function) | | [end(size\_type) cend(size\_type)](unordered_set/end2 "cpp/container/unordered set/end2") (C++11) | returns an iterator to the end of the specified bucket (public member function) | | [bucket\_count](unordered_set/bucket_count "cpp/container/unordered set/bucket count") (C++11) | returns the number of buckets (public member function) | | [max\_bucket\_count](unordered_set/max_bucket_count "cpp/container/unordered set/max bucket count") (C++11) | returns the maximum number of buckets (public member function) | | [bucket\_size](unordered_set/bucket_size "cpp/container/unordered set/bucket size") (C++11) | returns the number of elements in specific bucket (public member function) | | [bucket](unordered_set/bucket "cpp/container/unordered set/bucket") (C++11) | returns the bucket for specific key (public member function) | | Hash policy | | [load\_factor](unordered_set/load_factor "cpp/container/unordered set/load factor") (C++11) | returns average number of elements per bucket (public member function) | | [max\_load\_factor](unordered_set/max_load_factor "cpp/container/unordered set/max load factor") (C++11) | manages maximum average number of elements per bucket (public member function) | | [rehash](unordered_set/rehash "cpp/container/unordered set/rehash") (C++11) | reserves at least the specified number of buckets and regenerates the hash table (public member function) | | [reserve](unordered_set/reserve "cpp/container/unordered set/reserve") (C++11) | reserves space for at least the specified number of elements and regenerates the hash table (public member function) | | Observers | | [hash\_function](unordered_set/hash_function "cpp/container/unordered set/hash function") (C++11) | returns function used to hash the keys (public member function) | | [key\_eq](unordered_set/key_eq "cpp/container/unordered set/key eq") (C++11) | returns the function used to compare keys for equality (public member function) | ### Non-member functions | | | | --- | --- | | [operator==operator!=](unordered_set/operator_cmp "cpp/container/unordered set/operator cmp") (removed in C++20) | compares the values in the unordered\_set (function template) | | [std::swap(std::unordered\_set)](unordered_set/swap2 "cpp/container/unordered set/swap2") (C++11) | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | | [erase\_if(std::unordered\_set)](unordered_set/erase_if "cpp/container/unordered set/erase if") (C++20) | Erases all elements satisfying specific criteria (function template) | ### [Deduction guides](unordered_set/deduction_guides "cpp/container/unordered set/deduction guides")(since C++17) ### Notes The member types `iterator` and `const_iterator` may be aliases to the same type. This means defining a pair of function overloads using the two types as parameter types may violate the [One Definition Rule](../language/definition#One_Definition_Rule "cpp/language/definition"). Since `iterator` is convertible to `const_iterator`, a single function with a `const_iterator` as parameter type will work instead.
programming_docs
cpp std::unordered_map std::unordered\_map =================== | Defined in header `[<unordered\_map>](../header/unordered_map "cpp/header/unordered map")` | | | | --- | --- | --- | | ``` template< class Key, class T, class Hash = std::hash<Key>, class KeyEqual = std::equal_to<Key>, class Allocator = std::allocator< std::pair<const Key, T> > > class unordered_map; ``` | (1) | (since C++11) | | ``` namespace pmr { template <class Key, class T, class Hash = std::hash<Key>, class Pred = std::equal_to<Key>> using unordered_map = std::unordered_map<Key, T, Hash, Pred, std::pmr::polymorphic_allocator<std::pair<const Key,T>>>; } ``` | (2) | (since C++17) | Unordered map is an associative container that contains key-value pairs with unique keys. Search, insertion, and removal of elements have average constant-time complexity. Internally, the elements are not sorted in any particular order, but organized into buckets. Which bucket an element is placed into depends entirely on the hash of its key. Keys with the same hash code appear in the same bucket. This allows fast access to individual elements, since once the hash is computed, it refers to the exact bucket the element is placed into. `std::unordered_map` meets the requirements of [Container](../named_req/container "cpp/named req/Container"), [AllocatorAwareContainer](../named_req/allocatorawarecontainer "cpp/named req/AllocatorAwareContainer"), [UnorderedAssociativeContainer](../named_req/unorderedassociativecontainer "cpp/named req/UnorderedAssociativeContainer"). ### Iterator invalidation | Operations | Invalidated | | --- | --- | | All read only operations, `[swap](unordered_map/swap "cpp/container/unordered map/swap")`, `[std::swap](../algorithm/swap "cpp/algorithm/swap")` | Never | | `[clear](unordered_map/clear "cpp/container/unordered map/clear")`, `[rehash](unordered_map/rehash "cpp/container/unordered map/rehash")`, `[reserve](unordered_map/reserve "cpp/container/unordered map/reserve")`, `[operator=](unordered_map/operator= "cpp/container/unordered map/operator=")` | Always | | `[insert](unordered_map/insert "cpp/container/unordered map/insert")`, `[emplace](unordered_map/emplace "cpp/container/unordered map/emplace")`, `[emplace\_hint](unordered_map/emplace_hint "cpp/container/unordered map/emplace hint")`, `[operator[]](unordered_map/operator_at "cpp/container/unordered map/operator at")` | Only if causes rehash | | `[erase](unordered_map/erase "cpp/container/unordered map/erase")` | Only to the element erased | #### Notes * The swap functions do not invalidate any of the iterators inside the container, but they do invalidate the iterator marking the end of the swap region. * References and pointers to either key or data stored in the container are only invalidated by erasing that element, even when the corresponding iterator is invalidated. ### Member types | Member type | Definition | | --- | --- | | `key_type` | `Key` | | `mapped_type` | `T` | | `value_type` | `[std::pair](http://en.cppreference.com/w/cpp/utility/pair)<const Key, T>` | | `size_type` | Unsigned integer type (usually `[std::size\_t](../types/size_t "cpp/types/size t")`) | | `difference_type` | Signed integer type (usually `[std::ptrdiff\_t](../types/ptrdiff_t "cpp/types/ptrdiff t")`) | | `hasher` | `Hash` | | `key_equal` | `KeyEqual` | | `allocator_type` | `Allocator` | | `reference` | `value_type&` | | `const_reference` | `const value_type&` | | `pointer` | `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<Allocator>::pointer` | | `const_pointer` | `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<Allocator>::const\_pointer` | | `iterator` | [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator") to `value_type` | | `const_iterator` | [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator") to `const value_type` | | `local_iterator` | An iterator type whose category, value, difference, pointer and reference types are the same as `iterator`. This iterator can be used to iterate through a single bucket but not across buckets | | `const_local_iterator` | An iterator type whose category, value, difference, pointer and reference types are the same as `const_iterator`. This iterator can be used to iterate through a single bucket but not across buckets | | `node_type` (since C++17) | a specialization of [node handle](node_handle "cpp/container/node handle") representing a container node | | `insert_return_type` (since C++17) | type describing the result of inserting a `node_type`, a specialization of `template <class Iter, class NodeType> struct /*unspecified*/ { Iter position; bool inserted; NodeType node; };` instantiated with template arguments `iterator` and `node_type`. | ### Member functions | | | | --- | --- | | [(constructor)](unordered_map/unordered_map "cpp/container/unordered map/unordered map") (C++11) | constructs the `unordered_map` (public member function) | | [(destructor)](unordered_map/~unordered_map "cpp/container/unordered map/~unordered map") (C++11) | destructs the `unordered_map` (public member function) | | [operator=](unordered_map/operator= "cpp/container/unordered map/operator=") (C++11) | assigns values to the container (public member function) | | [get\_allocator](unordered_map/get_allocator "cpp/container/unordered map/get allocator") (C++11) | returns the associated allocator (public member function) | | Iterators | | [begin cbegin](unordered_map/begin "cpp/container/unordered map/begin") (C++11) | returns an iterator to the beginning (public member function) | | [end cend](unordered_map/end "cpp/container/unordered map/end") (C++11) | returns an iterator to the end (public member function) | | Capacity | | [empty](unordered_map/empty "cpp/container/unordered map/empty") (C++11) | checks whether the container is empty (public member function) | | [size](unordered_map/size "cpp/container/unordered map/size") (C++11) | returns the number of elements (public member function) | | [max\_size](unordered_map/max_size "cpp/container/unordered map/max size") (C++11) | returns the maximum possible number of elements (public member function) | | Modifiers | | [clear](unordered_map/clear "cpp/container/unordered map/clear") (C++11) | clears the contents (public member function) | | [insert](unordered_map/insert "cpp/container/unordered map/insert") (C++11) | inserts elements or nodes (since C++17) (public member function) | | [insert\_or\_assign](unordered_map/insert_or_assign "cpp/container/unordered map/insert or assign") (C++17) | inserts an element or assigns to the current element if the key already exists (public member function) | | [emplace](unordered_map/emplace "cpp/container/unordered map/emplace") (C++11) | constructs element in-place (public member function) | | [emplace\_hint](unordered_map/emplace_hint "cpp/container/unordered map/emplace hint") (C++11) | constructs elements in-place using a hint (public member function) | | [try\_emplace](unordered_map/try_emplace "cpp/container/unordered map/try emplace") (C++17) | inserts in-place if the key does not exist, does nothing if the key exists (public member function) | | [erase](unordered_map/erase "cpp/container/unordered map/erase") (C++11) | erases elements (public member function) | | [swap](unordered_map/swap "cpp/container/unordered map/swap") (C++11) | swaps the contents (public member function) | | [extract](unordered_map/extract "cpp/container/unordered map/extract") (C++17) | extracts nodes from the container (public member function) | | [merge](unordered_map/merge "cpp/container/unordered map/merge") (C++17) | splices nodes from another container (public member function) | | Lookup | | [at](unordered_map/at "cpp/container/unordered map/at") (C++11) | access specified element with bounds checking (public member function) | | [operator[]](unordered_map/operator_at "cpp/container/unordered map/operator at") (C++11) | access or insert specified element (public member function) | | [count](unordered_map/count "cpp/container/unordered map/count") (C++11) | returns the number of elements matching specific key (public member function) | | [find](unordered_map/find "cpp/container/unordered map/find") (C++11) | finds element with specific key (public member function) | | [contains](unordered_map/contains "cpp/container/unordered map/contains") (C++20) | checks if the container contains element with specific key (public member function) | | [equal\_range](unordered_map/equal_range "cpp/container/unordered map/equal range") (C++11) | returns range of elements matching a specific key (public member function) | | Bucket interface | | [begin(size\_type) cbegin(size\_type)](unordered_map/begin2 "cpp/container/unordered map/begin2") (C++11) | returns an iterator to the beginning of the specified bucket (public member function) | | [end(size\_type) cend(size\_type)](unordered_map/end2 "cpp/container/unordered map/end2") (C++11) | returns an iterator to the end of the specified bucket (public member function) | | [bucket\_count](unordered_map/bucket_count "cpp/container/unordered map/bucket count") (C++11) | returns the number of buckets (public member function) | | [max\_bucket\_count](unordered_map/max_bucket_count "cpp/container/unordered map/max bucket count") (C++11) | returns the maximum number of buckets (public member function) | | [bucket\_size](unordered_map/bucket_size "cpp/container/unordered map/bucket size") (C++11) | returns the number of elements in specific bucket (public member function) | | [bucket](unordered_map/bucket "cpp/container/unordered map/bucket") (C++11) | returns the bucket for specific key (public member function) | | Hash policy | | [load\_factor](unordered_map/load_factor "cpp/container/unordered map/load factor") (C++11) | returns average number of elements per bucket (public member function) | | [max\_load\_factor](unordered_map/max_load_factor "cpp/container/unordered map/max load factor") (C++11) | manages maximum average number of elements per bucket (public member function) | | [rehash](unordered_map/rehash "cpp/container/unordered map/rehash") (C++11) | reserves at least the specified number of buckets and regenerates the hash table (public member function) | | [reserve](unordered_map/reserve "cpp/container/unordered map/reserve") (C++11) | reserves space for at least the specified number of elements and regenerates the hash table (public member function) | | Observers | | [hash\_function](unordered_map/hash_function "cpp/container/unordered map/hash function") (C++11) | returns function used to hash the keys (public member function) | | [key\_eq](unordered_map/key_eq "cpp/container/unordered map/key eq") (C++11) | returns the function used to compare keys for equality (public member function) | ### Non-member functions | | | | --- | --- | | [operator==operator!=](unordered_map/operator_cmp "cpp/container/unordered map/operator cmp") (removed in C++20) | compares the values in the unordered\_map (function template) | | [std::swap(std::unordered\_map)](unordered_map/swap2 "cpp/container/unordered map/swap2") (C++11) | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | | [erase\_if(std::unordered\_map)](unordered_map/erase_if "cpp/container/unordered map/erase if") (C++20) | Erases all elements satisfying specific criteria (function template) | ### [Deduction guides](unordered_map/deduction_guides "cpp/container/unordered map/deduction guides")(since C++17) ### Example ``` #include <iostream> #include <string> #include <unordered_map> int main() { // Create an unordered_map of three strings (that map to strings) std::unordered_map<std::string, std::string> u = { {"RED","#FF0000"}, {"GREEN","#00FF00"}, {"BLUE","#0000FF"} }; // Helper lambda function to print key-value pairs auto print_key_value = [](const auto& key, const auto& value) { std::cout << "Key:[" << key << "] Value:[" << value << "]\n"; }; std::cout << "Iterate and print key-value pairs of unordered_map, being\n" "explicit with their types:\n"; for( const std::pair<const std::string, std::string>& n : u ) { print_key_value(n.first, n.second); } std::cout << "\nIterate and print key-value pairs using C++17 structured binding:\n"; for( const auto& [key, value] : u ) { print_key_value(key, value); } // Add two new entries to the unordered_map u["BLACK"] = "#000000"; u["WHITE"] = "#FFFFFF"; std::cout << "\nOutput values by key:\n" "The HEX of color RED is:[" << u["RED"] << "]\n" "The HEX of color BLACK is:[" << u["BLACK"] << "]\n\n"; std::cout << "Use operator[] with non-existent key to insert a new key-value pair:\n"; print_key_value("new_key", u["new_key"]); std::cout << "\nIterate and print key-value pairs, using `auto`;\n" "new_key is now one of the keys in the map:\n"; for( const auto& n : u ) { print_key_value(n.first, n.second); } } ``` Possible output: ``` Iterate and print key-value pairs of unordered_map, being explicit with their types: Key:[BLUE] Value:[#0000FF] Key:[GREEN] Value:[#00FF00] Key:[RED] Value:[#FF0000] Iterate and print key-value pairs using C++17 structured binding: Key:[BLUE] Value:[#0000FF] Key:[GREEN] Value:[#00FF00] Key:[RED] Value:[#FF0000] Output values by key: The HEX of color RED is:[#FF0000] The HEX of color BLACK is:[#000000] Use operator[] with non-existent key to insert a new key-value pair: Key:[new_key] Value:[] Iterate and print key-value pairs, using `auto`; new_key is now one of the keys in the map: Key:[new_key] Value:[] Key:[WHITE] Value:[#FFFFFF] Key:[BLACK] Value:[#000000] Key:[BLUE] Value:[#0000FF] Key:[GREEN] Value:[#00FF00] Key:[RED] Value:[#FF0000] ``` ### See also | | | | --- | --- | | [map](map "cpp/container/map") | collection of key-value pairs, sorted by keys, keys are unique (class template) | cpp std::unordered_multiset std::unordered\_multiset ======================== | Defined in header `[<unordered\_set>](../header/unordered_set "cpp/header/unordered set")` | | | | --- | --- | --- | | ``` template< class Key, class Hash = std::hash<Key>, class KeyEqual = std::equal_to<Key>, class Allocator = std::allocator<Key> > class unordered_multiset; ``` | (1) | (since C++11) | | ``` namespace pmr { template <class Key, class Hash = std::hash<Key>, class Pred = std::equal_to<Key>> using unordered_multiset = std::unordered_multiset<Key, Hash, Pred, std::pmr::polymorphic_allocator<Key>> } ``` | (2) | (since C++17) | Unordered multiset is an associative container that contains set of possibly non-unique objects of type Key. Search, insertion, and removal have average constant-time complexity. Internally, the elements are not sorted in any particular order, but organized into buckets. Which bucket an element is placed into depends entirely on the hash of its value. This allows fast access to individual elements, since once hash is computed, it refers to the exact bucket the element is placed into. The iteration order of this container is not required to be stable (so, for example, `[std::equal](../algorithm/equal "cpp/algorithm/equal")` cannot be used to compare two `std::unordered_multiset`s), except that every group of elements whose keys compare *equivalent* (compare equal with `[key\_eq()](unordered_multiset/key_eq "cpp/container/unordered multiset/key eq")` as the comparator) forms a contiguous subrange in the iteration order, also accessible with `[equal\_range()](unordered_multiset/equal_range "cpp/container/unordered multiset/equal range")`. `std::unordered_multiset` meets the requirements of [Container](../named_req/container "cpp/named req/Container"), [AllocatorAwareContainer](../named_req/allocatorawarecontainer "cpp/named req/AllocatorAwareContainer"), [UnorderedAssociativeContainer](../named_req/unorderedassociativecontainer "cpp/named req/UnorderedAssociativeContainer"). ### Member types | Member type | Definition | | --- | --- | | `key_type` | `Key` | | `value_type` | `Key` | | `size_type` | Unsigned integer type (usually `[std::size\_t](../types/size_t "cpp/types/size t")`) | | `difference_type` | Signed integer type (usually `[std::ptrdiff\_t](../types/ptrdiff_t "cpp/types/ptrdiff t")`) | | `hasher` | `Hash` | | `key_equal` | `KeyEqual` | | `allocator_type` | `Allocator` | | `reference` | `value_type&` | | `const_reference` | `const value_type&` | | `pointer` | `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<Allocator>::pointer` | | `const_pointer` | `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<Allocator>::const\_pointer` | | `iterator` | Constant [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator") to `value_type` | | `const_iterator` | [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator") to `const value_type` | | `local_iterator` | An iterator type whose category, value, difference, pointer and reference types are the same as `iterator`. This iterator can be used to iterate through a single bucket but not across buckets | | `const_local_iterator` | An iterator type whose category, value, difference, pointer and reference types are the same as `const_iterator`. This iterator can be used to iterate through a single bucket but not across buckets | | `node_type` (since C++17) | a specialization of [node handle](node_handle "cpp/container/node handle") representing a container node | ### Member functions | | | | --- | --- | | [(constructor)](unordered_multiset/unordered_multiset "cpp/container/unordered multiset/unordered multiset") (C++11) | constructs the `unordered_multiset` (public member function) | | [(destructor)](unordered_multiset/~unordered_multiset "cpp/container/unordered multiset/~unordered multiset") (C++11) | destructs the `unordered_multiset` (public member function) | | [operator=](unordered_multiset/operator= "cpp/container/unordered multiset/operator=") (C++11) | assigns values to the container (public member function) | | [get\_allocator](unordered_multiset/get_allocator "cpp/container/unordered multiset/get allocator") (C++11) | returns the associated allocator (public member function) | | Iterators | | [begin cbegin](unordered_multiset/begin "cpp/container/unordered multiset/begin") (C++11) | returns an iterator to the beginning (public member function) | | [end cend](unordered_multiset/end "cpp/container/unordered multiset/end") (C++11) | returns an iterator to the end (public member function) | | Capacity | | [empty](unordered_multiset/empty "cpp/container/unordered multiset/empty") (C++11) | checks whether the container is empty (public member function) | | [size](unordered_multiset/size "cpp/container/unordered multiset/size") (C++11) | returns the number of elements (public member function) | | [max\_size](unordered_multiset/max_size "cpp/container/unordered multiset/max size") (C++11) | returns the maximum possible number of elements (public member function) | | Modifiers | | [clear](unordered_multiset/clear "cpp/container/unordered multiset/clear") (C++11) | clears the contents (public member function) | | [insert](unordered_multiset/insert "cpp/container/unordered multiset/insert") (C++11) | inserts elements or nodes (since C++17) (public member function) | | [emplace](unordered_multiset/emplace "cpp/container/unordered multiset/emplace") (C++11) | constructs element in-place (public member function) | | [emplace\_hint](unordered_multiset/emplace_hint "cpp/container/unordered multiset/emplace hint") (C++11) | constructs elements in-place using a hint (public member function) | | [erase](unordered_multiset/erase "cpp/container/unordered multiset/erase") (C++11) | erases elements (public member function) | | [swap](unordered_multiset/swap "cpp/container/unordered multiset/swap") (C++11) | swaps the contents (public member function) | | [extract](unordered_multiset/extract "cpp/container/unordered multiset/extract") (C++17) | extracts nodes from the container (public member function) | | [merge](unordered_multiset/merge "cpp/container/unordered multiset/merge") (C++17) | splices nodes from another container (public member function) | | Lookup | | [count](unordered_multiset/count "cpp/container/unordered multiset/count") (C++11) | returns the number of elements matching specific key (public member function) | | [find](unordered_multiset/find "cpp/container/unordered multiset/find") (C++11) | finds element with specific key (public member function) | | [contains](unordered_multiset/contains "cpp/container/unordered multiset/contains") (C++20) | checks if the container contains element with specific key (public member function) | | [equal\_range](unordered_multiset/equal_range "cpp/container/unordered multiset/equal range") (C++11) | returns range of elements matching a specific key (public member function) | | Bucket interface | | [begin(size\_type) cbegin(size\_type)](unordered_multiset/begin2 "cpp/container/unordered multiset/begin2") (C++11) | returns an iterator to the beginning of the specified bucket (public member function) | | [end(size\_type) cend(size\_type)](unordered_multiset/end2 "cpp/container/unordered multiset/end2") (C++11) | returns an iterator to the end of the specified bucket (public member function) | | [bucket\_count](unordered_multiset/bucket_count "cpp/container/unordered multiset/bucket count") (C++11) | returns the number of buckets (public member function) | | [max\_bucket\_count](unordered_multiset/max_bucket_count "cpp/container/unordered multiset/max bucket count") (C++11) | returns the maximum number of buckets (public member function) | | [bucket\_size](unordered_multiset/bucket_size "cpp/container/unordered multiset/bucket size") (C++11) | returns the number of elements in specific bucket (public member function) | | [bucket](unordered_multiset/bucket "cpp/container/unordered multiset/bucket") (C++11) | returns the bucket for specific key (public member function) | | Hash policy | | [load\_factor](unordered_multiset/load_factor "cpp/container/unordered multiset/load factor") (C++11) | returns average number of elements per bucket (public member function) | | [max\_load\_factor](unordered_multiset/max_load_factor "cpp/container/unordered multiset/max load factor") (C++11) | manages maximum average number of elements per bucket (public member function) | | [rehash](unordered_multiset/rehash "cpp/container/unordered multiset/rehash") (C++11) | reserves at least the specified number of buckets and regenerates the hash table (public member function) | | [reserve](unordered_multiset/reserve "cpp/container/unordered multiset/reserve") (C++11) | reserves space for at least the specified number of elements and regenerates the hash table (public member function) | | Observers | | [hash\_function](unordered_multiset/hash_function "cpp/container/unordered multiset/hash function") (C++11) | returns function used to hash the keys (public member function) | | [key\_eq](unordered_multiset/key_eq "cpp/container/unordered multiset/key eq") (C++11) | returns the function used to compare keys for equality (public member function) | ### Non-member functions | | | | --- | --- | | [operator==operator!=](unordered_multiset/operator_cmp "cpp/container/unordered multiset/operator cmp") (removed in C++20) | compares the values in the unordered\_multiset (function template) | | [std::swap(std::unordered\_multiset)](unordered_multiset/swap2 "cpp/container/unordered multiset/swap2") (C++11) | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | | [erase\_if(std::unordered\_multiset)](unordered_multiset/erase_if "cpp/container/unordered multiset/erase if") (C++20) | Erases all elements satisfying specific criteria (function template) | ### [Deduction guides](unordered_multiset/deduction_guides "cpp/container/unordered multiset/deduction guides")(since C++17) ### Notes The member types `iterator` and `const_iterator` may be aliases to the same type. This means defining a pair of function overloads using the two types as parameter types may violate the [One Definition Rule](../language/definition#One_Definition_Rule "cpp/language/definition"). Since `iterator` is convertible to `const_iterator`, a single function with a `const_iterator` as parameter type will work instead.
programming_docs
cpp std::array std::array ========== | Defined in header `[<array>](../header/array "cpp/header/array")` | | | | --- | --- | --- | | ``` template< class T, std::size_t N > struct array; ``` | | (since C++11) | `std::array` is a container that encapsulates fixed size arrays. This container is an aggregate type with the same semantics as a struct holding a [C-style array](../language/array "cpp/language/array") `T[N]` as its only non-static data member. Unlike a C-style array, it doesn't decay to `T*` automatically. As an aggregate type, it can be initialized with [aggregate-initialization](../language/aggregate_initialization "cpp/language/aggregate initialization") given at most `N` initializers that are convertible to `T`: `std::array<int, 3> a = {1,2,3};`. The struct combines the performance and accessibility of a C-style array with the benefits of a standard container, such as knowing its own size, supporting assignment, random access iterators, etc. `std::array` satisfies the requirements of [Container](../named_req/container "cpp/named req/Container") and [ReversibleContainer](../named_req/reversiblecontainer "cpp/named req/ReversibleContainer") except that default-constructed array is not empty and that the complexity of swapping is linear, satisfies the requirements of [ContiguousContainer](../named_req/contiguouscontainer "cpp/named req/ContiguousContainer"), (since C++17) and partially satisfies the requirements of [SequenceContainer](../named_req/sequencecontainer "cpp/named req/SequenceContainer"). There is a special case for a zero-length array (`N == 0`). In that case, `array.begin() == array.end()`, which is some unique value. The effect of calling `front()` or `back()` on a zero-sized array is undefined. An array can also be used as a tuple of `N` elements of the same type. ### Iterator invalidation As a rule, iterators to an array are never invalidated throughout the lifetime of the array. One should take note, however, that during [swap](array/swap "cpp/container/array/swap"), the iterator will continue to point to the same array element, and will thus change its value. ### Member types | Member type | Definition | | --- | --- | | `value_type` | `T` | | `size_type` | `[std::size\_t](../types/size_t "cpp/types/size t")` | | `difference_type` | `[std::ptrdiff\_t](../types/ptrdiff_t "cpp/types/ptrdiff t")` | | `reference` | `value_type&` | | `const_reference` | `const value_type&` | | `pointer` | `value_type*` | | `const_pointer` | `const value_type*` | | `iterator` | | | | | --- | --- | | [LegacyRandomAccessIterator](../named_req/randomaccessiterator "cpp/named req/RandomAccessIterator") and [LegacyContiguousIterator](../named_req/contiguousiterator "cpp/named req/ContiguousIterator") to `value_type`. | (until C++17) | | [LegacyRandomAccessIterator](../named_req/randomaccessiterator "cpp/named req/RandomAccessIterator") and [LegacyContiguousIterator](../named_req/contiguousiterator "cpp/named req/ContiguousIterator") that is a [LiteralType](../named_req/literaltype "cpp/named req/LiteralType") to `value_type`. | (since C++17)(until C++20) | | [LegacyRandomAccessIterator](../named_req/randomaccessiterator "cpp/named req/RandomAccessIterator"), [`contiguous_iterator`](../iterator/contiguous_iterator "cpp/iterator/contiguous iterator"), and [ConstexprIterator](../named_req/constexpriterator "cpp/named req/ConstexprIterator") to `value_type`. | (since C++20) | | | `const_iterator` | | | | | --- | --- | | [LegacyRandomAccessIterator](../named_req/randomaccessiterator "cpp/named req/RandomAccessIterator") and [LegacyContiguousIterator](../named_req/contiguousiterator "cpp/named req/ContiguousIterator") to `const value_type`. | (until C++17) | | [LegacyRandomAccessIterator](../named_req/randomaccessiterator "cpp/named req/RandomAccessIterator") and [LegacyContiguousIterator](../named_req/contiguousiterator "cpp/named req/ContiguousIterator") that is a [LiteralType](../named_req/literaltype "cpp/named req/LiteralType") to `const value_type`. | (since C++17)(until C++20) | | [LegacyRandomAccessIterator](../named_req/randomaccessiterator "cpp/named req/RandomAccessIterator"), [`contiguous_iterator`](../iterator/contiguous_iterator "cpp/iterator/contiguous iterator"), and [ConstexprIterator](../named_req/constexpriterator "cpp/named req/ConstexprIterator") to `const value_type`. | (since C++20) | | | `reverse_iterator` | `[std::reverse\_iterator](http://en.cppreference.com/w/cpp/iterator/reverse_iterator)<iterator>` | | `const_reverse_iterator` | `[std::reverse\_iterator](http://en.cppreference.com/w/cpp/iterator/reverse_iterator)<const_iterator>` | ### Member functions | | | --- | | Implicitly-defined member functions | | (constructor) (implicitly declared) | initializes the array following the rules of [aggregate initialization](../language/aggregate_initialization "cpp/language/aggregate initialization") (note that default initialization may result in indeterminate values for non-class `T`) (public member function) | | (destructor) (implicitly declared) | destroys every element of the array (public member function) | | operator= (implicitly declared) | overwrites every element of the array with the corresponding element of another array (public member function) | | Element access | | [at](array/at "cpp/container/array/at") (C++11) | access specified element with bounds checking (public member function) | | [operator[]](array/operator_at "cpp/container/array/operator at") (C++11) | access specified element (public member function) | | [front](array/front "cpp/container/array/front") (C++11) | access the first element (public member function) | | [back](array/back "cpp/container/array/back") (C++11) | access the last element (public member function) | | [data](array/data "cpp/container/array/data") (C++11) | direct access to the underlying array (public member function) | | Iterators | | [begin cbegin](array/begin "cpp/container/array/begin") (C++11) | returns an iterator to the beginning (public member function) | | [end cend](array/end "cpp/container/array/end") (C++11) | returns an iterator to the end (public member function) | | [rbegincrbegin](array/rbegin "cpp/container/array/rbegin") (C++11) | returns a reverse iterator to the beginning (public member function) | | [rendcrend](array/rend "cpp/container/array/rend") (C++11) | returns a reverse iterator to the end (public member function) | | Capacity | | [empty](array/empty "cpp/container/array/empty") (C++11) | checks whether the container is empty (public member function) | | [size](array/size "cpp/container/array/size") (C++11) | returns the number of elements (public member function) | | [max\_size](array/max_size "cpp/container/array/max size") (C++11) | returns the maximum possible number of elements (public member function) | | Operations | | [fill](array/fill "cpp/container/array/fill") (C++11) | fill the container with specified value (public member function) | | [swap](array/swap "cpp/container/array/swap") (C++11) | swaps the contents (public member function) | ### Non-member functions | | | | --- | --- | | [operator==operator!=operator<operator<=operator>operator>=operator<=>](array/operator_cmp "cpp/container/array/operator cmp") (removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(C++20) | lexicographically compares the values in the array (function template) | | [std::get(std::array)](array/get "cpp/container/array/get") (C++11) | accesses an element of an `array` (function template) | | [std::swap(std::array)](array/swap2 "cpp/container/array/swap2") (C++11) | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | | [to\_array](array/to_array "cpp/container/array/to array") (C++20) | creates a `std::array` object from a built-in array (function template) | ### Helper classes | | | | --- | --- | | [std::tuple\_size<std::array>](array/tuple_size "cpp/container/array/tuple size") (C++11) | obtains the size of an `array` (class template specialization) | | [std::tuple\_element<std::array>](array/tuple_element "cpp/container/array/tuple element") (C++11) | obtains the type of the elements of `array` (class template specialization) | ### [Deduction guides](array/deduction_guides "cpp/container/array/deduction guides")(since C++17) ### Example ``` #include <string> #include <iterator> #include <iostream> #include <algorithm> #include <array> int main() { // construction uses aggregate initialization std::array<int, 3> a1{ {1, 2, 3} }; // double-braces required in C++11 prior to // the CWG 1270 revision (not needed in C++11 // after the revision and in C++14 and beyond) std::array<int, 3> a2 = {1, 2, 3}; // double braces never required after = std::array<std::string, 2> a3 = { std::string("a"), "b" }; // container operations are supported std::sort(a1.begin(), a1.end()); std::reverse_copy(a2.begin(), a2.end(), std::ostream_iterator<int>(std::cout, " ")); std::cout << '\n'; // ranged for loop is supported for(const auto& s: a3) std::cout << s << ' '; // deduction guide for array creation (since C++17) [[maybe_unused]] std::array a4{3.0, 1.0, 4.0}; // -> std::array<double, 3> } ``` Output: ``` 3 2 1 a b ``` ### See also | | | | --- | --- | | [make\_array](https://en.cppreference.com/w/cpp/experimental/make_array "cpp/experimental/make array") (library fundamentals TS v2) | Creates a `std::array` object whose size and optionally element type are deduced from the arguments (function template) | cpp std::deque std::deque ========== | Defined in header `[<deque>](../header/deque "cpp/header/deque")` | | | | --- | --- | --- | | ``` template< class T, class Allocator = std::allocator<T> > class deque; ``` | (1) | | | ``` namespace pmr { template <class T> using deque = std::deque<T, std::pmr::polymorphic_allocator<T>>; } ``` | (2) | (since C++17) | `std::deque` (double-ended queue) is an indexed sequence container that allows fast insertion and deletion at both its beginning and its end. In addition, insertion and deletion at either end of a deque never invalidates pointers or references to the rest of the elements. As opposed to `[std::vector](vector "cpp/container/vector")`, the elements of a deque are not stored contiguously: typical implementations use a sequence of individually allocated fixed-size arrays, with additional bookkeeping, which means indexed access to deque must perform two pointer dereferences, compared to vector's indexed access which performs only one. The storage of a deque is automatically expanded and contracted as needed. Expansion of a deque is cheaper than the expansion of a `[std::vector](vector "cpp/container/vector")` because it does not involve copying of the existing elements to a new memory location. On the other hand, deques typically have large minimal memory cost; a deque holding just one element has to allocate its full internal array (e.g. 8 times the object size on 64-bit libstdc++; 16 times the object size or 4096 bytes, whichever is larger, on 64-bit libc++). The complexity (efficiency) of common operations on deques is as follows: * Random access - constant O(1) * Insertion or removal of elements at the end or beginning - constant O(1) * Insertion or removal of elements - linear O(n) `std::deque` meets the requirements of [Container](../named_req/container "cpp/named req/Container"), [AllocatorAwareContainer](../named_req/allocatorawarecontainer "cpp/named req/AllocatorAwareContainer"), [SequenceContainer](../named_req/sequencecontainer "cpp/named req/SequenceContainer") and [ReversibleContainer](../named_req/reversiblecontainer "cpp/named req/ReversibleContainer"). ### Template parameters | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | | T | - | The type of the elements. | | | | --- | --- | | `T` must meet the requirements of [CopyAssignable](../named_req/copyassignable "cpp/named req/CopyAssignable") and [CopyConstructible](../named_req/copyconstructible "cpp/named req/CopyConstructible"). | (until C++11) | | The requirements that are imposed on the elements depend on the actual operations performed on the container. Generally, it is required that element type is a complete type and meets the requirements of [Erasable](../named_req/erasable "cpp/named req/Erasable"), but many member functions impose stricter requirements. | (since C++11) | | | Allocator | - | An allocator that is used to acquire/release memory and to construct/destroy the elements in that memory. The type must meet the requirements of [Allocator](../named_req/allocator "cpp/named req/Allocator"). The behavior is undefined (until C++20)The program is ill-formed (since C++20) if `Allocator::value_type` is not the same as `T`. | ### Iterator invalidation | Operations | Invalidated | | --- | --- | | All read only operations | Never | | `[swap](deque/swap "cpp/container/deque/swap")`, `[std::swap](../algorithm/swap "cpp/algorithm/swap")` | The past-the-end iterator may be invalidated (implementation defined) | | `[shrink\_to\_fit](deque/shrink_to_fit "cpp/container/deque/shrink to fit")`, `[clear](deque/clear "cpp/container/deque/clear")`, `[insert](deque/insert "cpp/container/deque/insert")`, `[emplace](deque/emplace "cpp/container/deque/emplace")`, `[push\_front](deque/push_front "cpp/container/deque/push front")`, `[push\_back](deque/push_back "cpp/container/deque/push back")`, `[emplace\_front](deque/emplace_front "cpp/container/deque/emplace front")`, `[emplace\_back](deque/emplace_back "cpp/container/deque/emplace back")` | Always | | `[erase](deque/erase "cpp/container/deque/erase")` | If erasing at begin - only erased elements If erasing at end - only erased elements and the past-the-end iterator Otherwise - all iterators are invalidated (including the past-the-end iterator). | | `[resize](deque/resize "cpp/container/deque/resize")` | If the new size is smaller than the old one : only erased elements and the past-the-end iterator If the new size is bigger than the old one : all iterators are invalidated Otherwise - none iterators are invalidated. | | `[pop\_front](deque/pop_front "cpp/container/deque/pop front")` | Only to the element erased | | `[pop\_back](deque/pop_back "cpp/container/deque/pop back")` | Only to the element erased and the past-the-end iterator | #### Invalidation notes * When inserting at either end of the deque, references are not invalidated by `[insert](deque/insert "cpp/container/deque/insert")` and `[emplace](deque/emplace "cpp/container/deque/emplace")`. * `[push\_front](deque/push_front "cpp/container/deque/push front")`, `[push\_back](deque/push_back "cpp/container/deque/push back")`, `[emplace\_front](deque/emplace_front "cpp/container/deque/emplace front")` and `[emplace\_back](deque/emplace_back "cpp/container/deque/emplace back")` do not invalidate any references to elements of the deque. * When erasing at either end of the deque, references to non-erased elements are not invalidated by `[erase](deque/erase "cpp/container/deque/erase")`, `[pop\_front](deque/pop_front "cpp/container/deque/pop front")` and `[pop\_back](deque/pop_back "cpp/container/deque/pop back")`. * A call to `[resize](deque/resize "cpp/container/deque/resize")` with a smaller size does not invalidate any references to non-erased elements. * A call to `[resize](deque/resize "cpp/container/deque/resize")` with a bigger size does not invalidate any references to elements of the deque. ### Member types | Member type | Definition | | --- | --- | | `value_type` | `T` | | `allocator_type` | `Allocator` | | `size_type` | Unsigned integer type (usually `[std::size\_t](../types/size_t "cpp/types/size t")`) | | `difference_type` | Signed integer type (usually `[std::ptrdiff\_t](../types/ptrdiff_t "cpp/types/ptrdiff t")`) | | `reference` | `value_type&` | | `const_reference` | `const value_type&` | | `pointer` | | | | | --- | --- | | `Allocator::pointer` | (until C++11) | | `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<Allocator>::pointer` | (since C++11) | | | `const_pointer` | | | | | --- | --- | | `Allocator::const_pointer` | (until C++11) | | `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<Allocator>::const\_pointer` | (since C++11) | | | `iterator` | [LegacyRandomAccessIterator](../named_req/randomaccessiterator "cpp/named req/RandomAccessIterator") to `value_type` | | `const_iterator` | [LegacyRandomAccessIterator](../named_req/randomaccessiterator "cpp/named req/RandomAccessIterator") to `const value_type` | | `reverse_iterator` | `[std::reverse\_iterator](http://en.cppreference.com/w/cpp/iterator/reverse_iterator)<iterator>` | | `const_reverse_iterator` | `[std::reverse\_iterator](http://en.cppreference.com/w/cpp/iterator/reverse_iterator)<const_iterator>` | ### Member functions | | | | --- | --- | | [(constructor)](deque/deque "cpp/container/deque/deque") | constructs the `deque` (public member function) | | [(destructor)](deque/~deque "cpp/container/deque/~deque") | destructs the `deque` (public member function) | | [operator=](deque/operator= "cpp/container/deque/operator=") | assigns values to the container (public member function) | | [assign](deque/assign "cpp/container/deque/assign") | assigns values to the container (public member function) | | [get\_allocator](deque/get_allocator "cpp/container/deque/get allocator") | returns the associated allocator (public member function) | | Element access | | [at](deque/at "cpp/container/deque/at") | access specified element with bounds checking (public member function) | | [operator[]](deque/operator_at "cpp/container/deque/operator at") | access specified element (public member function) | | [front](deque/front "cpp/container/deque/front") | access the first element (public member function) | | [back](deque/back "cpp/container/deque/back") | access the last element (public member function) | | Iterators | | [begin cbegin](deque/begin "cpp/container/deque/begin") (C++11) | returns an iterator to the beginning (public member function) | | [end cend](deque/end "cpp/container/deque/end") (C++11) | returns an iterator to the end (public member function) | | [rbegincrbegin](deque/rbegin "cpp/container/deque/rbegin") (C++11) | returns a reverse iterator to the beginning (public member function) | | [rendcrend](deque/rend "cpp/container/deque/rend") (C++11) | returns a reverse iterator to the end (public member function) | | Capacity | | [empty](deque/empty "cpp/container/deque/empty") | checks whether the container is empty (public member function) | | [size](deque/size "cpp/container/deque/size") | returns the number of elements (public member function) | | [max\_size](deque/max_size "cpp/container/deque/max size") | returns the maximum possible number of elements (public member function) | | [shrink\_to\_fit](deque/shrink_to_fit "cpp/container/deque/shrink to fit") (C++11) | reduces memory usage by freeing unused memory (public member function) | | Modifiers | | [clear](deque/clear "cpp/container/deque/clear") | clears the contents (public member function) | | [insert](deque/insert "cpp/container/deque/insert") | inserts elements (public member function) | | [emplace](deque/emplace "cpp/container/deque/emplace") (C++11) | constructs element in-place (public member function) | | [erase](deque/erase "cpp/container/deque/erase") | erases elements (public member function) | | [push\_back](deque/push_back "cpp/container/deque/push back") | adds an element to the end (public member function) | | [emplace\_back](deque/emplace_back "cpp/container/deque/emplace back") (C++11) | constructs an element in-place at the end (public member function) | | [pop\_back](deque/pop_back "cpp/container/deque/pop back") | removes the last element (public member function) | | [push\_front](deque/push_front "cpp/container/deque/push front") | inserts an element to the beginning (public member function) | | [emplace\_front](deque/emplace_front "cpp/container/deque/emplace front") (C++11) | constructs an element in-place at the beginning (public member function) | | [pop\_front](deque/pop_front "cpp/container/deque/pop front") | removes the first element (public member function) | | [resize](deque/resize "cpp/container/deque/resize") | changes the number of elements stored (public member function) | | [swap](deque/swap "cpp/container/deque/swap") | swaps the contents (public member function) | ### Non-member functions | | | | --- | --- | | [operator==operator!=operator<operator<=operator>operator>=operator<=>](deque/operator_cmp "cpp/container/deque/operator cmp") (removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(C++20) | lexicographically compares the values in the deque (function template) | | [std::swap(std::deque)](deque/swap2 "cpp/container/deque/swap2") | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | | [erase(std::deque)erase\_if(std::deque)](deque/erase2 "cpp/container/deque/erase2") (C++20) | Erases all elements satisfying specific criteria (function template) | ### [Deduction guides](deque/deduction_guides "cpp/container/deque/deduction guides")(since C++17) ### Example ``` #include <iostream> #include <deque> int main() { // Create a deque containing integers std::deque<int> d = {7, 5, 16, 8}; // Add an integer to the beginning and end of the deque d.push_front(13); d.push_back(25); // Iterate and print values of deque for(int n : d) { std::cout << n << ' '; } } ``` Output: ``` 13 7 5 16 8 25 ``` ### See also | | | | --- | --- | | [queue](queue "cpp/container/queue") | adapts a container to provide queue (FIFO data structure) (class template) |
programming_docs
cpp std::set std::set ======== | Defined in header `[<set>](../header/set "cpp/header/set")` | | | | --- | --- | --- | | ``` template< class Key, class Compare = std::less<Key>, class Allocator = std::allocator<Key> > class set; ``` | (1) | | | ``` namespace pmr { template <class Key, class Compare = std::less<Key>> using set = std::set<Key, Compare, std::pmr::polymorphic_allocator<Key>>; } ``` | (2) | (since C++17) | `std::set` is an associative container that contains a sorted set of unique objects of type `Key`. Sorting is done using the key comparison function [Compare](../named_req/compare "cpp/named req/Compare"). Search, removal, and insertion operations have logarithmic complexity. Sets are usually implemented as [red-black trees](https://en.wikipedia.org/wiki/Red%E2%80%93black_tree "enwiki:Red–black tree"). Everywhere the standard library uses the [Compare](../named_req/compare "cpp/named req/Compare") requirements, uniqueness is determined by using the equivalence relation. In imprecise terms, two objects `a` and `b` are considered equivalent if neither compares less than the other: `!comp(a, b) && !comp(b, a)`. `std::set` meets the requirements of [Container](../named_req/container "cpp/named req/Container"), [AllocatorAwareContainer](../named_req/allocatorawarecontainer "cpp/named req/AllocatorAwareContainer"), [AssociativeContainer](../named_req/associativecontainer "cpp/named req/AssociativeContainer") and [ReversibleContainer](../named_req/reversiblecontainer "cpp/named req/ReversibleContainer"). ### Member types | Member type | Definition | | --- | --- | | `key_type` | `Key` | | `value_type` | `Key` | | `size_type` | Unsigned integer type (usually `[std::size\_t](../types/size_t "cpp/types/size t")`) | | `difference_type` | Signed integer type (usually `[std::ptrdiff\_t](../types/ptrdiff_t "cpp/types/ptrdiff t")`) | | `key_compare` | `Compare` | | `value_compare` | `Compare` | | `allocator_type` | `Allocator` | | `reference` | `value_type&` | | `const_reference` | `const value_type&` | | `pointer` | | | | | --- | --- | | `Allocator::pointer` | (until C++11) | | `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<Allocator>::pointer` | (since C++11) | | | `const_pointer` | | | | | --- | --- | | `Allocator::const_pointer` | (until C++11) | | `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<Allocator>::const\_pointer` | (since C++11) | | | `iterator` | Constant [LegacyBidirectionalIterator](../named_req/bidirectionaliterator "cpp/named req/BidirectionalIterator") to `value_type` | | `const_iterator` | [LegacyBidirectionalIterator](../named_req/bidirectionaliterator "cpp/named req/BidirectionalIterator") to `const value_type` | | `reverse_iterator` | `[std::reverse\_iterator](http://en.cppreference.com/w/cpp/iterator/reverse_iterator)<iterator>` | | `const_reverse_iterator` | `[std::reverse\_iterator](http://en.cppreference.com/w/cpp/iterator/reverse_iterator)<const_iterator>` | | `node_type` (since C++17) | a specialization of [node handle](node_handle "cpp/container/node handle") representing a container node | | `insert_return_type` (since C++17) | type describing the result of inserting a `node_type`, a specialization of `template <class Iter, class NodeType> struct /*unspecified*/ { Iter position; bool inserted; NodeType node; };` instantiated with template arguments `iterator` and `node_type`. | ### Member functions | | | | --- | --- | | [(constructor)](set/set "cpp/container/set/set") | constructs the `set` (public member function) | | [(destructor)](set/~set "cpp/container/set/~set") | destructs the `set` (public member function) | | [operator=](set/operator= "cpp/container/set/operator=") | assigns values to the container (public member function) | | [get\_allocator](set/get_allocator "cpp/container/set/get allocator") | returns the associated allocator (public member function) | | Iterators | | [begin cbegin](set/begin "cpp/container/set/begin") (C++11) | returns an iterator to the beginning (public member function) | | [end cend](set/end "cpp/container/set/end") (C++11) | returns an iterator to the end (public member function) | | [rbegincrbegin](set/rbegin "cpp/container/set/rbegin") (C++11) | returns a reverse iterator to the beginning (public member function) | | [rendcrend](set/rend "cpp/container/set/rend") (C++11) | returns a reverse iterator to the end (public member function) | | Capacity | | [empty](set/empty "cpp/container/set/empty") | checks whether the container is empty (public member function) | | [size](set/size "cpp/container/set/size") | returns the number of elements (public member function) | | [max\_size](set/max_size "cpp/container/set/max size") | returns the maximum possible number of elements (public member function) | | Modifiers | | [clear](set/clear "cpp/container/set/clear") | clears the contents (public member function) | | [insert](set/insert "cpp/container/set/insert") | inserts elements or nodes (since C++17) (public member function) | | [emplace](set/emplace "cpp/container/set/emplace") (C++11) | constructs element in-place (public member function) | | [emplace\_hint](set/emplace_hint "cpp/container/set/emplace hint") (C++11) | constructs elements in-place using a hint (public member function) | | [erase](set/erase "cpp/container/set/erase") | erases elements (public member function) | | [swap](set/swap "cpp/container/set/swap") | swaps the contents (public member function) | | [extract](set/extract "cpp/container/set/extract") (C++17) | extracts nodes from the container (public member function) | | [merge](set/merge "cpp/container/set/merge") (C++17) | splices nodes from another container (public member function) | | Lookup | | [count](set/count "cpp/container/set/count") | returns the number of elements matching specific key (public member function) | | [find](set/find "cpp/container/set/find") | finds element with specific key (public member function) | | [contains](set/contains "cpp/container/set/contains") (C++20) | checks if the container contains element with specific key (public member function) | | [equal\_range](set/equal_range "cpp/container/set/equal range") | returns range of elements matching a specific key (public member function) | | [lower\_bound](set/lower_bound "cpp/container/set/lower bound") | returns an iterator to the first element *not less* than the given key (public member function) | | [upper\_bound](set/upper_bound "cpp/container/set/upper bound") | returns an iterator to the first element *greater* than the given key (public member function) | | Observers | | [key\_comp](set/key_comp "cpp/container/set/key comp") | returns the function that compares keys (public member function) | | [value\_comp](set/value_comp "cpp/container/set/value comp") | returns the function that compares keys in objects of type value\_type (public member function) | ### Non-member functions | | | | --- | --- | | [operator==operator!=operator<operator<=operator>operator>=operator<=>](set/operator_cmp "cpp/container/set/operator cmp") (removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(C++20) | lexicographically compares the values in the set (function template) | | [std::swap(std::set)](set/swap2 "cpp/container/set/swap2") | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | | [erase\_if(std::set)](set/erase_if "cpp/container/set/erase if") (C++20) | Erases all elements satisfying specific criteria (function template) | ### [Deduction guides](set/deduction_guides "cpp/container/set/deduction guides") (since C++17) ### Notes The member types `iterator` and `const_iterator` may be aliases to the same type. This means defining a pair of function overloads using the two types as parameter types may violate the [One Definition Rule](../language/definition#One_Definition_Rule "cpp/language/definition"). Since `iterator` is convertible to `const_iterator`, a single function with a `const_iterator` as parameter type will work instead. ### Defect Reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 103](https://cplusplus.github.io/LWG/issue103) | C++98 | iterator allows modification of keys | iterator made constant | cpp std::span std::span ========= | Defined in header `[<span>](../header/span "cpp/header/span")` | | | | --- | --- | --- | | ``` template< class T, std::size_t Extent = std::dynamic_extent > class span; ``` | | (since C++20) | The class template `span` describes an object that can refer to a contiguous sequence of objects with the first element of the sequence at position zero. A `span` can either have a *static* extent, in which case the number of elements in the sequence is known at compile-time and encoded in the type, or a *dynamic* extent. If a `span` has *dynamic* extent a typical implementation holds two members: a pointer to `T` and a size. A `span` with *static* extent may have only one member: a pointer to `T`. | | | | --- | --- | | Every specialization of `std::span` is a [TriviallyCopyable](../named_req/triviallycopyable "cpp/named req/TriviallyCopyable") type. | (since C++23) | ### Template parameters | | | | | --- | --- | --- | | T | - | element type; must be a complete object type that is not an abstract class type | | Extent | - | the number of elements in the sequence, or `std::dynamic_extent` if dynamic | ### Member types | Member type | Definition | | --- | --- | | `element_type` | `T` | | `value_type` | `[std::remove\_cv\_t](http://en.cppreference.com/w/cpp/types/remove_cv)<T>` | | `size_type` | `[std::size\_t](../types/size_t "cpp/types/size t")` | | `difference_type` | `[std::ptrdiff\_t](../types/ptrdiff_t "cpp/types/ptrdiff t")` | | `pointer` | `T*` | | `const_pointer` | `const T*` | | `reference` | `T&` | | `const_reference` | `const T&` | | `iterator` | implementation-defined [LegacyRandomAccessIterator](../named_req/randomaccessiterator "cpp/named req/RandomAccessIterator"), [ConstexprIterator](../named_req/constexpriterator "cpp/named req/ConstexprIterator"), and [`contiguous_iterator`](../iterator/contiguous_iterator "cpp/iterator/contiguous iterator") whose `value_type` is `value_type` | | `reverse_iterator` | `[std::reverse\_iterator](http://en.cppreference.com/w/cpp/iterator/reverse_iterator)<iterator>` | Note: `iterator` is a mutable iterator if `T` is not const-qualified. All requirements on the iterator types of a [Container](../named_req/container "cpp/named req/Container") apply to the `iterator` type of `span` as well. ### Member constant | | | | | --- | --- | --- | | ``` static constexpr std::size_t extent = Extent; ``` | | | ### Member functions | | | | --- | --- | | [(constructor)](span/span "cpp/container/span/span") | constructs a `span` (public member function) | | [operator=](span/operator= "cpp/container/span/operator=") | assigns a `span` (public member function) | | Iterators | | [begin](span/begin "cpp/container/span/begin") (C++20) | returns an iterator to the beginning (public member function) | | [end](span/end "cpp/container/span/end") (C++20) | returns an iterator to the end (public member function) | | [rbegin](span/rbegin "cpp/container/span/rbegin") (C++20) | returns a reverse iterator to the beginning (public member function) | | [rend](span/rend "cpp/container/span/rend") (C++20) | returns a reverse iterator to the end (public member function) | | Element access | | [front](span/front "cpp/container/span/front") (C++20) | access the first element (public member function) | | [back](span/back "cpp/container/span/back") (C++20) | access the last element (public member function) | | [operator[]](span/operator_at "cpp/container/span/operator at") | accesses an element of the sequence (public member function) | | [data](span/data "cpp/container/span/data") | returns a pointer to the beginning of the sequence of elements (public member function) | | Observers | | [size](span/size "cpp/container/span/size") | returns the number of elements in the sequence (public member function) | | [size\_bytes](span/size_bytes "cpp/container/span/size bytes") | returns the size of the sequence in bytes (public member function) | | [empty](span/empty "cpp/container/span/empty") | checks if the sequence is empty (public member function) | | Subviews | | [first](span/first "cpp/container/span/first") | obtains a subspan consisting of the first N elements of the sequence (public member function) | | [last](span/last "cpp/container/span/last") | obtains a subspan consisting of the last N elements of the sequence (public member function) | | [subspan](span/subspan "cpp/container/span/subspan") | obtains a subspan (public member function) | ### Non-member functions | | | | --- | --- | | [as\_bytesas\_writable\_bytes](span/as_bytes "cpp/container/span/as bytes") (C++20) | converts a `span` into a view of its underlying bytes (function template) | ### Non-member constant | | | | --- | --- | | [dynamic\_extent](span/dynamic_extent "cpp/container/span/dynamic extent") (C++20) | a constant of type `size_t` signifying that the `span` has dynamic extent (constant) | ### Helper templates | | | | | --- | --- | --- | | ``` template<class T, std::size_t Extent> inline constexpr bool ranges::enable_borrowed_range<std::span<T, Extent>> = true; ``` | | | This specialization of `[ranges::enable\_borrowed\_range](../ranges/borrowed_range "cpp/ranges/borrowed range")` makes `span` satisfy [`borrowed_range`](../ranges/borrowed_range "cpp/ranges/borrowed range"). | | | | | --- | --- | --- | | ``` template<class T, std::size_t Extent> inline constexpr bool ranges::enable_view<std::span<T, Extent>> = true; ``` | | | This specialization of `[ranges::enable\_view](../ranges/view "cpp/ranges/view")` makes `span` satisfy [`view`](../ranges/view "cpp/ranges/view"). ### [Deduction guides](span/deduction_guides "cpp/container/span/deduction guides") ### Notes Specializations of `std::span` are already trivially copyable types in all existing implementations, even before the formal requirement introduced in C++23. | [Feature-test](../utility/feature_test "cpp/utility/feature test") macro | | --- | | [`__cpp_lib_span`](../feature_test#Library_features "cpp/feature test") | ### Example The example uses `std::span` to implement some algorithms on contiguous ranges. ``` #include <algorithm> #include <cstddef> #include <iostream> #include <span> template<class T, std::size_t N> [[nodiscard]] constexpr auto slide(std::span<T,N> s, std::size_t offset, std::size_t width) { return s.subspan(offset, offset + width <= s.size() ? width : 0U); } template<class T, std::size_t N, std::size_t M> [[nodiscard]] constexpr bool starts_with(std::span<T,N> data, std::span<T,M> prefix) { return data.size() >= prefix.size() && std::equal(prefix.begin(), prefix.end(), data.begin()); } template<class T, std::size_t N, std::size_t M> [[nodiscard]] constexpr bool ends_with(std::span<T,N> data, std::span<T,M> suffix) { return data.size() >= suffix.size() && std::equal(data.end() - suffix.size(), data.end(), suffix.end() - suffix.size()); } template<class T, std::size_t N, std::size_t M> [[nodiscard]] constexpr bool contains(std::span<T,N> span, std::span<T,M> sub) { return std::search(span.begin(), span.end(), sub.begin(), sub.end()) != span.end(); // return std::ranges::search(span, sub).begin() != span.end(); } void print(const auto& seq) { for (const auto& elem : seq) std::cout << elem << ' '; std::cout << '\n'; } int main() { constexpr int a[] { 0, 1, 2, 3, 4, 5, 6, 7, 8 }; constexpr int b[] { 8, 7, 6 }; for (std::size_t offset{}; ; ++offset) { static constexpr std::size_t width{6}; auto s = slide(std::span{a}, offset, width); if (s.empty()) break; print(s); } static_assert( starts_with( std::span{a}, std::span{a, 4} ) and starts_with( std::span{a + 1, 4}, std::span{a + 1, 3} ) and ! starts_with( std::span{a}, std::span{b} ) and ! starts_with( std::span{a, 8}, std::span{a + 1, 3} ) and ends_with( std::span{a}, std::span{a + 6, 3} ) and ! ends_with( std::span{a}, std::span{a + 6, 2} ) and contains( std::span{a}, std::span{a + 1, 4} ) and ! contains( std::span{a, 8}, std::span{a, 9} ) ); } ``` Output: ``` 0 1 2 3 4 5 1 2 3 4 5 6 2 3 4 5 6 7 3 4 5 6 7 8 ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [P2325R3](https://wg21.link/P2325R3) | C++20 | `span` of non-zero static extents were not `view` | they are as [`default_initializable`](../concepts/default_initializable "cpp/concepts/default initializable") is not required | ### See also | | | | --- | --- | | [initializer\_list](../utility/initializer_list "cpp/utility/initializer list") (C++11) | creates a temporary array in [list-initialization](../language/list_initialization "cpp/language/list initialization") and then references it (class template) | | [basic\_string\_view](../string/basic_string_view "cpp/string/basic string view") (C++17) | read-only string view (class template) | | [ranges::subrange](../ranges/subrange "cpp/ranges/subrange") (C++20) | combines an iterator-sentinel pair into a [`view`](../ranges/view "cpp/ranges/view") (class template) | cpp std::multimap std::multimap ============= | Defined in header `[<map>](../header/map "cpp/header/map")` | | | | --- | --- | --- | | ``` template< class Key, class T, class Compare = std::less<Key>, class Allocator = std::allocator<std::pair<const Key, T> > > class multimap; ``` | (1) | | | ``` namespace pmr { template <class Key, class T, class Compare = std::less<Key>> using multimap = std::multimap<Key, T, Compare, std::pmr::polymorphic_allocator<std::pair<const Key,T>>>; } ``` | (2) | (since C++17) | Multimap is an associative container that contains a sorted list of key-value pairs, while permitting multiple entries with the same key. Sorting is done according to the comparison function `Compare`, applied to the keys. Search, insertion, and removal operations have logarithmic complexity. The order of the key-value pairs whose keys compare equivalent is the order of insertion and does not change. (since C++11). Everywhere the standard library uses the [Compare](../named_req/compare "cpp/named req/Compare") requirements, equivalence is determined by using the equivalence relation as described on [Compare](../named_req/compare "cpp/named req/Compare"). In imprecise terms, two objects `a` and `b` are considered equivalent if neither compares less than the other: `!comp(a, b) && !comp(b, a)`. `std::multimap` meets the requirements of [Container](../named_req/container "cpp/named req/Container"), [AllocatorAwareContainer](../named_req/allocatorawarecontainer "cpp/named req/AllocatorAwareContainer"), [AssociativeContainer](../named_req/associativecontainer "cpp/named req/AssociativeContainer") and [ReversibleContainer](../named_req/reversiblecontainer "cpp/named req/ReversibleContainer"). ### Member types | Member type | Definition | | --- | --- | | `key_type` | `Key` | | `mapped_type` | `T` | | `value_type` | `[std::pair](http://en.cppreference.com/w/cpp/utility/pair)<const Key, T>` | | `size_type` | Unsigned integer type (usually `[std::size\_t](../types/size_t "cpp/types/size t")`) | | `difference_type` | Signed integer type (usually `[std::ptrdiff\_t](../types/ptrdiff_t "cpp/types/ptrdiff t")`) | | `key_compare` | `Compare` | | `allocator_type` | `Allocator` | | `reference` | `value_type&` | | `const_reference` | `const value_type&` | | `pointer` | | | | | --- | --- | | `Allocator::pointer` | (until C++11) | | `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<Allocator>::pointer` | (since C++11) | | | `const_pointer` | | | | | --- | --- | | `Allocator::const_pointer` | (until C++11) | | `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<Allocator>::const\_pointer` | (since C++11) | | | `iterator` | [LegacyBidirectionalIterator](../named_req/bidirectionaliterator "cpp/named req/BidirectionalIterator") to `value_type` | | `const_iterator` | [LegacyBidirectionalIterator](../named_req/bidirectionaliterator "cpp/named req/BidirectionalIterator") to `const value_type` | | `reverse_iterator` | `[std::reverse\_iterator](http://en.cppreference.com/w/cpp/iterator/reverse_iterator)<iterator>` | | `const_reverse_iterator` | `[std::reverse\_iterator](http://en.cppreference.com/w/cpp/iterator/reverse_iterator)<const_iterator>` | | `node_type` (since C++17) | a specialization of [node handle](node_handle "cpp/container/node handle") representing a container node | ### Member classes | | | | --- | --- | | [value\_compare](multimap/value_compare "cpp/container/multimap/value compare") | compares objects of type `value_type` (class) | ### Member functions | | | | --- | --- | | [(constructor)](multimap/multimap "cpp/container/multimap/multimap") | constructs the `multimap` (public member function) | | [(destructor)](multimap/~multimap "cpp/container/multimap/~multimap") | destructs the `multimap` (public member function) | | [operator=](multimap/operator= "cpp/container/multimap/operator=") | assigns values to the container (public member function) | | [get\_allocator](multimap/get_allocator "cpp/container/multimap/get allocator") | returns the associated allocator (public member function) | | Iterators | | [begin cbegin](multimap/begin "cpp/container/multimap/begin") (C++11) | returns an iterator to the beginning (public member function) | | [end cend](multimap/end "cpp/container/multimap/end") (C++11) | returns an iterator to the end (public member function) | | [rbegincrbegin](multimap/rbegin "cpp/container/multimap/rbegin") (C++11) | returns a reverse iterator to the beginning (public member function) | | [rendcrend](multimap/rend "cpp/container/multimap/rend") (C++11) | returns a reverse iterator to the end (public member function) | | Capacity | | [empty](multimap/empty "cpp/container/multimap/empty") | checks whether the container is empty (public member function) | | [size](multimap/size "cpp/container/multimap/size") | returns the number of elements (public member function) | | [max\_size](multimap/max_size "cpp/container/multimap/max size") | returns the maximum possible number of elements (public member function) | | Modifiers | | [clear](multimap/clear "cpp/container/multimap/clear") | clears the contents (public member function) | | [insert](multimap/insert "cpp/container/multimap/insert") | inserts elements or nodes (since C++17) (public member function) | | [emplace](multimap/emplace "cpp/container/multimap/emplace") (C++11) | constructs element in-place (public member function) | | [emplace\_hint](multimap/emplace_hint "cpp/container/multimap/emplace hint") (C++11) | constructs elements in-place using a hint (public member function) | | [erase](multimap/erase "cpp/container/multimap/erase") | erases elements (public member function) | | [swap](multimap/swap "cpp/container/multimap/swap") | swaps the contents (public member function) | | [extract](multimap/extract "cpp/container/multimap/extract") (C++17) | extracts nodes from the container (public member function) | | [merge](multimap/merge "cpp/container/multimap/merge") (C++17) | splices nodes from another container (public member function) | | Lookup | | [count](multimap/count "cpp/container/multimap/count") | returns the number of elements matching specific key (public member function) | | [find](multimap/find "cpp/container/multimap/find") | finds element with specific key (public member function) | | [contains](multimap/contains "cpp/container/multimap/contains") (C++20) | checks if the container contains element with specific key (public member function) | | [equal\_range](multimap/equal_range "cpp/container/multimap/equal range") | returns range of elements matching a specific key (public member function) | | [lower\_bound](multimap/lower_bound "cpp/container/multimap/lower bound") | returns an iterator to the first element *not less* than the given key (public member function) | | [upper\_bound](multimap/upper_bound "cpp/container/multimap/upper bound") | returns an iterator to the first element *greater* than the given key (public member function) | | Observers | | [key\_comp](multimap/key_comp "cpp/container/multimap/key comp") | returns the function that compares keys (public member function) | | [value\_comp](multimap/value_comp "cpp/container/multimap/value comp") | returns the function that compares keys in objects of type value\_type (public member function) | ### Non-member functions | | | | --- | --- | | [operator==operator!=operator<operator<=operator>operator>=operator<=>](multimap/operator_cmp "cpp/container/multimap/operator cmp") (removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(C++20) | lexicographically compares the values in the multimap (function template) | | [std::swap(std::multimap)](multimap/swap2 "cpp/container/multimap/swap2") | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | | [erase\_if(std::multimap)](multimap/erase_if "cpp/container/multimap/erase if") (C++20) | Erases all elements satisfying specific criteria (function template) | ### [Deduction guides](multimap/deduction_guides "cpp/container/multimap/deduction guides")(since C++17)
programming_docs
cpp std::stack std::stack ========== | Defined in header `[<stack>](../header/stack "cpp/header/stack")` | | | | --- | --- | --- | | ``` template< class T, class Container = std::deque<T> > class stack; ``` | | | The `std::stack` class is a container adaptor that gives the programmer the functionality of a stack - specifically, a LIFO (last-in, first-out) data structure. The class template acts as a wrapper to the underlying container - only a specific set of functions is provided. The stack pushes and pops the element from the back of the underlying container, known as the top of the stack. ### Template parameters | | | | | --- | --- | --- | | T | - | The type of the stored elements. The behavior is undefined if `T` is not the same type as `Container::value_type`. (since C++17) | | Container | - | The type of the underlying container to use to store the elements. The container must satisfy the requirements of [SequenceContainer](../named_req/sequencecontainer "cpp/named req/SequenceContainer"). Additionally, it must provide the following functions with the usual semantics: * `back()` * `push_back()` * `pop_back()` The standard containers `[std::vector](vector "cpp/container/vector")`, `[std::deque](deque "cpp/container/deque")` and `[std::list](list "cpp/container/list")` satisfy these requirements. By default, if no container class is specified for a particular stack class instantiation, the standard container `[std::deque](deque "cpp/container/deque")` is used. | ### Member types | Member type | Definition | | --- | --- | | `container_type` | `Container` | | `value_type` | `Container::value_type` | | `size_type` | `Container::size_type` | | `reference` | `Container::reference` | | `const_reference` | `Container::const_reference` | ### Member functions | | | | --- | --- | | [(constructor)](stack/stack "cpp/container/stack/stack") | constructs the `stack` (public member function) | | [(destructor)](stack/~stack "cpp/container/stack/~stack") | destructs the `stack` (public member function) | | [operator=](stack/operator= "cpp/container/stack/operator=") | assigns values to the container adaptor (public member function) | | Element access | | [top](stack/top "cpp/container/stack/top") | accesses the top element (public member function) | | Capacity | | [empty](stack/empty "cpp/container/stack/empty") | checks whether the underlying container is empty (public member function) | | [size](stack/size "cpp/container/stack/size") | returns the number of elements (public member function) | | Modifiers | | [push](stack/push "cpp/container/stack/push") | inserts element at the top (public member function) | | [emplace](stack/emplace "cpp/container/stack/emplace") (C++11) | constructs element in-place at the top (public member function) | | [pop](stack/pop "cpp/container/stack/pop") | removes the top element (public member function) | | [swap](stack/swap "cpp/container/stack/swap") (C++11) | swaps the contents (public member function) | | Member objects | | Container c | the underlying container (protected member object) | ### Non-member functions | | | | --- | --- | | [operator==operator!=operator<operator<=operator>operator>=operator<=>](stack/operator_cmp "cpp/container/stack/operator cmp") (C++20) | lexicographically compares the values in the stack (function template) | | [std::swap(std::stack)](stack/swap2 "cpp/container/stack/swap2") (C++11) | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | ### Helper classes | | | | --- | --- | | [std::uses\_allocator<std::stack>](stack/uses_allocator "cpp/container/stack/uses allocator") (C++11) | specializes the `[std::uses\_allocator](../memory/uses_allocator "cpp/memory/uses allocator")` type trait (class template specialization) | ### [Deduction guides](stack/deduction_guides "cpp/container/stack/deduction guides")(since C++17) cpp std::forward_list<T,Allocator>::sort std::forward\_list<T,Allocator>::sort ===================================== | | | | | --- | --- | --- | | ``` void sort(); ``` | (1) | (since C++11) | | ``` template< class Compare > void sort( Compare comp ); ``` | (2) | (since C++11) | Sorts the elements in ascending order. The order of equal elements is preserved. The first version uses `operator<` to compare the elements, the second version uses the given comparison function `comp`. If an exception is thrown, the order of elements in `*this` is unspecified. ### Parameters | | | | | --- | --- | --- | | comp | - | comparison function object (i.e. an object that satisfies the requirements of [Compare](../../named_req/compare "cpp/named req/Compare")) which returns ​`true` if the first argument is *less* than (i.e. is ordered *before*) the second. The signature of the comparison function should be equivalent to the following: `bool cmp(const Type1 &a, const Type2 &b);` While the signature does not need to have `const &`, the function must not modify the objects passed to it and must be able to accept all values of type (possibly const) `Type1` and `Type2` regardless of [value category](../../language/value_category "cpp/language/value category") (thus, `Type1 &` is not allowed, nor is `Type1` unless for `Type1` a move is equivalent to a copy (since C++11)). The types `Type1` and `Type2` must be such that an object of type `forward_list<T,Allocator>::const_iterator` can be dereferenced and then implicitly converted to both of them. ​ | ### Return value (none). ### Complexity Approximately `N log N` comparisons, where N is the number of elements in the list. ### Notes `[std::sort](../../algorithm/sort "cpp/algorithm/sort")` requires random access iterators and so cannot be used with `forward_list` . This function also differs from `[std::sort](../../algorithm/sort "cpp/algorithm/sort")` in that it does not require the element type of the `forward_list` to be swappable, preserves the values of all iterators, and performs a stable sort. ### Example ``` #include <iostream> #include <functional> #include <forward_list> std::ostream& operator<<(std::ostream& ostr, const std::forward_list<int>& list) { for (auto &i : list) { ostr << " " << i; } return ostr; } int main() { std::forward_list<int> list = { 8,7,5,9,0,1,3,2,6,4 }; std::cout << "before: " << list << "\n"; list.sort(); std::cout << "ascending: " << list << "\n"; list.sort(std::greater<int>()); std::cout << "descending: " << list << "\n"; } ``` Output: ``` before: 8 7 5 9 0 1 3 2 6 4 ascending: 0 1 2 3 4 5 6 7 8 9 descending: 9 8 7 6 5 4 3 2 1 0 ``` cpp deduction guides for std::forward_list deduction guides for `std::forward_list` ======================================== | Defined in header `[<forward\_list>](../../header/forward_list "cpp/header/forward list")` | | | | --- | --- | --- | | ``` template< class InputIt, class Alloc = std::allocator<typename std::iterator_traits<InputIt>::value_type>> forward_list(InputIt, InputIt, Alloc = Alloc()) -> forward_list<typename std::iterator_traits<InputIt>::value_type, Alloc>; ``` | | (since C++17) | This [deduction guide](../../language/class_template_argument_deduction "cpp/language/class template argument deduction") is provided for forward\_list to allow deduction from an iterator range. This overload participates in overload resolution only if `InputIt` satisfies [LegacyInputIterator](../../named_req/inputiterator "cpp/named req/InputIterator") and `Alloc` satisfies [Allocator](../../named_req/allocator "cpp/named req/Allocator"). Note: the extent to which the library determines that a type does not satisfy [LegacyInputIterator](../../named_req/inputiterator "cpp/named req/InputIterator") is unspecified, except that as a minimum integral types do not qualify as input iterators. Likewise, the extent to which it determines that a type does not satisfy [Allocator](../../named_req/allocator "cpp/named req/Allocator") is unspecified, except that as a minimum the member type `Alloc::value_type` must exist and the expression `[std::declval](http://en.cppreference.com/w/cpp/utility/declval)<Alloc&>().allocate([std::size\_t](http://en.cppreference.com/w/cpp/types/size_t){})` must be well-formed when treated as an unevaluated operand. ### Example ``` #include <forward_list> #include <vector> int main() { std::vector<int> v = {1, 2, 3, 4}; // uses explicit deduction guide to deduce std::forward_list<int> std::forward_list x(v.begin(), v.end()); // deduces std::forward_list<std::vector<int>::iterator> // first phase of overload resolution for list-initialization selects the candidate // synthesized from the initializer-list constructor; second phase is not performed and // deduction guide has no effect std::forward_list y{v.begin(), v.end()}; } ``` cpp std::forward_list<T,Allocator>::forward_list std::forward\_list<T,Allocator>::forward\_list ============================================== | | | | | --- | --- | --- | | ``` forward_list(); ``` | (1) | | | ``` explicit forward_list( const Allocator& alloc ); ``` | (2) | | | ``` forward_list( size_type count, const T& value, const Allocator& alloc = Allocator()); ``` | (3) | (since C++11) | | | (4) | | | ``` explicit forward_list( size_type count ); ``` | (since C++11) (until C++14) | | ``` explicit forward_list( size_type count, const Allocator& alloc = Allocator() ); ``` | (since C++14) | | ``` template< class InputIt > forward_list( InputIt first, InputIt last, const Allocator& alloc = Allocator() ); ``` | (5) | (since C++11) | | ``` forward_list( const forward_list& other ); ``` | (6) | (since C++11) | | ``` forward_list( const forward_list& other, const Allocator& alloc ); ``` | (7) | (since C++11) | | ``` forward_list( forward_list&& other ); ``` | (8) | (since C++11) | | ``` forward_list( forward_list&& other, const Allocator& alloc ); ``` | (9) | (since C++11) | | ``` forward_list( std::initializer_list<T> init, const Allocator& alloc = Allocator() ); ``` | (10) | (since C++11) | Constructs a new container from a variety of data sources, optionally using a user supplied allocator `alloc`. 1) Default constructor. Constructs an empty container with a default-constructed allocator. 2) Constructs an empty container with the given allocator `alloc`. 3) Constructs the container with `count` copies of elements with value `value`. 4) Constructs the container with `count` [default-inserted](../../named_req/defaultinsertable "cpp/named req/DefaultInsertable") instances of `T`. No copies are made. 5) Constructs the container with the contents of the range `[first, last)`. | | | | --- | --- | | This constructor has the same effect as `forward_list(static_cast<size_type>(first), static_cast<value_type>(last), a)` if `InputIt` is an integral type. | (until C++11) | | This overload participates in overload resolution only if `InputIt` satisfies [LegacyInputIterator](../../named_req/inputiterator "cpp/named req/InputIterator"), to avoid ambiguity with the overload (3). | (since C++11) | 6) Copy constructor. Constructs the container with the copy of the contents of `other`. | | | | --- | --- | | The allocator is obtained as if by calling `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<allocator_type>::select\_on\_container\_copy\_construction( other.get\_allocator())`. | (since C++11) | 7) Constructs the container with the copy of the contents of `other`, using `alloc` as the allocator. | | | | --- | --- | | The template parameter `Allocator` is only deduced from the first argument while used in [class template argument deduction](../../language/class_template_argument_deduction "cpp/language/class template argument deduction"). | (since C++23) | 8) Move constructor. Constructs the container with the contents of `other` using move semantics. Allocator is obtained by move-construction from the allocator belonging to `other`. 9) Allocator-extended move constructor. Using `alloc` as the allocator for the new container, moving the contents from `other`; if `alloc != other.get_allocator()`, this results in an element-wise move. | | | | --- | --- | | The template parameter `Allocator` is only deduced from the first argument while used in [class template argument deduction](../../language/class_template_argument_deduction "cpp/language/class template argument deduction"). | (since C++23) | 10) Constructs the container with the contents of the initializer list `init`. ### Parameters | | | | | --- | --- | --- | | alloc | - | allocator to use for all memory allocations of this container | | count | - | the size of the container | | value | - | the value to initialize elements of the container with | | first, last | - | the range to copy the elements from | | other | - | another container to be used as source to initialize the elements of the container with | | init | - | initializer list to initialize the elements of the container with | ### Complexity 1-2) Constant 3-4) Linear in `count` 5) Linear in distance between `first` and `last` 6-7) Linear in size of `other` 8) Constant. 9) Linear if `alloc != other.get_allocator()`, otherwise constant. 10) Linear in size of `init`. ### Exceptions Calls to `Allocator::allocate` may throw. ### Notes After container move construction (overload (8)), references, pointers, and iterators (other than the end iterator) to `other` remain valid, but refer to elements that are now in `*this`. The current standard makes this guarantee via the blanket statement in [[container.requirements.general]/12](https://eel.is/c++draft/container.requirements.general#12), and a more direct guarantee is under consideration via [LWG 2321](https://cplusplus.github.io/LWG/issue2321). ### Example ``` #include <forward_list> #include <string> #include <iostream> template<typename T> std::ostream& operator<<(std::ostream& s, const std::forward_list<T>& v) { s.put('['); char comma[3] = {'\0', ' ', '\0'}; for (const auto& e : v) { s << comma << e; comma[0] = ','; } return s << ']'; } int main() { // c++11 initializer list syntax: std::forward_list<std::string> words1 {"the", "frogurt", "is", "also", "cursed"}; std::cout << "words1: " << words1 << '\n'; // words2 == words1 std::forward_list<std::string> words2(words1.begin(), words1.end()); std::cout << "words2: " << words2 << '\n'; // words3 == words1 std::forward_list<std::string> words3(words1); std::cout << "words3: " << words3 << '\n'; // words4 is {"Mo", "Mo", "Mo", "Mo", "Mo"} std::forward_list<std::string> words4(5, "Mo"); std::cout << "words4: " << words4 << '\n'; } ``` Output: ``` words1: [the, frogurt, is, also, cursed] words2: [the, frogurt, is, also, cursed] words3: [the, frogurt, is, also, cursed] words4: [Mo, Mo, Mo, Mo, Mo] ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 2193](https://cplusplus.github.io/LWG/issue2193) | C++11 | the default constructor is explicit | made non-explicit | ### See also | | | | --- | --- | | [assign](assign "cpp/container/forward list/assign") (C++11) | assigns values to the container (public member function) | | [operator=](operator= "cpp/container/forward list/operator=") (C++11) | assigns values to the container (public member function) | cpp std::forward_list<T,Allocator>::get_allocator std::forward\_list<T,Allocator>::get\_allocator =============================================== | | | | | --- | --- | --- | | ``` allocator_type get_allocator() const noexcept; ``` | | (since C++11) | Returns the allocator associated with the container. ### Parameters (none). ### Return value The associated allocator. ### Complexity Constant. cpp std::forward_list<T,Allocator>::merge std::forward\_list<T,Allocator>::merge ====================================== | | | | | --- | --- | --- | | ``` void merge( forward_list& other ); ``` | (1) | (since C++11) | | ``` void merge( forward_list&& other ); ``` | (1) | (since C++11) | | ``` template <class Compare> void merge( forward_list& other, Compare comp ); ``` | (2) | (since C++11) | | ``` template <class Compare> void merge( forward_list&& other, Compare comp ); ``` | (2) | (since C++11) | Merges two sorted lists into one. The lists should be sorted into ascending order. No elements are copied. The container `other` becomes empty after the operation. The function does nothing if `other` refers to the same object as `*this`. If `get_allocator() != other.get_allocator()`, the behavior is undefined. No iterators or references become invalidated, except that the iterators of moved elements now refer into `*this`, not into `other`. The first version uses `operator<` to compare the elements, the second version uses the given comparison function `comp`. This operation is stable: for equivalent elements in the two lists, the elements from `*this` shall always precede the elements from `other`, and the order of equivalent elements of `*this` and `other` does not change. ### Parameters | | | | | --- | --- | --- | | other | - | another container to merge | | comp | - | comparison function object (i.e. an object that satisfies the requirements of [Compare](../../named_req/compare "cpp/named req/Compare")) which returns ​`true` if the first argument is *less* than (i.e. is ordered *before*) the second. The signature of the comparison function should be equivalent to the following: `bool cmp(const Type1 &a, const Type2 &b);` While the signature does not need to have `const &`, the function must not modify the objects passed to it and must be able to accept all values of type (possibly const) `Type1` and `Type2` regardless of [value category](../../language/value_category "cpp/language/value category") (thus, `Type1 &` is not allowed, nor is `Type1` unless for `Type1` a move is equivalent to a copy (since C++11)). The types `Type1` and `Type2` must be such that an object of type `forward_list<T,Allocator>::const_iterator` can be dereferenced and then implicitly converted to both of them. ​ | ### Return value (none). ### Exceptions If an exception is thrown, this function has no effect (strong exception guarantee), except if the exception comes from the comparison function. ### Complexity At most `[std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(begin(), end()) + [std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(other.begin(), other.end()) - 1` comparisons. ### Example ``` #include <iostream> #include <forward_list> std::ostream& operator<<(std::ostream& ostr, const std::forward_list<int>& list) { for (const auto &i : list) { ostr << ' ' << i; } return ostr; } int main() { std::forward_list<int> list1 = { 5,9,1,3,3 }; std::forward_list<int> list2 = { 8,7,2,3,4,4 }; list1.sort(); list2.sort(); std::cout << "list1: " << list1 << '\n'; std::cout << "list2: " << list2 << '\n'; list1.merge(list2); std::cout << "merged: " << list1 << '\n'; } ``` Output: ``` list1: 1 3 3 5 9 list2: 2 3 4 4 7 8 merged: 1 2 3 3 3 4 4 5 7 8 9 ``` ### See also | | | | --- | --- | | [splice\_after](splice_after "cpp/container/forward list/splice after") (C++11) | moves elements from another `forward_list` (public member function) | | [merge](../../algorithm/merge "cpp/algorithm/merge") | merges two sorted ranges (function template) | | [inplace\_merge](../../algorithm/inplace_merge "cpp/algorithm/inplace merge") | merges two ordered ranges in-place (function template) | | [ranges::merge](../../algorithm/ranges/merge "cpp/algorithm/ranges/merge") (C++20) | merges two sorted ranges (niebloid) | | [ranges::inplace\_merge](../../algorithm/ranges/inplace_merge "cpp/algorithm/ranges/inplace merge") (C++20) | merges two ordered ranges in-place (niebloid) |
programming_docs
cpp std::forward_list<T,Allocator>::push_front std::forward\_list<T,Allocator>::push\_front ============================================ | | | | | --- | --- | --- | | ``` void push_front( const T& value ); ``` | | (since C++11) | | ``` void push_front( T&& value ); ``` | | (since C++11) | Prepends the given element `value` to the beginning of the container. No iterators or references are invalidated. ### Parameters | | | | | --- | --- | --- | | value | - | the value of the element to prepend | ### Return value (none). ### Complexity Constant. ### Exceptions If an exception is thrown, this function has no effect (strong exception guarantee). ### Example ``` #include <forward_list> #include <iostream> #include <iomanip> #include <string> int main() { std::forward_list<std::string> letters; letters.push_front("abc"); std::string s{"def"}; letters.push_front(std::move(s)); std::cout << "std::forward_list `letters` holds: "; for (auto&& e : letters) std::cout << std::quoted(e) << ' '; std::cout << "\nMoved-from string `s` holds: " << std::quoted(s) << '\n'; } ``` Possible output: ``` std::forward_list `letters` holds: "def" "abc" Moved-from string `s` holds: "" ``` ### See also | | | | --- | --- | | [emplace\_front](emplace_front "cpp/container/forward list/emplace front") (C++11) | constructs an element in-place at the beginning (public member function) | | [pop\_front](pop_front "cpp/container/forward list/pop front") (C++11) | removes the first element (public member function) | | [front\_inserter](../../iterator/front_inserter "cpp/iterator/front inserter") | creates a `[std::front\_insert\_iterator](../../iterator/front_insert_iterator "cpp/iterator/front insert iterator")` of type inferred from the argument (function template) | cpp std::forward_list<T,Allocator>::reverse std::forward\_list<T,Allocator>::reverse ======================================== | | | | | --- | --- | --- | | ``` void reverse() noexcept; ``` | | (since C++11) | Reverses the order of the elements in the container. No references or iterators become invalidated. ### Parameters (none). ### Return value (none). ### Complexity Linear in the size of the container. ### Example ``` #include <iostream> #include <forward_list> std::ostream& operator<<(std::ostream& ostr, const std::forward_list<int>& list) { for (auto &i : list) { ostr << " " << i; } return ostr; } int main() { std::forward_list<int> list = { 8,7,5,9,0,1,3,2,6,4 }; std::cout << "before: " << list << "\n"; list.sort(); std::cout << "ascending: " << list << "\n"; list.reverse(); std::cout << "descending: " << list << "\n"; } ``` Output: ``` before: 8 7 5 9 0 1 3 2 6 4 ascending: 0 1 2 3 4 5 6 7 8 9 descending: 9 8 7 6 5 4 3 2 1 0 ``` ### See also | | | | --- | --- | | [sort](sort "cpp/container/forward list/sort") (C++11) | sorts the elements (public member function) | cpp std::forward_list<T,Allocator>::swap std::forward\_list<T,Allocator>::swap ===================================== | | | | | --- | --- | --- | | ``` void swap( forward_list& other ); ``` | | (since C++11) (until C++17) | | ``` void swap( forward_list& other ) noexcept(/* see below */); ``` | | (since C++17) | Exchanges the contents of the container with those of `other`. Does not invoke any move, copy, or swap operations on individual elements. All iterators and references remain valid. It is unspecified whether an iterator holding the past-the-end value in this container will refer to this or the other container after the operation. | | | | --- | --- | | If `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<allocator_type>::propagate\_on\_container\_swap::value` is true, then the allocators are exchanged using an unqualified call to non-member `swap`. Otherwise, they are not swapped (and if `get_allocator() != other.get_allocator()`, the behavior is undefined). | (since C++11) | ### Parameters | | | | | --- | --- | --- | | other | - | container to exchange the contents with | ### Return value (none). ### Exceptions | | | | --- | --- | | (none). | (until C++17) | | [`noexcept`](../../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept([std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<Allocator>::is\_always\_equal::value)` | (since C++17) | ### Complexity Constant. ### Example ``` #include <iostream> #include <forward_list> template<class Os, class Co> Os& operator<<(Os& os, const Co& co) { os << "{"; for (auto const& i : co) { os << ' ' << i; } return os << " } "; } int main() { std::forward_list<int> a1{1, 2, 3}, a2{4, 5}; auto it1 = std::next(a1.begin()); auto it2 = std::next(a2.begin()); int& ref1 = a1.front(); int& ref2 = a2.front(); std::cout << a1 << a2 << *it1 << ' ' << *it2 << ' ' << ref1 << ' ' << ref2 << '\n'; a1.swap(a2); std::cout << a1 << a2 << *it1 << ' ' << *it2 << ' ' << ref1 << ' ' << ref2 << '\n'; // Note that after swap the iterators and references stay associated with their // original elements, e.g. it1 that pointed to an element in 'a1' with value 2 // still points to the same element, though this element was moved into 'a2'. } ``` Output: ``` { 1 2 3 } { 4 5 } 2 5 1 4 { 4 5 } { 1 2 3 } 2 5 1 4 ``` ### See also | | | | --- | --- | | [std::swap(std::forward\_list)](swap2 "cpp/container/forward list/swap2") (C++11) | specializes the `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | cpp std::forward_list<T,Allocator>::max_size std::forward\_list<T,Allocator>::max\_size ========================================== | | | | | --- | --- | --- | | ``` size_type max_size() const noexcept; ``` | | (since C++11) | Returns the maximum number of elements the container is able to hold due to system or library implementation limitations, i.e. `[std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(begin(), end())` for the largest container. ### Parameters (none). ### Return value Maximum number of elements. ### Complexity Constant. ### Notes This value typically reflects the theoretical limit on the size of the container, at most `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<difference_type>::max()`. At runtime, the size of the container may be limited to a value smaller than `max_size()` by the amount of RAM available. ### Example ``` #include <iostream> #include <locale> #include <forward_list> int main() { std::forward_list<char> q; std::cout.imbue(std::locale("en_US.UTF-8")); std::cout << "Maximum size of a std::forward_list is " << q.max_size() << '\n'; } ``` Possible output: ``` Maximum size of a std::forward_list is 1,152,921,504,606,846,975 ``` cpp std::forward_list<T,Allocator>::remove, remove_if std::forward\_list<T,Allocator>::remove, remove\_if =================================================== | | | | | --- | --- | --- | | | (1) | | | ``` void remove( const T& value ); ``` | (since C++11) (until C++20) | | ``` size_type remove( const T& value ); ``` | (since C++20) | | | (2) | | | ``` template< class UnaryPredicate > void remove_if( UnaryPredicate p ); ``` | (since C++11) (until C++20) | | ``` template< class UnaryPredicate > size_type remove_if( UnaryPredicate p ); ``` | (since C++20) | Removes all elements satisfying specific criteria. 1) Removes all elements that are equal to `value`. 2) Removes all elements for which predicate `p` returns `true`. ### Parameters | | | | | --- | --- | --- | | value | - | value of the elements to remove | | p | - | unary predicate which returns ​`true` if the element should be removed. The expression `p(v)` must be convertible to `bool` for every argument `v` of type (possibly const) `T`, regardless of [value category](../../language/value_category "cpp/language/value category"), and must not modify `v`. Thus, a parameter type of `T&`is not allowed, nor is `T` unless for `T` a move is equivalent to a copy (since C++11). ​ | ### Return value | | | | --- | --- | | (none). | (until C++20) | | The number of elements removed. | (since C++20) | ### Complexity Linear in the size of the container. ### Notes | [Feature-test](../../utility/feature_test "cpp/utility/feature test") macro | | --- | | [`__cpp_lib_list_remove_return_type`](../../feature_test#Library_features "cpp/feature test") | ### Example ``` #include <forward_list> #include <iostream> int main() { std::forward_list<int> l = { 1,100,2,3,10,1,11,-1,12 }; auto count1 = l.remove(1); std::cout << count1 << " elements equal to 1 were removed\n"; auto count2 = l.remove_if([](int n){ return n > 10; }); std::cout << count2 << " elements greater than 10 were removed\n"; std::cout << "Finally, the list contains: "; for (int n : l) { std::cout << n << ' '; } std::cout << '\n'; } ``` Output: ``` 2 elements equal to 1 were removed 3 elements greater than 10 were removed Finally, the list contains: 2 3 10 -1 ``` ### See also | | | | --- | --- | | [removeremove\_if](../../algorithm/remove "cpp/algorithm/remove") | removes elements satisfying specific criteria (function template) | cpp std::forward_list<T,Allocator>::assign std::forward\_list<T,Allocator>::assign ======================================= | | | | | --- | --- | --- | | ``` void assign( size_type count, const T& value ); ``` | (1) | (since C++11) | | ``` template< class InputIt > void assign( InputIt first, InputIt last ); ``` | (2) | (since C++11) | | ``` void assign( std::initializer_list<T> ilist ); ``` | (3) | (since C++11) | Replaces the contents of the container. 1) Replaces the contents with `count` copies of value `value` 2) Replaces the contents with copies of those in the range `[first, last)`. The behavior is undefined if either argument is an iterator into `*this`. | | | | --- | --- | | This overload has the same effect as overload (1) if `InputIt` is an integral type. | (until C++11) | | This overload participates in overload resolution only if `InputIt` satisfies [LegacyInputIterator](../../named_req/inputiterator "cpp/named req/InputIterator"). | (since C++11) | 3) Replaces the contents with the elements from the initializer list `ilist`. All iterators, pointers and references to the elements of the container are invalidated. ### Parameters | | | | | --- | --- | --- | | count | - | the new size of the container | | value | - | the value to initialize elements of the container with | | first, last | - | the range to copy the elements from | | ilist | - | initializer list to copy the values from | ### Complexity 1) Linear in `count` 2) Linear in distance between `first` and `last` 3) Linear in `ilist.size()` ### Example The following code uses `assign` to add several characters to a `[std::forward\_list](http://en.cppreference.com/w/cpp/container/forward_list)<char>`: ``` #include <forward_list> #include <iostream> #include <string> int main() { std::forward_list<char> characters; auto print_forward_list = [&](){ for (char c : characters) std::cout << c << ' '; std::cout << '\n'; }; characters.assign(5, 'a'); print_forward_list(); const std::string extra(6, 'b'); characters.assign(extra.begin(), extra.end()); print_forward_list(); characters.assign({'C', '+', '+', '1', '1'}); print_forward_list(); } ``` Output: ``` a a a a a b b b b b b C + + 1 1 ``` ### See also | | | | --- | --- | | [(constructor)](forward_list "cpp/container/forward list/forward list") (C++11) | constructs the `forward_list` (public member function) | cpp std::forward_list<T,Allocator>::splice_after std::forward\_list<T,Allocator>::splice\_after ============================================== | | | | | --- | --- | --- | | ``` void splice_after( const_iterator pos, forward_list& other ); ``` | (1) | (since C++11) | | ``` void splice_after( const_iterator pos, forward_list&& other ); ``` | (1) | (since C++11) | | ``` void splice_after( const_iterator pos, forward_list& other, const_iterator it ); ``` | (2) | (since C++11) | | ``` void splice_after( const_iterator pos, forward_list&& other, const_iterator it ); ``` | (2) | (since C++11) | | ``` void splice_after( const_iterator pos, forward_list& other, const_iterator first, const_iterator last ); ``` | (3) | (since C++11) | | ``` void splice_after( const_iterator pos, forward_list&& other, const_iterator first, const_iterator last ); ``` | (3) | (since C++11) | Moves elements from another `forward_list` to `*this`. No elements are copied. `pos` must be either a deferenceable valid iterator into `*this` or the `[before\_begin()](before_begin "cpp/container/forward list/before begin")` iterator (in particular, `[end()](end "cpp/container/forward list/end")` is not a valid argument for `pos`). The behavior is undefined if `get_allocator() != other.get_allocator()`. No iterators or references become invalidated, the iterators to the moved elements now refer into `*this`, not into `other`. 1) Moves all elements from `other` into `*this`. The elements are inserted after the element pointed to by `pos`. The container `other` becomes empty after the operation. The behavior is undefined if `other` refers to the same object as `*this`. 2) Moves the element pointed to by the iterator following `it` from `other` into `*this`. The element is inserted after the element pointed to by `pos`. Has no effect if `pos==it` or if `pos==++it`. 3) Moves the elements in the range `(first, last)` from `other` into `*this`. The elements are inserted after the element pointed to by `pos`. The element pointed-to by `first` is not moved. The behavior is undefined if `pos` is an iterator in the range `(first,last)`. ### Parameters | | | | | --- | --- | --- | | pos | - | element after which the content will be inserted | | other | - | another container to move the content from | | it | - | iterator preceding the iterator to the element to move from `other` to `*this` | | first, last | - | the range of elements to move from `other` to `*this` | ### Return value (none). ### Exceptions Throws nothing. ### Complexity 1) Linear in the size of `other` 2) Constant 3) Linear in `[std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(first, last)` ### Example Demonstrates the meaning of open interval (first, last) in the third form of splice\_after(): the first element of l1 is not moved. ``` #include <algorithm> #include <cassert> #include <forward_list> #include <initializer_list> #include <iostream> using F = std::forward_list<int>; std::ostream& operator<< (std::ostream& os, F const& l) { for (int e : l) os << e << ' '; return os; } int main() { { F l1 = { 1, 2, 3, 4, 5 }; F l2 = { 10, 11, 12 }; l2.splice_after(l2.cbegin(), l1, l1.cbegin(), l1.cend()); // not equivalent to l2.splice_after(l2.cbegin(), l1); // which is equivalent to // l2.splice_after(l2.cbegin(), l1, l1.cbefore_begin(), l1.end()); std::cout << "l1: " << l1 << "\n" "l2: " << l2 << '\n'; } // Compare two given lists and abort the program if they are not equal. auto equ = [] (F const& p, std::initializer_list<int> const& q) { assert(std::ranges::equal(p, q)); }; // The following code demonstrates all three overloads (1),..(3). { F x = { 1, 2, 3, 4, 5 }; F y = { 10, 11, 12 }; x.splice_after(x.cbegin(), y); // (1) equ( x, { 1, 10, 11, 12, 2, 3, 4, 5 } ); equ( y, { } ); } { F x = { 1, 2, 3, 4, 5 }; F y = { 10, 11, 12 }; x.splice_after(x.cbegin(), y, y.cbegin()); // (2) equ( x, { 1, 11, 2, 3, 4, 5 } ); equ( y, { 10, 12 } ); } { F x = { 1, 2, 3, 4, 5 }; F y = { 10, 11, 12 }; x.splice_after(x.cbegin(), y, y.cbegin(), y.cend()); // (3) equ( x, { 1, 11, 12, 2, 3, 4, 5 } ); equ( y, { 10 } ); } } ``` Output: ``` l1: 1 l2: 10 2 3 4 5 11 12 ``` ### See also | | | | --- | --- | | [merge](merge "cpp/container/forward list/merge") (C++11) | merges two sorted lists (public member function) | | [removeremove\_if](remove "cpp/container/forward list/remove") (C++11) | removes elements satisfying specific criteria (public member function) | | [before\_begincbefore\_begin](before_begin "cpp/container/forward list/before begin") (C++11) | returns an iterator to the element before beginning (public member function) | cpp std::forward_list<T,Allocator>::pop_front std::forward\_list<T,Allocator>::pop\_front =========================================== | | | | | --- | --- | --- | | ``` void pop_front(); ``` | | (since C++11) | Removes the first element of the container. If there are no elements in the container, the behavior is undefined. References and iterators to the erased element are invalidated. ### Parameters (none). ### Return value (none). ### Complexity Constant. ### Exceptions Does not throw. ### Example ``` #include <forward_list> #include <iostream> int main() { std::forward_list<char> chars{'A', 'B', 'C', 'D'}; for (; !chars.empty(); chars.pop_front()) { std::cout << "chars.front(): '" << chars.front() << "'\n"; } } ``` Output: ``` chars.front(): 'A' chars.front(): 'B' chars.front(): 'C' chars.front(): 'D' ``` ### See also | | | | --- | --- | | [push\_front](push_front "cpp/container/forward list/push front") (C++11) | inserts an element to the beginning (public member function) | | [front](front "cpp/container/forward list/front") (C++11) | access the first element (public member function) | cpp std::forward_list<T,Allocator>::insert_after std::forward\_list<T,Allocator>::insert\_after ============================================== | | | | | --- | --- | --- | | ``` iterator insert_after( const_iterator pos, const T& value ); ``` | (1) | (since C++11) | | ``` iterator insert_after( const_iterator pos, T&& value ); ``` | (2) | (since C++11) | | ``` iterator insert_after( const_iterator pos, size_type count, const T& value ); ``` | (3) | (since C++11) | | ``` template< class InputIt > iterator insert_after( const_iterator pos, InputIt first, InputIt last ); ``` | (4) | (since C++11) | | ``` iterator insert_after( const_iterator pos, std::initializer_list<T> ilist ); ``` | (5) | (since C++11) | Inserts elements after the specified position in the container. 1-2) inserts `value` after the element pointed to by `pos` 3) inserts `count` copies of the `value` after the element pointed to by `pos` 4) inserts elements from range `[first, last)` after the element pointed to by `pos`. The behavior is undefined if `first` and `last` are iterators into `*this`. 5) inserts elements from initializer list `ilist`. No iterators or references are invalidated. ### Parameters | | | | | --- | --- | --- | | pos | - | iterator after which the content will be inserted | | value | - | element value to insert | | count | - | number of copies to insert | | first, last | - | the range of elements to insert | | ilist | - | initializer list to insert the values from | | Type requirements | | -`InputIt` must meet the requirements of [LegacyInputIterator](../../named_req/inputiterator "cpp/named req/InputIterator"). | ### Return value 1-2) Iterator to the inserted element. 3) Iterator to the last element inserted, or `pos` if `count==0`. 4) Iterator to the last element inserted, or `pos` if `first==last`. 5) Iterator to the last element inserted, or `pos` if `ilist` is empty. ### Exceptions If an exception is thrown during `insert_after` there are no effects (strong exception guarantee). ### Complexity 1-2) Constant. 3) Linear in `count` 4) Linear in `[std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(first, last)` 5) Linear in `ilist.size()` ### Example ``` #include <forward_list> #include <string> #include <iostream> #include <vector> template<typename T> std::ostream& operator<<(std::ostream& s, const std::forward_list<T>& v) { s.put('['); char comma[3] = {'\0', ' ', '\0'}; for (const auto& e : v) { s << comma << e; comma[0] = ','; } return s << ']'; } int main() { std::forward_list<std::string> words {"the", "frogurt", "is", "also", "cursed"}; std::cout << "words: " << words << '\n'; // insert_after (2) auto beginIt = words.begin(); words.insert_after(beginIt, "strawberry"); std::cout << "words: " << words << '\n'; // insert_after (3) auto anotherIt = beginIt; ++anotherIt; anotherIt = words.insert_after(anotherIt, 2, "strawberry"); std::cout << "words: " << words << '\n'; // insert_after (4) std::vector<std::string> V = { "apple", "banana", "cherry"}; anotherIt = words.insert_after(anotherIt, V.begin(), V.end()); std::cout << "words: " << words << '\n'; // insert_after (5) words.insert_after(anotherIt, {"jackfruit", "kiwifruit", "lime", "mango"}); std::cout << "words: " << words << '\n'; } ``` Output: ``` words: [the, frogurt, is, also, cursed] words: [the, strawberry, frogurt, is, also, cursed] words: [the, strawberry, strawberry, strawberry, frogurt, is, also, cursed] words: [the, strawberry, strawberry, strawberry, apple, banana, cherry, frogurt, is, also, cursed] words: [the, strawberry, strawberry, strawberry, apple, banana, cherry, jackfruit, kiwifruit, lime, mango, frogurt, is, also, cursed] ``` ### See also | | | | --- | --- | | [emplace\_after](emplace_after "cpp/container/forward list/emplace after") (C++11) | constructs elements in-place after an element (public member function) | | [push\_front](push_front "cpp/container/forward list/push front") (C++11) | inserts an element to the beginning (public member function) |
programming_docs
cpp std::forward_list<T,Allocator>::resize std::forward\_list<T,Allocator>::resize ======================================= | | | | | --- | --- | --- | | ``` void resize( size_type count ); ``` | (1) | (since C++11) | | ``` void resize( size_type count, const value_type& value ); ``` | (2) | (since C++11) | Resizes the container to contain `count` elements. If the current size is greater than `count`, the container is reduced to its first `count` elements. If the current size is less than `count`, 1) additional [default-inserted](../../named_req/defaultinsertable "cpp/named req/DefaultInsertable") elements are appended 2) additional copies of `value` are appended. ### Parameters | | | | | --- | --- | --- | | count | - | new size of the container | | value | - | the value to initialize the new elements with | | Type requirements | | -`T` must meet the requirements of [DefaultInsertable](../../named_req/defaultinsertable "cpp/named req/DefaultInsertable") in order to use overload (1). | | -`T` must meet the requirements of [CopyInsertable](../../named_req/copyinsertable "cpp/named req/CopyInsertable") in order to use overload (2). | ### Return value (none). ### Complexity Linear in the difference between the current size and `count`. Additional complexity possible due to list traversal to reach the first element to erase/the end position to insert. ### Notes If value-initialization in overload (1) is undesirable, for example, if the elements are of non-class type and zeroing out is not needed, it can be avoided by providing a [custom `Allocator::construct`](http://stackoverflow.com/a/21028912/273767). ### Example ``` #include <iostream> #include <forward_list> int main() { std::forward_list<int> c = {1, 2, 3}; std::cout << "The forward_list holds: "; for(const auto& el: c) std::cout << el << ' '; std::cout << '\n'; c.resize(5); std::cout << "After resize up to 5: "; for(const auto& el: c) std::cout << el << ' '; std::cout << '\n'; c.resize(2); std::cout << "After resize down to 2: "; for(const auto& el: c) std::cout << el << ' '; std::cout << '\n'; c.resize(6, 4); std::cout << "After resize up to 6 (initializer = 4): "; for(const auto& el: c) std::cout << el << ' '; std::cout << '\n'; } ``` Output: ``` The forward_list holds: 1 2 3 After resize up to 5: 1 2 3 0 0 After resize down to 2: 1 2 After resize up to 6 (initializer = 4): 1 2 4 4 4 4 ``` ### See also | | | | --- | --- | | [insert\_after](insert_after "cpp/container/forward list/insert after") (C++11) | inserts elements after an element (public member function) | | [erase\_after](erase_after "cpp/container/forward list/erase after") (C++11) | erases an element after an element (public member function) | cpp std::swap(std::forward_list) std::swap(std::forward\_list) ============================= | Defined in header `[<forward\_list>](../../header/forward_list "cpp/header/forward list")` | | | | --- | --- | --- | | ``` template< class T, class Alloc > void swap( std::forward_list<T,Alloc>& lhs, std::forward_list<T,Alloc>& rhs ); ``` | | (since C++11) (until C++17) | | ``` template< class T, class Alloc > void swap( std::forward_list<T,Alloc>& lhs, std::forward_list<T,Alloc>& rhs ) noexcept(/* see below */); ``` | | (since C++17) | Specializes the `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` algorithm for `[std::forward\_list](http://en.cppreference.com/w/cpp/container/forward_list)`. Swaps the contents of `lhs` and `rhs`. Calls `lhs.swap(rhs)`. ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | containers whose contents to swap | ### Return value (none). ### Complexity Constant. ### Exceptions | | | | --- | --- | | [`noexcept`](../../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept(noexcept(lhs.swap(rhs)))` | (since C++17) | ### Notes Although the overloads of `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` for container adaptors are introduced in C++11, container adaptors can already be swapped by `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` in C++98. Such calls to `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` usually have linear time complexity, but better complexity may be provided. ### Example ``` #include <algorithm> #include <iostream> #include <forward_list> int main() { std::forward_list<int> alice{1, 2, 3}; std::forward_list<int> bob{7, 8, 9, 10}; auto print = [](const int& n) { std::cout << ' ' << n; }; // Print state before swap std::cout << "alice:"; std::for_each(alice.begin(), alice.end(), print); std::cout << "\n" "bob :"; std::for_each(bob.begin(), bob.end(), print); std::cout << '\n'; std::cout << "-- SWAP\n"; std::swap(alice, bob); // Print state after swap std::cout << "alice:"; std::for_each(alice.begin(), alice.end(), print); std::cout << "\n" "bob :"; std::for_each(bob.begin(), bob.end(), print); std::cout << '\n'; } ``` Output: ``` alice: 1 2 3 bob : 7 8 9 10 -- SWAP alice: 7 8 9 10 bob : 1 2 3 ``` ### See also | | | | --- | --- | | [swap](swap "cpp/container/forward list/swap") (C++11) | swaps the contents (public member function) | cpp std::forward_list<T,Allocator>::~forward_list std::forward\_list<T,Allocator>::~forward\_list =============================================== | | | | | --- | --- | --- | | ``` ~forward_list(); ``` | | (since C++11) | Destructs the `forward_list`. The destructors of the elements are called and the used storage is deallocated. Note, that if the elements are pointers, the pointed-to objects are not destroyed. ### Complexity Linear in the size of the `forward_list`. cpp std::forward_list<T,Allocator>::front std::forward\_list<T,Allocator>::front ====================================== | | | | | --- | --- | --- | | ``` reference front(); ``` | | (since C++11) | | ``` const_reference front() const; ``` | | (since C++11) | Returns a reference to the first element in the container. Calling `front` on an empty container is undefined. ### Parameters (none). ### Return value reference to the first element. ### Complexity Constant. ### Notes For a container `c`, the expression `c.front()` is equivalent to `*c.begin()`. ### Example The following code uses `front` to display the first element of a `[std::forward\_list](http://en.cppreference.com/w/cpp/container/forward_list)<char>`: ``` #include <forward_list> #include <iostream> int main() { std::forward_list<char> letters {'o', 'm', 'g', 'w', 't', 'f'}; if (!letters.empty()) { std::cout << "The first character is '" << letters.front() << "'.\n"; } } ``` Output: ``` The first character is 'o'. ``` cpp std::forward_list<T,Allocator>::operator= std::forward\_list<T,Allocator>::operator= ========================================== | | | | | --- | --- | --- | | ``` forward_list& operator=( const forward_list& other ); ``` | (1) | (since C++11) | | | (2) | | | ``` forward_list& operator=( forward_list&& other ); ``` | (since C++11) (until C++17) | | ``` forward_list& operator=( forward_list&& other ) noexcept(/* see below */); ``` | (since C++17) | | ``` forward_list& operator=( std::initializer_list<T> ilist ); ``` | (3) | (since C++11) | Replaces the contents of the container. 1) Copy assignment operator. Replaces the contents with a copy of the contents of `other`. If `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<allocator_type>::propagate\_on\_container\_copy\_assignment::value` is `true`, the allocator of `*this` is replaced by a copy of that of `other`. If the allocator of `*this` after assignment would compare unequal to its old value, the old allocator is used to deallocate the memory, then the new allocator is used to allocate it before copying the elements. Otherwise, the memory owned by `*this` may be reused when possible. In any case, the elements originally belonging to `*this` may be either destroyed or replaced by element-wise copy-assignment. 2) Move assignment operator. Replaces the contents with those of `other` using move semantics (i.e. the data in `other` is moved from `other` into this container). `other` is in a valid but unspecified state afterwards. If `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<allocator_type>::propagate\_on\_container\_move\_assignment::value` is `true`, the allocator of `*this` is replaced by a copy of that of `other`. If it is `false` and the allocators of `*this` and `other` do not compare equal, `*this` cannot take ownership of the memory owned by `other` and must move-assign each element individually, allocating additional memory using its own allocator as needed. In any case, all elements originally belonging to `*this` are either destroyed or replaced by element-wise move-assignment. 3) Replaces the contents with those identified by initializer list `ilist`. ### Parameters | | | | | --- | --- | --- | | other | - | another container to use as data source | | ilist | - | initializer list to use as data source | ### Return value `*this`. ### Complexity 1) Linear in the size of `*this` and `other`. 2) Linear in the size of `*this` unless the allocators do not compare equal and do not propagate, in which case linear in the size of `*this` and `other`. 3) Linear in the size of `*this` and `ilist`. ### Exceptions | | | | --- | --- | | May throw implementation-defined exceptions. | (until C++17) | | 1,3) May throw implementation-defined exceptions. 2) [`noexcept`](../../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept([std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<Allocator>::is\_always\_equal::value)` | (since C++17) | ### Notes After container move assignment (overload (2)), unless element-wise move assignment is forced by incompatible allocators, references, pointers, and iterators (other than the end iterator) to `other` remain valid, but refer to elements that are now in `*this`. The current standard makes this guarantee via the blanket statement in [[container.requirements.general]/12](https://eel.is/c++draft/container.requirements.general#12), and a more direct guarantee is under consideration via [LWG 2321](https://cplusplus.github.io/LWG/issue2321). ### Example The following code uses `operator=` to assign one `[std::forward\_list](../forward_list "cpp/container/forward list")` to another: ``` #include <forward_list> #include <iterator> #include <iostream> void print(auto const comment, auto const& container) { auto size = std::ranges::distance(container); std::cout << comment << "{ "; for (auto const& element: container) std::cout << element << (--size ? ", " : " "); std::cout << "}\n"; } int main() { std::forward_list<int> x { 1, 2, 3 }, y, z; const auto w = { 4, 5, 6, 7 }; std::cout << "Initially:\n"; print("x = ", x); print("y = ", y); print("z = ", z); std::cout << "Copy assignment copies data from x to y:\n"; y = x; print("x = ", x); print("y = ", y); std::cout << "Move assignment moves data from x to z, modifying both x and z:\n"; z = std::move(x); print("x = ", x); print("z = ", z); std::cout << "Assignment of initializer_list w to z:\n"; z = w; print("w = ", w); print("z = ", z); } ``` Output: ``` Initially: x = { 1, 2, 3 } y = { } z = { } Copy assignment copies data from x to y: x = { 1, 2, 3 } y = { 1, 2, 3 } Move assignment moves data from x to z, modifying both x and z: x = { } z = { 1, 2, 3 } Assignment of initializer_list w to z: w = { 4, 5, 6, 7 } z = { 4, 5, 6, 7 } ``` ### See also | | | | --- | --- | | [(constructor)](forward_list "cpp/container/forward list/forward list") (C++11) | constructs the `forward_list` (public member function) | | [assign](assign "cpp/container/forward list/assign") (C++11) | assigns values to the container (public member function) | cpp std::forward_list<T,Allocator>::clear std::forward\_list<T,Allocator>::clear ====================================== | | | | | --- | --- | --- | | ``` void clear() noexcept; ``` | | (since C++11) | Erases all elements from the container. Invalidates any references, pointers, or iterators referring to contained elements. Any past-the-end iterator remains valid. ### Parameters (none). ### Return value (none). ### Complexity Linear in the size of the container, i.e., the number of elements. ### Example ``` #include <algorithm> #include <iostream> #include <forward_list> int main() { std::forward_list<int> container{1, 2, 3}; auto print = [](const int& n) { std::cout << " " << n; }; std::cout << "Before clear:"; std::for_each(container.begin(), container.end(), print); std::cout << '\n'; std::cout << "Clear\n"; container.clear(); std::cout << "After clear:"; std::for_each(container.begin(), container.end(), print); std::cout << '\n'; } ``` Output: ``` Before clear: 1 2 3 Clear After clear: ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 2231](https://cplusplus.github.io/LWG/issue2231) | C++11 | complexity guarantee was mistakenly omitted in C++11 | complexity reaffirmed as linear | ### See also | | | | --- | --- | | [erase\_after](erase_after "cpp/container/forward list/erase after") (C++11) | erases an element after an element (public member function) | cpp std::forward_list<T,Allocator>::emplace_front std::forward\_list<T,Allocator>::emplace\_front =============================================== | | | | | --- | --- | --- | | ``` template< class... Args > void emplace_front( Args&&... args ); ``` | | (since C++11) (until C++17) | | ``` template< class... Args > reference emplace_front( Args&&... args ); ``` | | (since C++17) | Inserts a new element to the beginning of the container. The element is constructed through `[std::allocator\_traits::construct](../../memory/allocator_traits/construct "cpp/memory/allocator traits/construct")`, which typically uses placement-new to construct the element in-place at the location provided by the container. The arguments `args...` are forwarded to the constructor as `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Args>(args)...`. No iterators or references are invalidated. ### Parameters | | | | | --- | --- | --- | | args | - | arguments to forward to the constructor of the element | | Type requirements | | -`T (the container's element type)` must meet the requirements of [EmplaceConstructible](../../named_req/emplaceconstructible "cpp/named req/EmplaceConstructible"). | ### Return value | | | | --- | --- | | (none) | (until C++17) | | A reference to the inserted element. | (since C++17) | ### Complexity Constant. ### Exceptions If an exception is thrown, this function has no effect (strong exception guarantee). ### See also | | | | --- | --- | | [push\_front](push_front "cpp/container/forward list/push front") (C++11) | inserts an element to the beginning (public member function) | cpp std::forward_list<T,Allocator>::erase_after std::forward\_list<T,Allocator>::erase\_after ============================================= | | | | | --- | --- | --- | | ``` iterator erase_after( const_iterator pos ); ``` | (1) | (since C++11) | | ``` iterator erase_after( const_iterator first, const_iterator last ); ``` | (2) | (since C++11) | Removes specified elements from the container. 1) Removes the element following `pos`. 2) Removes the elements following `first` until `last`. ### Parameters | | | | | --- | --- | --- | | pos | - | iterator to the element preceding the element to remove | | first, last | - | range of elements to remove | ### Return value 1) Iterator to the element following the erased one, or `[end()](end "cpp/container/forward list/end")` if no such element exists. 2) `last` ### Complexity 1) Constant. 2) Linear in distance between `first` and `last`. ### Example ``` #include <forward_list> #include <iterator> #include <iostream> int main() { std::forward_list<int> l = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; // l.erase( l.begin() ); // ERROR: No function erase l.erase_after( l.before_begin() ); // Removes first element for( auto n : l ) std::cout << n << " "; std::cout << '\n'; auto fi = std::next( l.begin() ); auto la = std::next( fi, 3 ); l.erase_after( fi, la ); for( auto n : l ) std::cout << n << " "; std::cout << '\n'; } ``` Output: ``` 2 3 4 5 6 7 8 9 2 3 6 7 8 9 ``` ### See also | | | | --- | --- | | [clear](clear "cpp/container/forward list/clear") (C++11) | clears the contents (public member function) | cpp std::forward_list<T,Allocator>::before_begin, cbefore_begin std::forward\_list<T,Allocator>::before\_begin, cbefore\_begin ============================================================== | | | | | --- | --- | --- | | ``` iterator before_begin() noexcept; ``` | | (since C++11) | | ``` const_iterator before_begin() const noexcept; ``` | | (since C++11) | | ``` const_iterator cbefore_begin() const noexcept; ``` | | (since C++11) | Returns an iterator to the element before the first element of the container. This element acts as a placeholder, attempting to access it results in undefined behavior. The only usage cases are in functions `[insert\_after()](insert_after "cpp/container/forward list/insert after")`, `[emplace\_after()](emplace_after "cpp/container/forward list/emplace after")`, `[erase\_after()](erase_after "cpp/container/forward list/erase after")`, `[splice\_after()](splice_after "cpp/container/forward list/splice after")` and the increment operator: incrementing the before-begin iterator gives exactly the same iterator as obtained from `[begin()](begin "cpp/container/forward list/begin")`/`[cbegin()](begin "cpp/container/forward list/begin")`. ### Parameters (none). ### Return value Iterator to the element before the first element. ### Complexity Constant. ### See also | | | | --- | --- | | [begin cbegin](begin "cpp/container/forward list/begin") (C++11) | returns an iterator to the beginning (public member function) | | [end cend](end "cpp/container/forward list/end") (C++11) | returns an iterator to the end (public member function) | cpp std::forward_list<T,Allocator>::empty std::forward\_list<T,Allocator>::empty ====================================== | | | | | --- | --- | --- | | ``` bool empty() const noexcept; ``` | | (since C++11) (until C++20) | | ``` [[nodiscard]] bool empty() const noexcept; ``` | | (since C++20) | Checks if the container has no elements, i.e. whether `begin() == end()`. ### Parameters (none). ### Return value `true` if the container is empty, `false` otherwise. ### Complexity Constant. ### Example The following code uses `empty` to check if a `[std::forward\_list](http://en.cppreference.com/w/cpp/container/forward_list)<int>` contains any elements: ``` #include <forward_list> #include <iostream> int main() { std::forward_list<int> numbers; std::cout << std::boolalpha; std::cout << "Initially, numbers.empty(): " << numbers.empty() << '\n'; numbers.push_front(42); numbers.push_front(13317); std::cout << "After adding elements, numbers.empty(): " << numbers.empty() << '\n'; } ``` Output: ``` Initially, numbers.empty(): true After adding elements, numbers.empty(): false ```
programming_docs
cpp std::forward_list<T,Allocator>::emplace_after std::forward\_list<T,Allocator>::emplace\_after =============================================== | | | | | --- | --- | --- | | ``` template< class... Args > iterator emplace_after( const_iterator pos, Args&&... args ); ``` | | (since C++11) | Inserts a new element into a position after the specified position in the container. The element is constructed in-place, i.e. no copy or move operations are performed. The constructor of the element is called with exactly the same arguments, as supplied to the function. No iterators or references are invalidated. ### Parameters | | | | | --- | --- | --- | | pos | - | iterator after which the new element will be constructed | | args | - | arguments to forward to the constructor of the element | ### Return value iterator to the new element. ### Complexity Constant. ### Exceptions If an exception is thrown (e.g. by the constructor), the container is left unmodified, as if this function was never called (strong exception guarantee). ### Example The example demonstrates a canonical filling of a single-linked list in natural (as opposed to reverse) order. ``` #include <forward_list> #include <iostream> #include <string> struct Sum { std::string remark; int sum; Sum(std::string remark, int sum) : remark{std::move(remark)}, sum{sum} {} void print() const { std::cout << remark << " = " << sum << '\n'; } }; int main() { std::forward_list<Sum> list; auto iter = list.before_begin(); std::string str{"1"}; for (int i{1}, sum{1}; i != 10; sum += i) { iter = list.emplace_after(iter, str, sum); ++i; str += " + " + std::to_string(i); } for (const Sum& s : list) s.print(); } ``` Output: ``` 1 = 1 1 + 2 = 3 1 + 2 + 3 = 6 1 + 2 + 3 + 4 = 10 1 + 2 + 3 + 4 + 5 = 15 1 + 2 + 3 + 4 + 5 + 6 = 21 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 = 36 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 = 45 ``` ### See also | | | | --- | --- | | [insert\_after](insert_after "cpp/container/forward list/insert after") (C++11) | inserts elements after an element (public member function) | cpp std::forward_list<T,Allocator>::begin, std::forward_list<T,Allocator>::cbegin std::forward\_list<T,Allocator>::begin, std::forward\_list<T,Allocator>::cbegin =============================================================================== | | | | | --- | --- | --- | | ``` iterator begin() noexcept; ``` | | (since C++11) | | ``` const_iterator begin() const noexcept; ``` | | (since C++11) | | ``` const_iterator cbegin() const noexcept; ``` | | (since C++11) | Returns an iterator to the first element of the `forward_list`. If the `forward_list` is empty, the returned iterator will be equal to `[end()](end "cpp/container/forward list/end")`. ![range-begin-end.svg]() ### Parameters (none). ### Return value Iterator to the first element. ### Complexity Constant. ### Example ``` #include <algorithm> #include <iostream> #include <numeric> #include <string> #include <forward_list> int main() { std::forward_list<int> nums {1, 2, 4, 8, 16}; std::forward_list<std::string> fruits {"orange", "apple", "raspberry"}; std::forward_list<char> empty; // Print forward_list. std::for_each(nums.begin(), nums.end(), [](const int n) { std::cout << n << ' '; }); std::cout << '\n'; // Sums all integers in the forward_list nums (if any), printing only the result. std::cout << "Sum of nums: " << std::accumulate(nums.begin(), nums.end(), 0) << '\n'; // Prints the first fruit in the forward_list fruits, checking if there is any. if (!fruits.empty()) std::cout << "First fruit: " << *fruits.begin() << '\n'; if (empty.begin() == empty.end()) std::cout << "forward_list 'empty' is indeed empty.\n"; } ``` Output: ``` 1 2 4 8 16 Sum of nums: 31 First fruit: orange forward_list 'empty' is indeed empty. ``` ### See also | | | | --- | --- | | [end cend](end "cpp/container/forward list/end") (C++11) | returns an iterator to the end (public member function) | | [begincbegin](../../iterator/begin "cpp/iterator/begin") (C++11)(C++14) | returns an iterator to the beginning of a container or array (function template) | cpp std::forward_list<T,Allocator>::unique std::forward\_list<T,Allocator>::unique ======================================= | | | | | --- | --- | --- | | | (1) | | | ``` void unique(); ``` | (since C++11) (until C++20) | | ``` size_type unique(); ``` | (since C++20) | | | (2) | | | ``` template< class BinaryPredicate > void unique( BinaryPredicate p ); ``` | (since C++11) (until C++20) | | ``` template< class BinaryPredicate > size_type unique( BinaryPredicate p ); ``` | (since C++20) | Removes all *consecutive* duplicate elements from the container. Only the first element in each group of equal elements is left. The behavior is undefined if the selected comparator does not establish an equivalence relation. 1) Uses `operator==` to compare the elements. 2) Uses the given binary predicate `p` to compare the elements. ### Parameters | | | | | --- | --- | --- | | p | - | binary predicate which returns ​`true` if the elements should be treated as equal. The signature of the predicate function should be equivalent to the following: `bool pred(const Type1 &a, const Type2 &b);` While the signature does not need to have `const &`, the function must not modify the objects passed to it and must be able to accept all values of type (possibly const) `Type1` and `Type2` regardless of [value category](../../language/value_category "cpp/language/value category") (thus, `Type1 &` is not allowed, nor is `Type1` unless for `Type1` a move is equivalent to a copy (since C++11)). The types `Type1` and `Type2` must be such that an object of type `forward_list<T,Allocator>::const_iterator` can be dereferenced and then implicitly converted to both of them. ​ | ### Return value | | | | --- | --- | | (none). | (until C++20) | | The number of elements removed. | (since C++20) | ### Complexity Exactly `[std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(begin(), end()) - 1` comparisons of the elements, if the container is not empty. Otherwise, no comparison is performed. ### Notes | [Feature-test](../../utility/feature_test "cpp/utility/feature test") macro | | --- | | [`__cpp_lib_list_remove_return_type`](../../feature_test#Library_features "cpp/feature test") | ### Example ``` #include <iostream> #include <forward_list> auto print = [](auto remark, auto const& container) { std::cout << remark; for (auto const& val : container) std::cout << ' ' << val; std::cout << '\n'; }; int main() { std::forward_list<int> c = {1, 2, 2, 3, 3, 2, 1, 1, 2}; print("Before unique():", c); const auto count1 = c.unique(); print("After unique(): ", c); std::cout << count1 << " elements were removed\n"; c = {1, 2, 12, 23, 3, 2, 51, 1, 2, 2}; print("Before unique(pred):", c); const auto count2 = c.unique([mod=10](int x, int y) { return (x % mod) == (y % mod); }); print("After unique(pred): ", c); std::cout << count2 << " elements were removed\n"; } ``` Output: ``` Before unique(): 1 2 2 3 3 2 1 1 2 After unique(): 1 2 3 2 1 2 3 elements were removed Before unique(pred): 1 2 12 23 3 2 51 1 2 2 After unique(pred): 1 2 23 2 51 2 4 elements were removed ``` ### See also | | | | --- | --- | | [unique](../../algorithm/unique "cpp/algorithm/unique") | removes consecutive duplicate elements in a range (function template) | cpp std::forward_list<T,Allocator>::end, std::forward_list<T,Allocator>::cend std::forward\_list<T,Allocator>::end, std::forward\_list<T,Allocator>::cend =========================================================================== | | | | | --- | --- | --- | | ``` iterator end() noexcept; ``` | | (since C++11) | | ``` const_iterator end() const noexcept; ``` | | (since C++11) | | ``` const_iterator cend() const noexcept; ``` | | (since C++11) | Returns an iterator to the element following the last element of the `forward_list`. This element acts as a placeholder; attempting to access it results in undefined behavior. ![range-begin-end.svg]() ### Parameters (none). ### Return value Iterator to the element following the last element. ### Complexity Constant. ### Example ``` #include <algorithm> #include <iostream> #include <numeric> #include <string> #include <forward_list> int main() { std::forward_list<int> nums {1, 2, 4, 8, 16}; std::forward_list<std::string> fruits {"orange", "apple", "raspberry"}; std::forward_list<char> empty; // Print forward_list. std::for_each(nums.begin(), nums.end(), [](const int n) { std::cout << n << ' '; }); std::cout << '\n'; // Sums all integers in the forward_list nums (if any), printing only the result. std::cout << "Sum of nums: " << std::accumulate(nums.begin(), nums.end(), 0) << '\n'; // Prints the first fruit in the forward_list fruits, checking if there is any. if (!fruits.empty()) std::cout << "First fruit: " << *fruits.begin() << '\n'; if (empty.begin() == empty.end()) std::cout << "forward_list 'empty' is indeed empty.\n"; } ``` Output: ``` 1 2 4 8 16 Sum of nums: 31 First fruit: orange forward_list 'empty' is indeed empty. ``` ### See also | | | | --- | --- | | [begin cbegin](begin "cpp/container/forward list/begin") (C++11) | returns an iterator to the beginning (public member function) | | [endcend](../../iterator/end "cpp/iterator/end") (C++11)(C++14) | returns an iterator to the end of a container or array (function template) | cpp std::unordered_map<Key,T,Hash,KeyEqual,Allocator>::contains std::unordered\_map<Key,T,Hash,KeyEqual,Allocator>::contains ============================================================ | | | | | --- | --- | --- | | ``` bool contains( const Key& key ) const; ``` | (1) | (since C++20) | | ``` template< class K > bool contains( const K& x ) const; ``` | (2) | (since C++20) | 1) Checks if there is an element with key equivalent to `key` in the container. 2) Checks if there is an element with key that compares *equivalent* to the value `x`. This overload participates in overload resolution only if `Hash::is_transparent` and `KeyEqual::is_transparent` are valid and each denotes a type. This assumes that such `Hash` is callable with both `K` and `Key` type, and that the `KeyEqual` is transparent, which, together, allows calling this function without constructing an instance of `Key`. ### Parameters | | | | | --- | --- | --- | | key | - | key value of the element to search for | | x | - | a value of any type that can be transparently compared with a key | ### Return value `true` if there is such an element, otherwise `false`. ### Complexity Constant on average, worst case linear in the size of the container. ### Example ``` #include <iostream> #include <unordered_map> int main() { std::unordered_map<int,char> example = {{1,'a'},{2,'b'}}; for(int x: {2, 5}) { if(example.contains(x)) { std::cout << x << ": Found\n"; } else { std::cout << x << ": Not found\n"; } } } ``` Output: ``` 2: Found 5: Not found ``` ### See also | | | | --- | --- | | [find](find "cpp/container/unordered map/find") (C++11) | finds element with specific key (public member function) | | [count](count "cpp/container/unordered map/count") (C++11) | returns the number of elements matching specific key (public member function) | | [equal\_range](equal_range "cpp/container/unordered map/equal range") (C++11) | returns range of elements matching a specific key (public member function) | cpp std::unordered_map<Key,T,Hash,KeyEqual,Allocator>::size std::unordered\_map<Key,T,Hash,KeyEqual,Allocator>::size ======================================================== | | | | | --- | --- | --- | | ``` size_type size() const noexcept; ``` | | (since C++11) | Returns the number of elements in the container, i.e. `[std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(begin(), end())`. ### Parameters (none). ### Return value The number of elements in the container. ### Complexity Constant. ### Example The following code uses `size` to display the number of elements in a `[std::unordered\_map](../unordered_map "cpp/container/unordered map")`: ``` #include <unordered_map> #include <iostream> int main() { std::unordered_map<int,char> nums {{1, 'a'}, {3, 'b'}, {5, 'c'}, {7, 'd'}}; std::cout << "nums contains " << nums.size() << " elements.\n"; } ``` Output: ``` nums contains 4 elements. ``` ### See also | | | | --- | --- | | [empty](empty "cpp/container/unordered map/empty") (C++11) | checks whether the container is empty (public member function) | | [max\_size](max_size "cpp/container/unordered map/max size") (C++11) | returns the maximum possible number of elements (public member function) | | [sizessize](../../iterator/size "cpp/iterator/size") (C++17)(C++20) | returns the size of a container or array (function template) | cpp std::unordered_map<Key,T,Hash,KeyEqual,Allocator>::bucket_count std::unordered\_map<Key,T,Hash,KeyEqual,Allocator>::bucket\_count ================================================================= | | | | | --- | --- | --- | | ``` size_type bucket_count() const; ``` | | (since C++11) | Returns the number of buckets in the container. ### Parameters (none). ### Return value The number of buckets in the container. ### Complexity Constant. ### See also | | | | --- | --- | | [bucket\_size](bucket_size "cpp/container/unordered map/bucket size") (C++11) | returns the number of elements in specific bucket (public member function) | | [max\_bucket\_count](max_bucket_count "cpp/container/unordered map/max bucket count") (C++11) | returns the maximum number of buckets (public member function) | cpp deduction guides for std::unordered_map deduction guides for `std::unordered_map` ========================================= | Defined in header `[<unordered\_map>](../../header/unordered_map "cpp/header/unordered map")` | | | | --- | --- | --- | | ``` template<class InputIt, class Hash = std::hash<iter_key_t<InputIt>>, class Pred = std::equal_to<iter_key_t<InputIt>>, class Alloc = std::allocator<iter_to_alloc_t<InputIt>>> unordered_map(InputIt, InputIt, typename /*see below*/::size_type = /*see below*/, Hash = Hash(), Pred = Pred(), Alloc = Alloc()) -> unordered_map<iter_key_t<InputIt>, iter_val_t<InputIt>, Hash, Pred, Alloc>; ``` | (1) | (since C++17) | | ``` template<class Key, class T, class Hash = std::hash<Key>, class Pred = std::equal_to<Key>, class Alloc = std::allocator<std::pair<const Key, T>>> unordered_map(std::initializer_list<std::pair<Key, T>>, typename /*see below*/::size_type = /*see below*/, Hash = Hash(), Pred = Pred(), Alloc = Alloc()) -> unordered_map<Key, T, Hash, Pred, Alloc>; ``` | (2) | (since C++17) | | ``` template<class InputIt, class Alloc> unordered_map(InputIt, InputIt, typename /*see below*/::size_type, Alloc) -> unordered_map<iter_key_t<InputIt>, iter_val_t<InputIt>, std::hash<iter_key_t<InputIt>>, std::equal_to<iter_key_t<InputIt>>, Alloc>; ``` | (3) | (since C++17) | | ``` template<class InputIt, class Alloc> unordered_map(InputIt, InputIt, Alloc) -> unordered_map<iter_key_t<InputIt>, iter_val_t<InputIt>, std::hash<iter_key_t<InputIt>>, std::equal_to<iter_key_t<InputIt>>, Alloc>; ``` | (4) | (since C++17) | | ``` template<class InputIt, class Hash, class Alloc> unordered_map(InputIt, InputIt, typename /*see below*/::size_type, Hash, Alloc) -> unordered_map<iter_key_t<InputIt>, iter_val_t<InputIt>, Hash, std::equal_to<iter_key_t<InputIt>>, Alloc>; ``` | (5) | (since C++17) | | ``` template<class Key, class T, typename Alloc> unordered_map(std::initializer_list<std::pair<Key, T>>, typename /*see below*/::size_type, Alloc) -> unordered_map<Key, T, std::hash<Key>, std::equal_to<Key>, Alloc>; ``` | (6) | (since C++17) | | ``` template<class Key, class T, typename Alloc> unordered_map(std::initializer_list<std::pair<Key, T>>, Alloc) -> unordered_map<Key, T, std::hash<Key>, std::equal_to<Key>, Alloc>; ``` | (7) | (since C++17) | | ``` template<class Key, class T, class Hash, class Alloc> unordered_map(std::initializer_list<std::pair<Key, T>>, typename /*see below*/::size_type, Hash, Alloc) -> unordered_map<Key, T, Hash, std::equal_to<Key>, Alloc>; ``` | (8) | (since C++17) | where the type aliases `iter_key_t`, `iter_val_t`, `iter_to_alloc_t` are defined as if as follows. | | | | | --- | --- | --- | | ``` template< class InputIt > using iter_key_t = std::remove_const_t< typename std::iterator_traits<InputIt>::value_type::first_type>; ``` | | (exposition only) | | ``` template< class InputIt > using iter_val_t = typename std::iterator_traits<InputIt>::value_type::second_type; ``` | | (exposition only) | | ``` template< class InputIt > using iter_to_alloc_t = std::pair< std::add_const_t<typename std::iterator_traits<InputIt>::value_type::first_type>, typename std::iterator_traits<InputIt>::value_type::second_type > ``` | | (exposition only) | These [deduction guide](../../language/class_template_argument_deduction "cpp/language/class template argument deduction") are provided for unordered\_map to allow deduction from an iterator range (overloads (1,3-5)) and `[std::initializer\_list](../../utility/initializer_list "cpp/utility/initializer list")` (overloads (2,6-8)). These overloads participate in overload resolution only if `InputIt` satisfies [LegacyInputIterator](../../named_req/inputiterator "cpp/named req/InputIterator"), `Alloc` satisfies [Allocator](../../named_req/allocator "cpp/named req/Allocator"), neither `Hash` nor `Pred` satisfy [Allocator](../../named_req/allocator "cpp/named req/Allocator"), and `Hash` is not an integral type. Note: the extent to which the library determines that a type does not satisfy [LegacyInputIterator](../../named_req/inputiterator "cpp/named req/InputIterator") is unspecified, except that as a minimum integral types do not qualify as input iterators. Likewise, the extent to which it determines that a type does not satisfy [Allocator](../../named_req/allocator "cpp/named req/Allocator") is unspecified, except that as a minimum the member type `Alloc::value_type` must exist and the expression `[std::declval](http://en.cppreference.com/w/cpp/utility/declval)<Alloc&>().allocate([std::size\_t](http://en.cppreference.com/w/cpp/types/size_t){})` must be well-formed when treated as an unevaluated operand. The `size_type` parameter type in these guides in an refers to the `size_type` member type of the type deduced by the deduction guide. ### Example ``` #include <unordered_map> int main() { // std::unordered_map m1 = {{"foo", 1}, {"bar", 2}}; // Error: braced-init-list has no type // cannot deduce pair<Key, T> from // {"foo", 1} or {"bar", 2} std::unordered_map m1 = {std::pair{"foo", 2}, {"bar", 3}}; // guide #2 std::unordered_map m2(m1.begin(), m1.end()); // guide #1 } ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 3025](https://cplusplus.github.io/LWG/issue3025) | C++17 | initializer-list guides take `[std::pair](http://en.cppreference.com/w/cpp/utility/pair)<const Key, T>` | use `[std::pair](http://en.cppreference.com/w/cpp/utility/pair)<Key, T>` |
programming_docs
cpp std::unordered_map<Key,T,Hash,KeyEqual,Allocator>::insert_or_assign std::unordered\_map<Key,T,Hash,KeyEqual,Allocator>::insert\_or\_assign ====================================================================== | | | | | --- | --- | --- | | ``` template <class M> std::pair<iterator, bool> insert_or_assign( const Key& k, M&& obj ); ``` | (1) | (since C++17) | | ``` template <class M> std::pair<iterator, bool> insert_or_assign( Key&& k, M&& obj ); ``` | (2) | (since C++17) | | ``` template <class M> iterator insert_or_assign( const_iterator hint, const Key& k, M&& obj ); ``` | (3) | (since C++17) | | ``` template <class M> iterator insert_or_assign( const_iterator hint, Key&& k, M&& obj ); ``` | (4) | (since C++17) | 1,3) If a key equivalent to `k` already exists in the container, assigns `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<M>(obj)` to the `mapped_type` corresponding to the key `k`. If the key does not exist, inserts the new value as if by [`insert`](insert "cpp/container/unordered map/insert"), constructing it from `value_type(k, [std::forward](http://en.cppreference.com/w/cpp/utility/forward)<M>(obj))` 2,4) Same as (1,3), except the mapped value is constructed from `value_type(std::move(k), [std::forward](http://en.cppreference.com/w/cpp/utility/forward)<M>(obj))` The behavior is undefined (until C++20)The program is ill-formed (since C++20) if `[std::is\_assignable\_v](http://en.cppreference.com/w/cpp/types/is_assignable)<mapped_type&, M&&>` is `false`. If an insertion occurs and results in a rehashing of the container, all iterators are invalidated. Otherwise iterators are not affected. References are not invalidated. Rehashing occurs only if the new number of elements is greater than `max_load_factor()*bucket_count()`. ### Parameters | | | | | --- | --- | --- | | k | - | the key used both to look up and to insert if not found | | hint | - | iterator to the position before which the new element will be inserted | | obj | - | the value to insert or assign | ### Return value 1,2) The bool component is `true` if the insertion took place and `false` if the assignment took place. The iterator component is pointing at the element that was inserted or updated 3,4) Iterator pointing at the element that was inserted or updated ### Complexity 1,2) Same as for [`emplace`](emplace "cpp/container/unordered map/emplace") 3,4) Same as for [`emplace_hint`](emplace_hint "cpp/container/unordered map/emplace hint") ### Notes `insert_or_assign` returns more information than `operator[]` and does not require default-constructibility of the mapped type. | [Feature-test](../../utility/feature_test "cpp/utility/feature test") macro | | --- | | [`__cpp_lib_unordered_map_try_emplace`](../../feature_test#Library_features "cpp/feature test") | ### Example ``` #include <iostream> #include <unordered_map> #include <string> auto print_node = [](const auto &node) { std::cout << "[" << node.first << "] = " << node.second << '\n'; }; auto print_result = [](auto const &pair) { std::cout << (pair.second ? "inserted: " : "assigned: "); print_node(*pair.first); }; int main() { std::unordered_map<std::string, std::string> myMap; print_result( myMap.insert_or_assign("a", "apple" ) ); print_result( myMap.insert_or_assign("b", "banana" ) ); print_result( myMap.insert_or_assign("c", "cherry" ) ); print_result( myMap.insert_or_assign("c", "clementine") ); for (const auto &node : myMap) { print_node(node); } } ``` Possible output: ``` inserted: [a] = apple inserted: [b] = banana inserted: [c] = cherry assigned: [c] = clementine [c] = clementine [a] = apple [b] = banana ``` ### See also | | | | --- | --- | | [operator[]](operator_at "cpp/container/unordered map/operator at") (C++11) | access or insert specified element (public member function) | | [at](at "cpp/container/unordered map/at") (C++11) | access specified element with bounds checking (public member function) | | [insert](insert "cpp/container/unordered map/insert") (C++11) | inserts elements or nodes (since C++17) (public member function) | | [emplace](emplace "cpp/container/unordered map/emplace") (C++11) | constructs element in-place (public member function) | cpp std::unordered_map<Key,T,Hash,KeyEqual,Allocator>::emplace std::unordered\_map<Key,T,Hash,KeyEqual,Allocator>::emplace =========================================================== | | | | | --- | --- | --- | | ``` template< class... Args > std::pair<iterator,bool> emplace( Args&&... args ); ``` | | (since C++11) | Inserts a new element into the container constructed in-place with the given `args` if there is no element with the key in the container. Careful use of `emplace` allows the new element to be constructed while avoiding unnecessary copy or move operations. The constructor of the new element (i.e. `[std::pair](http://en.cppreference.com/w/cpp/utility/pair)<const Key, T>`) is called with exactly the same arguments as supplied to `emplace`, forwarded via `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Args>(args)...`. The element may be constructed even if there already is an element with the key in the container, in which case the newly constructed element will be destroyed immediately. If rehashing occurs due to the insertion, all iterators are invalidated. Otherwise iterators are not affected. References are not invalidated. Rehashing occurs only if the new number of elements is greater than `max_load_factor()*bucket_count()`. ### Parameters | | | | | --- | --- | --- | | args | - | arguments to forward to the constructor of the element | ### Return value Returns a pair consisting of an iterator to the inserted element, or the already-existing element if no insertion happened, and a `bool` denoting whether the insertion took place (`true` if insertion happened, `false` if it did not). ### Exceptions If an exception is thrown by any operation, this function has no effect (strong exception guarantee). ### Complexity Amortized constant on average, worst case linear in the size of the container. ### Example ``` #include <iostream> #include <utility> #include <string> #include <unordered_map> int main() { std::unordered_map<std::string, std::string> m; // uses pair's move constructor m.emplace(std::make_pair(std::string("a"), std::string("a"))); // uses pair's converting move constructor m.emplace(std::make_pair("b", "abcd")); // uses pair's template constructor m.emplace("d", "ddd"); // uses pair's piecewise constructor m.emplace(std::piecewise_construct, std::forward_as_tuple("c"), std::forward_as_tuple(10, 'c')); // as of C++17, m.try_emplace("c", 10, 'c'); can be used for (const auto &p : m) { std::cout << p.first << " => " << p.second << '\n'; } } ``` Possible output: ``` a => a b => abcd c => cccccccccc d => ddd ``` ### See also | | | | --- | --- | | [emplace\_hint](emplace_hint "cpp/container/unordered map/emplace hint") (C++11) | constructs elements in-place using a hint (public member function) | | [try\_emplace](try_emplace "cpp/container/unordered map/try emplace") (C++17) | inserts in-place if the key does not exist, does nothing if the key exists (public member function) | | [insert](insert "cpp/container/unordered map/insert") (C++11) | inserts elements or nodes (since C++17) (public member function) | cpp std::unordered_map<Key,T,Hash,KeyEqual,Allocator>::insert std::unordered\_map<Key,T,Hash,KeyEqual,Allocator>::insert ========================================================== | | | | | --- | --- | --- | | ``` std::pair<iterator,bool> insert( const value_type& value ); ``` | (1) | (since C++11) | | ``` std::pair<iterator,bool> insert( value_type&& value ); ``` | (1) | (since C++17) | | ``` template< class P > std::pair<iterator,bool> insert( P&& value ); ``` | (2) | (since C++11) | | ``` iterator insert( const_iterator hint, const value_type& value ); ``` | (3) | (since C++11) | | ``` iterator insert( const_iterator hint, value_type&& value ); ``` | (3) | (since C++17) | | ``` template< class P > iterator insert( const_iterator hint, P&& value ); ``` | (4) | (since C++11) | | ``` template< class InputIt > void insert( InputIt first, InputIt last ); ``` | (5) | (since C++11) | | ``` void insert( std::initializer_list<value_type> ilist ); ``` | (6) | (since C++11) | | ``` insert_return_type insert( node_type&& nh ); ``` | (7) | (since C++17) | | ``` iterator insert( const_iterator hint, node_type&& nh ); ``` | (8) | (since C++17) | Inserts element(s) into the container, if the container doesn't already contain an element with an equivalent key. 1-2) Inserts `value`. The overload (2) is equivalent to `emplace([std::forward](http://en.cppreference.com/w/cpp/utility/forward)<P>(value))` and only participates in overload resolution if `[std::is\_constructible](http://en.cppreference.com/w/cpp/types/is_constructible)<value_type, P&&>::value == true`. 3-4) Inserts `value`, using `hint` as a non-binding suggestion to where the search should start. The overload (4) is equivalent to `emplace_hint(hint, [std::forward](http://en.cppreference.com/w/cpp/utility/forward)<P>(value))` and only participates in overload resolution if `[std::is\_constructible](http://en.cppreference.com/w/cpp/types/is_constructible)<value_type, P&&>::value == true`. 5) Inserts elements from range `[first, last)`. If multiple elements in the range have keys that compare equivalent, it is unspecified which element is inserted (pending [LWG2844](https://cplusplus.github.io/LWG/issue2844)). 6) Inserts elements from initializer list `ilist`. If multiple elements in the range have keys that compare equivalent, it is unspecified which element is inserted (pending [LWG2844](https://cplusplus.github.io/LWG/issue2844)). 7) If `nh` is an empty [node handle](../node_handle "cpp/container/node handle"), does nothing. Otherwise, inserts the element owned by `nh` into the container , if the container doesn't already contain an element with a key equivalent to `nh.key()`. The behavior is undefined if `nh` is not empty and `get_allocator() != nh.get_allocator()`. 8) If `nh` is an empty [node handle](../node_handle "cpp/container/node handle"), does nothing and returns the end iterator. Otherwise, inserts the element owned by `nh` into the container, if the container doesn't already contain an element with a key equivalent to `nh.key()`, and returns the iterator pointing to the element with key equivalent to `nh.key()` (regardless of whether the insert succeeded or failed). If the insertion succeeds, `nh` is moved from, otherwise it retains ownership of the element. The element is inserted as close as possible to `hint`. The behavior is undefined if `nh` is not empty and `get_allocator() != nh.get_allocator()`. If rehashing occurs due to the insertion, all iterators are invalidated. Otherwise iterators are not affected. References are not invalidated. Rehashing occurs only if the new number of elements is greater than `max_load_factor()*bucket_count()`. If the insertion is successful, pointers and references to the element obtained while it is held in the node handle are invalidated, and pointers and references obtained to that element before it was extracted become valid. (since C++17). ### Parameters | | | | | --- | --- | --- | | hint | - | iterator, used as a suggestion as to where to insert the content | | value | - | element value to insert | | first, last | - | range of elements to insert | | ilist | - | initializer list to insert the values from | | nh | - | a compatible [node handle](../node_handle "cpp/container/node handle") | | Type requirements | | -`InputIt` must meet the requirements of [LegacyInputIterator](../../named_req/inputiterator "cpp/named req/InputIterator"). | ### Return value 1-2) Returns a pair consisting of an iterator to the inserted element (or to the element that prevented the insertion) and a `bool` denoting whether the insertion took place (`true` if insertion happened, `false` if it did not). 3-4) Returns an iterator to the inserted element, or to the element that prevented the insertion. 5-6) (none) 7) Returns an [`insert_return_type`](../unordered_map#Member_types "cpp/container/unordered map") with the members initialized as follows: * 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()`. 8) End iterator if `nh` was empty, iterator pointing to the inserted element if insertion took place, and iterator pointing to an element with a key equivalent to `nh.key()` if it failed. ### Exceptions 1-4) If an exception is thrown by any operation, the insertion has no effect. ### Complexity 1-4) Average case: `O(1)`, worst case `O(size())` 5-6) Average case: `O(N)`, where N is the number of elements to insert. Worst case: `O(N*size()+N)` 7-8) Average case: `O(1)`, worst case `O(size())` ### Notes The hinted insert (3,4) does not return a boolean in order to be signature-compatible with positional insert on sequential containers, such as `[std::vector::insert](../vector/insert "cpp/container/vector/insert")`. This makes it possible to create generic inserters such as `[std::inserter](../../iterator/inserter "cpp/iterator/inserter")`. One way to check success of a hinted insert is to compare [`size()`](size "cpp/container/unordered map/size") before and after. ### Example ``` #include <string> #include <iostream> #include <unordered_map> int main () { std::unordered_map<int, std::string> dict = {{1, "one"}, {2, "two"}}; dict.insert({3, "three"}); dict.insert(std::make_pair(4, "four")); dict.insert({{4, "another four"}, {5, "five"}}); bool ok = dict.insert({1, "another one"}).second; std::cout << "inserting 1 -> \"another one\" " << (ok ? "succeeded" : "failed") << '\n'; std::cout << "contents:\n"; for(auto& p: dict) std::cout << " " << p.first << " => " << p.second << '\n'; } ``` Possible output: ``` inserting 1 -> "another one" failed contents: 5 => five 1 => one 2 => two 3 => three 4 => four ``` ### See also | | | | --- | --- | | [emplace](emplace "cpp/container/unordered map/emplace") (C++11) | constructs element in-place (public member function) | | [emplace\_hint](emplace_hint "cpp/container/unordered map/emplace hint") (C++11) | constructs elements in-place using a hint (public member function) | | [insert\_or\_assign](insert_or_assign "cpp/container/unordered map/insert or assign") (C++17) | inserts an element or assigns to the current element if the key already exists (public member function) | | [inserter](../../iterator/inserter "cpp/iterator/inserter") | creates a `[std::insert\_iterator](../../iterator/insert_iterator "cpp/iterator/insert iterator")` of type inferred from the argument (function template) | cpp std::unordered_map<Key,T,Hash,KeyEqual,Allocator>::get_allocator std::unordered\_map<Key,T,Hash,KeyEqual,Allocator>::get\_allocator ================================================================== | | | | | --- | --- | --- | | ``` allocator_type get_allocator() const noexcept; ``` | | (since C++11) | Returns the allocator associated with the container. ### Parameters (none). ### Return value The associated allocator. ### Complexity Constant. cpp std::unordered_map<Key,T,Hash,KeyEqual,Allocator>::merge std::unordered\_map<Key,T,Hash,KeyEqual,Allocator>::merge ========================================================= | | | | | --- | --- | --- | | ``` template<class H2, class P2> void merge( std::unordered_map<Key, T, H2, P2, Allocator>& source ); ``` | (1) | (since C++17) | | ``` template<class H2, class P2> void merge( std::unordered_map<Key, T, H2, P2, Allocator>&& source ); ``` | (2) | (since C++17) | | ``` template<class H2, class P2> void merge( std::unordered_multimap<Key, T, H2, P2, Allocator>& source ); ``` | (3) | (since C++17) | | ``` template<class H2, class P2> void merge( std::unordered_multimap<Key, T, H2, P2, Allocator>&& source ); ``` | (4) | (since C++17) | Attempts to extract ("splice") each element in `source` and insert it into `*this` using the hash function and key equality predicate of `*this`. If there is an element in `*this` with key equivalent to the key of an element from `source`, then that element is not extracted from `source`. No elements are copied or moved, only the internal pointers of the container nodes are repointed. All pointers and references to the transferred elements remain valid, but now refer into `*this`, not into `source`. Iterators referring to the transferred elements and all iterators referring to `*this` are invalidated. Iterators to elements remaining in `source` remain valid. The behavior is undefined if `get_allocator() != source.get_allocator()`. ### Parameters | | | | | --- | --- | --- | | source | - | compatible container to transfer the nodes from | ### Return value (none). ### Complexity Average case O(N), worst case O(N\*size()+N), where N is `source.size()`. ### Example ``` #include <iostream> #include <string> #include <utility> #include <unordered_map> // print out a std::pair template <class Os, class U, class V> Os& operator<<(Os& os, const std::pair<U,V>& p) { return os << '{' << p.first << ", " << p.second << '}'; } // print out an associative container template <class Os, class K, class V> Os& operator<<(Os& os, const std::unordered_map<K, V>& v) { os << '[' << v.size() << "] { "; bool o{}; for (const auto& e : v) os << (o ? ", " : (o = 1, "")) << e; return os << " }\n"; } int main() { std::unordered_map<std::string, int> p{ {"C", 3}, {"B", 2}, {"A", 1}, {"A", 0} }, q{ {"E", 6}, {"E", 7}, {"D", 5}, {"A", 4} }; std::cout << "p: " << p << "q: " << q; p.merge(q); std::cout << "p.merge(q);\n" << "p: " << p << "q: " << q; } ``` Possible output: ``` p: [3] { {A, 1}, {B, 2}, {C, 3} } q: [3] { {A, 4}, {D, 5}, {E, 6} } p.merge(q); p: [5] { {E, 6}, {D, 5}, {A, 1}, {B, 2}, {C, 3} } q: [1] { {A, 4} } ``` ### See also | | | | --- | --- | | [extract](extract "cpp/container/unordered map/extract") (C++17) | extracts nodes from the container (public member function) | | [insert](insert "cpp/container/unordered map/insert") (C++11) | inserts elements or nodes (since C++17) (public member function) | cpp std::unordered_map<Key,T,Hash,KeyEqual,Allocator>::extract std::unordered\_map<Key,T,Hash,KeyEqual,Allocator>::extract =========================================================== | | | | | --- | --- | --- | | ``` node_type extract( const_iterator position ); ``` | (1) | (since C++17) | | ``` node_type extract( const Key& k ); ``` | (2) | (since C++17) | | ``` template< class K > node_type extract( K&& x ); ``` | (3) | (since C++23) | 1) Unlinks the node that contains the element pointed to by `position` and returns a [node handle](../node_handle "cpp/container/node handle") that owns it. 2) If the container has an element with key equivalent to `k`, unlinks the node that contains that element from the container and returns a [node handle](../node_handle "cpp/container/node handle") that owns it. Otherwise, returns an empty node handle. 3) Same as (2). This overload participates in overload resolution only if `Hash::is_transparent` and `KeyEqual::is_transparent` are valid and each denotes a type, and neither `iterator` nor `const_iterator` is implicitly convertible from `K`. This assumes that such `Hash` is callable with both `K` and `Key` type, and that the `KeyEqual` is transparent, which, together, allows calling this function without constructing an instance of `Key`. In either case, no elements are copied or moved, only the internal pointers of the container nodes are repointed . Extracting a node invalidates only the iterators to the extracted element, and preserves the relative order of the elements that are not erased. Pointers and references to the extracted element remain valid, but cannot be used while element is owned by a node handle: they become usable if the element is inserted into a container. ### Parameters | | | | | --- | --- | --- | | position | - | a valid iterator into this container | | k | - | a key to identify the node to be extracted | | x | - | a value of any type that can be transparently compared with a key identifying the node to be extracted | ### Return value A [node handle](../node_handle "cpp/container/node handle") that owns the extracted element, or empty node handle in case the element is not found in (2,3). ### Exceptions 1) Throws nothing. 2,3) Any exceptions thrown by the `Hash` and `KeyEqual` object. ### Complexity 1,2,3) Average case O(1), worst case O(`a.size()`). ### Notes extract is the only way to change a key of a map element without reallocation: ``` std::map<int, std::string> m{{1, "mango"}, {2, "papaya"}, {3, "guava"}}; auto nh = m.extract(2); nh.key() = 4; m.insert(std::move(nh)); // m == {{1, "mango"}, {3, "guava"}, {4, "papaya"}} ``` | [Feature-test](../../utility/feature_test "cpp/utility/feature test") macro | Comment | | --- | --- | | [`__cpp_lib_associative_heterogeneous_erasure`](../../feature_test#Library_features "cpp/feature test") | for overload (3) | ### Example ``` #include <algorithm> #include <iostream> #include <string_view> #include <unordered_map> void print(std::string_view comment, const auto& data) { std::cout << comment; for (auto [k, v] : data) std::cout << ' ' << k << '(' << v << ')'; std::cout << '\n'; } int main() { std::unordered_map<int, char> cont{{1, 'a'}, {2, 'b'}, {3, 'c'}}; print("Start:", cont); // Extract node handle and change key auto nh = cont.extract(1); nh.key() = 4; print("After extract and before insert:", cont); // Insert node handle back cont.insert(std::move(nh)); print("End:", cont); } ``` Possible output: ``` Start: 1(a) 2(b) 3(c) After extract and before insert: 2(b) 3(c) End: 2(b) 3(c) 4(a) ``` ### See also | | | | --- | --- | | [merge](merge "cpp/container/unordered map/merge") (C++17) | splices nodes from another container (public member function) | | [insert](insert "cpp/container/unordered map/insert") (C++11) | inserts elements or nodes (since C++17) (public member function) | | [erase](erase "cpp/container/unordered map/erase") (C++11) | erases elements (public member function) |
programming_docs
cpp std::unordered_map<Key,T,Hash,KeyEqual,Allocator>::max_load_factor std::unordered\_map<Key,T,Hash,KeyEqual,Allocator>::max\_load\_factor ===================================================================== | | | | | --- | --- | --- | | ``` float max_load_factor() const; ``` | (1) | (since C++11) | | ``` void max_load_factor( float ml ); ``` | (2) | (since C++11) | Manages the maximum load factor (number of elements per bucket). The container automatically increases the number of buckets if the load factor exceeds this threshold. 1) Returns current maximum load factor. 2) Sets the maximum load factor to `ml`. ### Parameters | | | | | --- | --- | --- | | ml | - | new maximum load factor setting | ### Return value 1) current maximum load factor. 2) none. ### Complexity Constant. ### See also | | | | --- | --- | | [load\_factor](load_factor "cpp/container/unordered map/load factor") (C++11) | returns average number of elements per bucket (public member function) | cpp std::unordered_map<Key,T,Hash,KeyEqual,Allocator>::emplace_hint std::unordered\_map<Key,T,Hash,KeyEqual,Allocator>::emplace\_hint ================================================================= | | | | | --- | --- | --- | | ``` template <class... Args> iterator emplace_hint( const_iterator hint, Args&&... args ); ``` | | (since C++11) | Inserts a new element to the container, using `hint` as a suggestion where the element should go. The element is constructed in-place, i.e. no copy or move operations are performed. The constructor of the element type (`value_type`, that is, `[std::pair](http://en.cppreference.com/w/cpp/utility/pair)<const Key, T>`) is called with exactly the same arguments as supplied to the function, forwarded with `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Args>(args)...`. If rehashing occurs due to the insertion, all iterators are invalidated. Otherwise iterators are not affected. References are not invalidated. Rehashing occurs only if the new number of elements is greater than `max_load_factor()*bucket_count()`. ### Parameters | | | | | --- | --- | --- | | hint | - | iterator, used as a suggestion as to where to insert the new element | | args | - | arguments to forward to the constructor of the element | ### Return value Returns an iterator to the newly inserted element. If the insertion failed because the element already exists, returns an iterator to the already existing element with the equivalent key. ### Exceptions If an exception is thrown by any operation, this function has no effect (strong exception guarantee). ### Complexity Amortized constant on average, worst case linear in the size of the container. ### See also | | | | --- | --- | | [emplace](emplace "cpp/container/unordered map/emplace") (C++11) | constructs element in-place (public member function) | | [insert](insert "cpp/container/unordered map/insert") (C++11) | inserts elements or nodes (since C++17) (public member function) | cpp std::unordered_map<Key,T,Hash,KeyEqual,Allocator>::hash_function std::unordered\_map<Key,T,Hash,KeyEqual,Allocator>::hash\_function ================================================================== | | | | | --- | --- | --- | | ``` hasher hash_function() const; ``` | | (since C++11) | Returns the function that hashes the keys. ### Parameters (none). ### Return value The hash function. ### Complexity Constant. ### See also | | | | --- | --- | | [key\_eq](key_eq "cpp/container/unordered map/key eq") (C++11) | returns the function used to compare keys for equality (public member function) | cpp std::unordered_map<Key,T,Hash,KeyEqual,Allocator>::at std::unordered\_map<Key,T,Hash,KeyEqual,Allocator>::at ====================================================== | | | | | --- | --- | --- | | ``` T& at( const Key& key ); ``` | (1) | (since C++11) | | ``` const T& at( const Key& key ) const; ``` | (2) | (since C++11) | Returns a reference to the mapped value of the element with key equivalent to `key`. If no such element exists, an exception of type `[std::out\_of\_range](../../error/out_of_range "cpp/error/out of range")` is thrown. ### Parameters | | | | | --- | --- | --- | | key | - | the key of the element to find | ### Return value Reference to the mapped value of the requested element. ### Exceptions `[std::out\_of\_range](../../error/out_of_range "cpp/error/out of range")` if the container does not have an element with the specified `key`. ### Complexity Average case: constant, worst case: linear in size. ### See also | | | | --- | --- | | [operator[]](operator_at "cpp/container/unordered map/operator at") (C++11) | access or insert specified element (public member function) | cpp std::unordered_map<Key,T,Hash,KeyEqual,Allocator>::~unordered_map std::unordered\_map<Key,T,Hash,KeyEqual,Allocator>::~unordered\_map =================================================================== | | | | | --- | --- | --- | | ``` ~unordered_map(); ``` | | (since C++11) | Destructs the `unordered_map`. The destructors of the elements are called and the used storage is deallocated. Note, that if the elements are pointers, the pointed-to objects are not destroyed. ### Complexity Linear in the size of the `unordered_map`. cpp std::unordered_map<Key,T,Hash,KeyEqual,Allocator>::operator[] std::unordered\_map<Key,T,Hash,KeyEqual,Allocator>::operator[] ============================================================== | | | | | --- | --- | --- | | ``` T& operator[]( const Key& key ); ``` | (1) | (since C++11) | | ``` T& operator[]( Key&& key ); ``` | (2) | (since C++11) | Returns a reference to the value that is mapped to a key equivalent to `key`, performing an insertion if such key does not already exist. 1) Inserts a `value_type` object constructed in-place from `[std::piecewise\_construct](http://en.cppreference.com/w/cpp/utility/piecewise_construct), [std::forward\_as\_tuple](http://en.cppreference.com/w/cpp/utility/tuple/forward_as_tuple)(key), [std::tuple](http://en.cppreference.com/w/cpp/utility/tuple)<>()` if the key does not exist. This function is equivalent to `return this->try_emplace(key).first->second;`. (since C++17) When the default allocator is used, this results in the key being copy constructed from `key` and the mapped value being [value-initialized](../../language/value_initialization "cpp/language/value initialization"). | | | --- | | -`value_type` must be [EmplaceConstructible](../../named_req/emplaceconstructible "cpp/named req/EmplaceConstructible") from `[std::piecewise\_construct](http://en.cppreference.com/w/cpp/utility/piecewise_construct), [std::forward\_as\_tuple](http://en.cppreference.com/w/cpp/utility/tuple/forward_as_tuple)(key), [std::tuple](http://en.cppreference.com/w/cpp/utility/tuple)<>()`. When the default allocator is used, this means that `key_type` must be [CopyConstructible](../../named_req/copyconstructible "cpp/named req/CopyConstructible") and `mapped_type` must be [DefaultConstructible](../../named_req/defaultconstructible "cpp/named req/DefaultConstructible"). | 2) Inserts a `value_type` object constructed in-place from `[std::piecewise\_construct](http://en.cppreference.com/w/cpp/utility/piecewise_construct), [std::forward\_as\_tuple](http://en.cppreference.com/w/cpp/utility/tuple/forward_as_tuple)(std::move(key)), [std::tuple](http://en.cppreference.com/w/cpp/utility/tuple)<>()` if the key does not exist. This function is equivalent to `return this->try_emplace(std::move(key)).first->second;`. (since C++17) When the default allocator is used, this results in the key being move constructed from `key` and the mapped value being [value-initialized](../../language/value_initialization "cpp/language/value initialization"). | | | --- | | -`value_type` must be [EmplaceConstructible](../../named_req/emplaceconstructible "cpp/named req/EmplaceConstructible") from `[std::piecewise\_construct](http://en.cppreference.com/w/cpp/utility/piecewise_construct), [std::forward\_as\_tuple](http://en.cppreference.com/w/cpp/utility/tuple/forward_as_tuple)(std::move(key)), [std::tuple](http://en.cppreference.com/w/cpp/utility/tuple)<>()`. When the default allocator is used, this means that `key_type` must be [MoveConstructible](../../named_req/moveconstructible "cpp/named req/MoveConstructible") and `mapped_type` must be [DefaultConstructible](../../named_req/defaultconstructible "cpp/named req/DefaultConstructible"). | If an insertion occurs and results in a rehashing of the container, all iterators are invalidated. Otherwise iterators are not affected. References are not invalidated. Rehashing occurs only if the new number of elements is greater than `max_load_factor()*bucket_count()`. ### Parameters | | | | | --- | --- | --- | | key | - | the key of the element to find | ### Return value Reference to the mapped value of the new element if no element with key `key` existed. Otherwise a reference to the mapped value of the existing element whose key is equivalent to `key`. ### Exceptions If an exception is thrown by any operation, the insertion has no effect. ### Complexity Average case: constant, worst case: linear in size. ### Notes In the published C++11 and C++14 standards, this function was specified to require `mapped_type` to be [DefaultInsertable](../../named_req/defaultinsertable "cpp/named req/DefaultInsertable") and `key_type` to be [CopyInsertable](../../named_req/copyinsertable "cpp/named req/CopyInsertable") or [MoveInsertable](../../named_req/moveinsertable "cpp/named req/MoveInsertable") into `*this`. This specification was defective and was fixed by [LWG issue 2469](https://cplusplus.github.io/LWG/issue2469), and the description above incorporates the resolution of that issue. However, one implementation (libc++) is known to construct the `key_type` and `mapped_type` objects via two separate allocator `construct()` calls, as arguably required by the standards as published, rather than emplacing a `value_type` object. `operator[]` is non-const because it inserts the key if it doesn't exist. If this behavior is undesirable or if the container is `const`, [`at()`](at "cpp/container/unordered map/at") may be used. | | | | --- | --- | | [`insert_or_assign()`](insert_or_assign "cpp/container/unordered map/insert or assign") returns more information than `operator[]` and does not require default-constructibility of the mapped type. | (since C++17) | ### Example ``` #include <iostream> #include <string> #include <unordered_map> auto print = [](auto const comment, auto const& map) { std::cout << comment << "{"; for (const auto &pair : map) { std::cout << "{" << pair.first << ": " << pair.second << "}"; } std::cout << "}\n"; }; int main() { std::unordered_map<char, int> letter_counts {{'a', 27}, {'b', 3}, {'c', 1}}; print("letter_counts initially contains: ", letter_counts); letter_counts['b'] = 42; // updates an existing value letter_counts['x'] = 9; // inserts a new value print("after modifications it contains: ", letter_counts); // count the number of occurrences of each word // (the first call to operator[] initialized the counter with zero) std::unordered_map<std::string, int> word_map; for (const auto &w : { "this", "sentence", "is", "not", "a", "sentence", "this", "sentence", "is", "a", "hoax"}) { ++word_map[w]; } word_map["that"]; // just inserts the pair {"that", 0} for (const auto &[word, count] : word_map) { std::cout << count << " occurrences of word '" << word << "'\n"; } } ``` Possible output: ``` letter_counts initially contains: {{a: 27}{b: 3}{c: 1}} after modifications it contains: {{a: 27}{b: 42}{c: 1}{x: 9}} 2 occurrences of word 'a' 1 occurrences of word 'hoax' 2 occurrences of word 'is' 1 occurrences of word 'not' 3 occurrences of word 'sentence' 0 occurrences of word 'that' 2 occurrences of word 'this' ``` ### See also | | | | --- | --- | | [at](at "cpp/container/unordered map/at") (C++11) | access specified element with bounds checking (public member function) | | [insert\_or\_assign](insert_or_assign "cpp/container/unordered map/insert or assign") (C++17) | inserts an element or assigns to the current element if the key already exists (public member function) | | [try\_emplace](try_emplace "cpp/container/unordered map/try emplace") (C++17) | inserts in-place if the key does not exist, does nothing if the key exists (public member function) | cpp std::unordered_map<Key,T,Hash,KeyEqual,Allocator>::swap std::unordered\_map<Key,T,Hash,KeyEqual,Allocator>::swap ======================================================== | | | | | --- | --- | --- | | ``` void swap( unordered_map& other ); ``` | | (since C++11) (until C++17) | | ``` void swap( unordered_map& other ) noexcept(/* see below */); ``` | | (since C++17) | Exchanges the contents of the container with those of `other`. Does not invoke any move, copy, or swap operations on individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated. The `Hash` and `KeyEqual` objects must be [Swappable](../../named_req/swappable "cpp/named req/Swappable"), and they are exchanged using unqualified calls to non-member `swap`. | | | | --- | --- | | If `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<allocator_type>::propagate\_on\_container\_swap::value` is true, then the allocators are exchanged using an unqualified call to non-member `swap`. Otherwise, they are not swapped (and if `get_allocator() != other.get_allocator()`, the behavior is undefined). | (since C++11) | ### Parameters | | | | | --- | --- | --- | | other | - | container to exchange the contents with | ### Return value (none). ### Exceptions | | | | --- | --- | | Any exception thrown by the swap of the `Hash` or `KeyEqual` objects. | (until C++17) | | [`noexcept`](../../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept([std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<Allocator>::is\_always\_equal::value && [std::is\_nothrow\_swappable](http://en.cppreference.com/w/cpp/types/is_swappable)<Hash>::value. && [std::is\_nothrow\_swappable](http://en.cppreference.com/w/cpp/types/is_swappable)<key_equal>::value)` | (since C++17) | ### Complexity Constant. ### Example ``` #include <iostream> #include <string> #include <utility> #include <unordered_map> // print out a std::pair template <class Os, class U, class V> Os& operator<<(Os& os, const std::pair<U, V>& p) { return os << p.first << ":" << p.second; } // print out a container template <class Os, class Co> Os& operator<<(Os& os, const Co& co) { os << "{"; for (auto const& i : co) { os << ' ' << i; } return os << " }\n"; } int main() { std::unordered_map<std::string, std::string> m1 { {"γ", "gamma"}, {"β", "beta"}, {"α", "alpha"}, {"γ", "gamma"}, }, m2 { {"ε", "epsilon"}, {"δ", "delta"}, {"ε", "epsilon"} }; const auto& ref = *(m1.begin()); const auto iter = std::next(m1.cbegin()); std::cout << "──────── before swap ────────\n" << "m1: " << m1 << "m2: " << m2 << "ref: " << ref << "\niter: " << *iter << '\n'; m1.swap(m2); std::cout << "──────── after swap ────────\n" << "m1: " << m1 << "m2: " << m2 << "ref: " << ref << "\niter: " << *iter << '\n'; // Note that every iterator referring to an element in one container before // the swap refers to the same element in the other container after the swap. // Same is true for references. } ``` Possible output: ``` ──────── before swap ──────── m1: { α:alpha β:beta γ:gamma } m2: { δ:delta ε:epsilon } ref: α:alpha iter: β:beta ──────── after swap ──────── m1: { δ:delta ε:epsilon } m2: { α:alpha β:beta γ:gamma } ref: α:alpha iter: β:beta ``` ### See also | | | | --- | --- | | [std::swap(std::unordered\_map)](swap2 "cpp/container/unordered map/swap2") (C++11) | specializes the `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | cpp std::unordered_map<Key,T,Hash,KeyEqual,Allocator>::max_size std::unordered\_map<Key,T,Hash,KeyEqual,Allocator>::max\_size ============================================================= | | | | | --- | --- | --- | | ``` size_type max_size() const noexcept; ``` | | (since C++11) | Returns the maximum number of elements the container is able to hold due to system or library implementation limitations, i.e. `[std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(begin(), end())` for the largest container. ### Parameters (none). ### Return value Maximum number of elements. ### Complexity Constant. ### Notes This value typically reflects the theoretical limit on the size of the container, at most `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<difference_type>::max()`. At runtime, the size of the container may be limited to a value smaller than `max_size()` by the amount of RAM available. ### Example ``` #include <iostream> #include <locale> #include <unordered_map> int main() { std::unordered_map<char, char> q; std::cout.imbue(std::locale("en_US.UTF-8")); std::cout << "Maximum size of a std::unordered_map is " << q.max_size() << '\n'; } ``` Possible output: ``` Maximum size of a std::unordered_map is 768,614,336,404,564,650 ``` ### See also | | | | --- | --- | | [size](size "cpp/container/unordered map/size") (C++11) | returns the number of elements (public member function) | cpp std::unordered_map<Key,T,Hash,KeyEqual,Allocator>::count std::unordered\_map<Key,T,Hash,KeyEqual,Allocator>::count ========================================================= | | | | | --- | --- | --- | | ``` size_type count( const Key& key ) const; ``` | (1) | (since C++11) | | ``` template< class K > size_type count( const K& x ) const; ``` | (2) | (since C++20) | 1) Returns the number of elements with key that compares equal to the specified argument `key`, which is either 1 or 0 since this container does not allow duplicates. 2) Returns the number of elements with key that compares equivalent to the specified argument `x`. This overload participates in overload resolution only if `Hash::is_transparent` and `KeyEqual::is_transparent` are valid and each denotes a type. This assumes that such `Hash` is callable with both `K` and `Key` type, and that the `KeyEqual` is transparent, which, together, allows calling this function without constructing an instance of `Key`. ### Parameters | | | | | --- | --- | --- | | key | - | key value of the elements to count | | x | - | a value of any type that can be transparently compared with a key | ### Return value 1) Number of elements with key `key`, that is either 1 or 0. 2) Number of elements with key that compares equivalent to `x`. ### Complexity Constant on average, worst case linear in the size of the container. ### Notes | [Feature-test](../../utility/feature_test "cpp/utility/feature test") macro | Comment | | --- | --- | | [`__cpp_lib_generic_unordered_lookup`](../../feature_test#Library_features "cpp/feature test") | for overload (2) | ### Example ``` #include <string> #include <iostream> #include <unordered_map> int main() { std::unordered_map<int, std::string> dict = { {1, "one"}, {6, "six"}, {3, "three"} }; dict.insert({4, "four"}); dict.insert({5, "five"}); dict.insert({6, "six"}); std::cout << "dict: { "; for (auto const& [key, value] : dict) { std::cout << "[" << key << "]=" << value << " "; } std::cout << "}\n\n"; for (int i{1}; i != 8; ++i) { std::cout << "dict.count(" << i << ") = " << dict.count(i) << '\n'; } } ``` Possible output: ``` dict: { [5]=five [4]=four [1]=one [6]=six [3]=three } dict.count(1) = 1 dict.count(2) = 0 dict.count(3) = 1 dict.count(4) = 1 dict.count(5) = 1 dict.count(6) = 1 dict.count(7) = 0 ``` ### See also | | | | --- | --- | | [find](find "cpp/container/unordered map/find") (C++11) | finds element with specific key (public member function) | | [contains](contains "cpp/container/unordered map/contains") (C++20) | checks if the container contains element with specific key (public member function) | | [equal\_range](equal_range "cpp/container/unordered map/equal range") (C++11) | returns range of elements matching a specific key (public member function) |
programming_docs
cpp std::unordered_map<Key,T,Hash,KeyEqual,Allocator>::bucket_size std::unordered\_map<Key,T,Hash,KeyEqual,Allocator>::bucket\_size ================================================================ | | | | | --- | --- | --- | | ``` size_type bucket_size( size_type n ) const; ``` | | (since C++11) | Returns the number of elements in the bucket with index `n`. ### Parameters | | | | | --- | --- | --- | | n | - | the index of the bucket to examine | ### Return value The number of elements in the bucket `n`. ### Complexity Linear in the size of the bucket `n`. ### See also | | | | --- | --- | | [bucket\_count](bucket_count "cpp/container/unordered map/bucket count") (C++11) | returns the number of buckets (public member function) | cpp std::unordered_map<Key,T,Hash,KeyEqual,Allocator>::max_bucket_count std::unordered\_map<Key,T,Hash,KeyEqual,Allocator>::max\_bucket\_count ====================================================================== | | | | | --- | --- | --- | | ``` size_type max_bucket_count() const; ``` | | (since C++11) | Returns the maximum number of buckets the container is able to hold due to system or library implementation limitations. ### Parameters (none). ### Return value Maximum number of buckets. ### Complexity Constant. ### Example ``` #include <iostream> #include <unordered_map> int main() { struct Ha { std::size_t operator()(long x) const { return std::hash<long>{}(x); }; }; auto c1 = std::unordered_map<char, long>{}; auto c2 = std::unordered_map<long, long>{}; auto c3 = std::unordered_map<long, long, std::hash<int>>{}; auto c4 = std::unordered_map<long, long, Ha>{}; std::cout << "Max bucket count of\n" << std::hex << std::showbase << "c1: " << c1.max_bucket_count() << '\n' << "c2: " << c2.max_bucket_count() << '\n' << "c3: " << c3.max_bucket_count() << '\n' << "c4: " << c4.max_bucket_count() << '\n' ; } ``` Possible output: ``` Max bucket count of c1: 0xfffffffffffffff c2: 0xfffffffffffffff c3: 0xfffffffffffffff c4: 0xaaaaaaaaaaaaaaa ``` ### See also | | | | --- | --- | | [bucket\_count](bucket_count "cpp/container/unordered map/bucket count") (C++11) | returns the number of buckets (public member function) | cpp std::unordered_map<Key,T,Hash,KeyEqual,Allocator>::find std::unordered\_map<Key,T,Hash,KeyEqual,Allocator>::find ======================================================== | | | | | --- | --- | --- | | ``` iterator find( const Key& key ); ``` | (1) | | | ``` const_iterator find( const Key& key ) const; ``` | (2) | | | ``` template< class K > iterator find( const K& x ); ``` | (3) | (since C++20) | | ``` template< class K > const_iterator find( const K& x ) const; ``` | (4) | (since C++20) | 1,2) Finds an element with key equivalent to `key`. 3,4) Finds an element with key that compares *equivalent* to the value `x`. This overload participates in overload resolution only if `Hash::is_transparent` and `KeyEqual::is_transparent` are valid and each denotes a type. This assumes that such `Hash` is callable with both `K` and `Key` type, and that the `KeyEqual` is transparent, which, together, allows calling this function without constructing an instance of `Key`. ### Parameters | | | | | --- | --- | --- | | key | - | key value of the element to search for | | x | - | a value of any type that can be transparently compared with a key | ### Return value Iterator to an element with key equivalent to `key`. If no such element is found, past-the-end (see `[end()](end "cpp/container/unordered map/end")`) iterator is returned. ### Complexity Constant on average, worst case linear in the size of the container. ### Notes | [Feature-test](../../utility/feature_test "cpp/utility/feature test") macro | Comment | | --- | --- | | [`__cpp_lib_generic_unordered_lookup`](../../feature_test#Library_features "cpp/feature test") | for overloads (3,4) | ### Example ``` #include <cstddef> #include <iostream> #include <functional> #include <string> #include <string_view> #include <unordered_map> using namespace std::literals; using std::size_t; struct string_hash { using hash_type = std::hash<std::string_view>; using is_transparent = void; size_t operator()(const char* str) const { return hash_type{}(str); } size_t operator()(std::string_view str) const { return hash_type{}(str); } size_t operator()(std::string const& str) const { return hash_type{}(str); } }; int main() { // simple comparison demo std::unordered_map<int,char> example = {{1,'a'},{2,'b'}}; auto search = example.find(2); if (search != example.end()) { std::cout << "Found " << search->first << " " << search->second << '\n'; } else { std::cout << "Not found\n"; } // C++20 demo: Heterogeneous lookup for unordered containers (transparent hashing) std::unordered_map<std::string, size_t, string_hash, std::equal_to<>> map{ {"one"s, 1} }; std::cout << std::boolalpha << (map.find("one") != map.end()) << '\n' << (map.find("one"s) != map.end()) << '\n' << (map.find("one"sv) != map.end()) << '\n'; } ``` Output: ``` Found 2 b true true true ``` ### See also | | | | --- | --- | | [count](count "cpp/container/unordered map/count") (C++11) | returns the number of elements matching specific key (public member function) | | [equal\_range](equal_range "cpp/container/unordered map/equal range") (C++11) | returns range of elements matching a specific key (public member function) | cpp std::unordered_map<Key,T,Hash,KeyEqual,Allocator>::equal_range std::unordered\_map<Key,T,Hash,KeyEqual,Allocator>::equal\_range ================================================================ | | | | | --- | --- | --- | | ``` std::pair<iterator,iterator> equal_range( const Key& key ); ``` | (1) | (since C++11) | | ``` std::pair<const_iterator,const_iterator> equal_range( const Key& key ) const; ``` | (2) | (since C++11) | | ``` template< class K > std::pair<iterator,iterator> equal_range( const K& x ); ``` | (3) | (since C++20) | | ``` template< class K > std::pair<const_iterator,const_iterator> equal_range( const K& x ) const; ``` | (4) | (since C++20) | 1,2) Returns a range containing all elements with key `key` in the container. The range is defined by two iterators, the first pointing to the first element of the wanted range and the second pointing past the last element of the range. 3,4) Returns a range containing all elements in the container with key equivalent to `x`. This overload participates in overload resolution only if `Hash::is_transparent` and `KeyEqual::is_transparent` are valid and each denotes a type. This assumes that such `Hash` is callable with both `K` and `Key` type, and that the `KeyEqual` is transparent, which, together, allows calling this function without constructing an instance of `Key`. ### Parameters | | | | | --- | --- | --- | | key | - | key value to compare the elements to | | x | - | a value of any type that can be transparently compared with a key | ### Return value `[std::pair](../../utility/pair "cpp/utility/pair")` containing a pair of iterators defining the wanted range. If there are no such elements, past-the-end (see `[end()](end "cpp/container/unordered map/end")`) iterators are returned as both elements of the pair. ### Complexity Average case linear in the number of elements with the key `key`, worst case linear in the size of the container. ### Notes | [Feature-test](../../utility/feature_test "cpp/utility/feature test") macro | Comment | | --- | --- | | [`__cpp_lib_generic_unordered_lookup`](../../feature_test#Library_features "cpp/feature test") | for overloads (3,4) | ### Example ``` #include <iostream> #include <unordered_map> int main() { std::unordered_map<int,char> map = {{1,'a'},{1,'b'},{1,'d'},{2,'b'}}; auto range = map.equal_range(1); for (auto it = range.first; it != range.second; ++it) { std::cout << it->first << ' ' << it->second << '\n'; } } ``` Output: ``` 1 a ``` ### See also | | | | --- | --- | | [find](find "cpp/container/unordered map/find") (C++11) | finds element with specific key (public member function) | | [contains](contains "cpp/container/unordered map/contains") (C++20) | checks if the container contains element with specific key (public member function) | | [count](count "cpp/container/unordered map/count") (C++11) | returns the number of elements matching specific key (public member function) | | [equal\_range](../../algorithm/equal_range "cpp/algorithm/equal range") | returns range of elements matching a specific key (function template) | cpp std::unordered_map<Key,T,Hash,KeyEqual,Allocator>::unordered_map std::unordered\_map<Key,T,Hash,KeyEqual,Allocator>::unordered\_map ================================================================== | | | | | --- | --- | --- | | ``` unordered_map() : unordered_map( size_type(/*implementation-defined*/) ) {} explicit unordered_map( size_type bucket_count, const Hash& hash = Hash(), const key_equal& equal = key_equal(), const Allocator& alloc = Allocator() ); ``` | (1) | (since C++11) | | ``` unordered_map( size_type bucket_count, const Allocator& alloc ) : unordered_map(bucket_count, Hash(), key_equal(), alloc) {} unordered_map( size_type bucket_count, const Hash& hash, const Allocator& alloc ) : unordered_map(bucket_count, hash, key_equal(), alloc) {} ``` | (1) | (since C++14) | | ``` explicit unordered_map( const Allocator& alloc ); ``` | (1) | (since C++11) | | ``` template< class InputIt > unordered_map( InputIt first, InputIt last, size_type bucket_count = /*implementation-defined*/, const Hash& hash = Hash(), const key_equal& equal = key_equal(), const Allocator& alloc = Allocator() ); ``` | (2) | (since C++11) | | ``` template< class InputIt > unordered_map( InputIt first, InputIt last, size_type bucket_count, const Allocator& alloc ) : unordered_map(first, last, bucket_count, Hash(), key_equal(), alloc) {} ``` | (2) | (since C++14) | | ``` template< class InputIt > unordered_map( InputIt first, InputIt last, size_type bucket_count, const Hash& hash, const Allocator& alloc ) : unordered_map(first, last, bucket_count, hash, key_equal(), alloc) {} ``` | (2) | (since C++14) | | ``` unordered_map( const unordered_map& other ); ``` | (3) | (since C++11) | | ``` unordered_map( const unordered_map& other, const Allocator& alloc ); ``` | (3) | (since C++11) | | ``` unordered_map( unordered_map&& other ); ``` | (4) | (since C++11) | | ``` unordered_map( unordered_map&& other, const Allocator& alloc ); ``` | (4) | (since C++11) | | ``` unordered_map( std::initializer_list<value_type> init, size_type bucket_count = /*implementation-defined*/, const Hash& hash = Hash(), const key_equal& equal = key_equal(), const Allocator& alloc = Allocator() ); ``` | (5) | (since C++11) | | ``` unordered_map( std::initializer_list<value_type> init, size_type bucket_count, const Allocator& alloc ) : unordered_map(init, bucket_count, Hash(), key_equal(), alloc) {} ``` | (5) | (since C++14) | | ``` unordered_map( std::initializer_list<value_type> init, size_type bucket_count, const Hash& hash, const Allocator& alloc ) : unordered_map(init, bucket_count, hash, key_equal(), alloc) {} ``` | (5) | (since C++14) | Constructs new container from a variety of data sources. Optionally uses user supplied `bucket_count` as a minimal number of buckets to create, `hash` as the hash function, `equal` as the function to compare keys and `alloc` as the allocator. 1) Constructs empty container. Sets `[max\_load\_factor()](max_load_factor "cpp/container/unordered map/max load factor")` to 1.0. For the default constructor, the number of buckets is implementation-defined. 2) constructs the container with the contents of the range `[first, last)`. Sets `[max\_load\_factor()](max_load_factor "cpp/container/unordered map/max load factor")` to 1.0. If multiple elements in the range have keys that compare equivalent, it is unspecified which element is inserted (pending [LWG2844](https://cplusplus.github.io/LWG/issue2844)). 3) copy constructor. Constructs the container with the copy of the contents of `other`, copies the load factor, the predicate, and the hash function as well. If `alloc` is not provided, allocator is obtained by calling `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<allocator_type>::select\_on\_container\_copy\_construction(other.get\_allocator())`. | | | | --- | --- | | The template parameter `Allocator` is only deduced from the first argument while used in [class template argument deduction](../../language/class_template_argument_deduction "cpp/language/class template argument deduction"). | (since C++23) | 4) move constructor. Constructs the container with the contents of `other` using move semantics. If `alloc` is not provided, allocator is obtained by move-construction from the allocator belonging to `other`. | | | | --- | --- | | The template parameter `Allocator` is only deduced from the first argument while used in [class template argument deduction](../../language/class_template_argument_deduction "cpp/language/class template argument deduction"). | (since C++23) | 5) constructs the container with the contents of the initializer list `init`, same as `unordered_map(init.begin(), init.end())`. ### Parameters | | | | | --- | --- | --- | | alloc | - | allocator to use for all memory allocations of this container | | bucket\_count | - | minimal number of buckets to use on initialization. If it is not specified, implementation-defined default value is used | | hash | - | hash function to use | | equal | - | comparison function to use for all key comparisons of this container | | first, last | - | the range to copy the elements from | | other | - | another container to be used as source to initialize the elements of the container with | | init | - | initializer list to initialize the elements of the container with | | Type requirements | | -`InputIt` must meet the requirements of [LegacyInputIterator](../../named_req/inputiterator "cpp/named req/InputIterator"). | ### Complexity 1) constant 2) average case linear worst case quadratic in distance between `first` and `last` 3) linear in size of `other` 4) constant. If `alloc` is given and `alloc != other.get_allocator()`, then linear. 5) average case linear worst case quadratic in size of `init` ### Exceptions Calls to `Allocator::allocate` may throw. ### Notes After container move construction (overload (4)), references, pointers, and iterators (other than the end iterator) to `other` remain valid, but refer to elements that are now in `*this`. The current standard makes this guarantee via the blanket statement in [[container.requirements.general]/12](https://eel.is/c++draft/container.requirements.general#12), and a more direct guarantee is under consideration via [LWG 2321](https://cplusplus.github.io/LWG/issue2321). Although not formally required until C++23, some implementations has already put the template parameter `Allocator` into [non-deduced contexts](../../language/template_argument_deduction#Non-deduced_contexts "cpp/language/template argument deduction") in earlier modes. ### Example ``` #include <unordered_map> #include <vector> #include <bitset> #include <string> #include <utility> struct Key { std::string first; std::string second; }; struct KeyHash { std::size_t operator()(const Key& k) const { return std::hash<std::string>()(k.first) ^ (std::hash<std::string>()(k.second) << 1); } }; struct KeyEqual { bool operator()(const Key& lhs, const Key& rhs) const { return lhs.first == rhs.first && lhs.second == rhs.second; } }; struct Foo { Foo(int val_) : val(val_) {} int val; bool operator==(const Foo &rhs) const { return val == rhs.val; } }; template<> struct std::hash<Foo> { std::size_t operator()(const Foo &f) const { return std::hash<int>{}(f.val); } }; int main() { // default constructor: empty map std::unordered_map<std::string, std::string> m1; // list constructor std::unordered_map<int, std::string> m2 = { {1, "foo"}, {3, "bar"}, {2, "baz"}, }; // copy constructor std::unordered_map<int, std::string> m3 = m2; // move constructor std::unordered_map<int, std::string> m4 = std::move(m2); // range constructor std::vector<std::pair<std::bitset<8>, int>> v = { {0x12, 1}, {0x01,-1} }; std::unordered_map<std::bitset<8>, double> m5(v.begin(), v.end()); //Option 1 for a constructor with a custom Key type // Define the KeyHash and KeyEqual structs and use them in the template std::unordered_map<Key, std::string, KeyHash, KeyEqual> m6 = { { {"John", "Doe"}, "example"}, { {"Mary", "Sue"}, "another"} }; //Option 2 for a constructor with a custom Key type // Define a const == operator for the class/struct and specialize std::hash // structure in the std namespace std::unordered_map<Foo, std::string> m7 = { { Foo(1), "One"}, { 2, "Two"}, { 3, "Three"} }; //Option 3: Use lambdas // Note that the initial bucket count has to be passed to the constructor struct Goo {int val; }; auto hash = [](const Goo &g){ return std::hash<int>{}(g.val); }; auto comp = [](const Goo &l, const Goo &r){ return l.val == r.val; }; std::unordered_map<Goo, double, decltype(hash), decltype(comp)> m8(10, hash, comp); } ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 2193](https://cplusplus.github.io/LWG/issue2193) | C++11 | the default constructor is explicit | made non-explicit | ### See also | | | | --- | --- | | [operator=](operator= "cpp/container/unordered map/operator=") (C++11) | assigns values to the container (public member function) | cpp std::unordered_map<Key,T,Hash,KeyEqual,Allocator>::erase std::unordered\_map<Key,T,Hash,KeyEqual,Allocator>::erase ========================================================= | | | | | --- | --- | --- | | | (1) | | | ``` iterator erase( iterator pos ); ``` | (since C++11) | | ``` iterator erase( const_iterator pos ); ``` | (since C++11) | | | (2) | | | ``` iterator erase( const_iterator first, const_iterator last ); ``` | (since C++11) | | ``` size_type erase( const Key& key ); ``` | (3) | (since C++11) | | ``` template< class K > size_type erase( K&& x ); ``` | (4) | (since C++23) | Removes specified elements from the container. 1) Removes the element at `pos`. 2) Removes the elements in the range `[first; last)`, which must be a valid range in `*this`. 3) Removes the element (if one exists) with the key equivalent to `key`. 4) Removes the element (if one exists) with key that compares *equivalent* to the value `x`. This overload participates in overload resolution only if `Hash::is_transparent` and `KeyEqual::is_transparent` are valid and each denotes a type, and neither `iterator` nor `const_iterator` is implicitly convertible from `K`. This assumes that such `Hash` is callable with both `K` and `Key` type, and that the `KeyEqual` is transparent, which, together, allows calling this function without constructing an instance of `Key`. References and iterators to the erased elements are invalidated. Other iterators and references are not invalidated. The iterator `pos` must be valid and dereferenceable. Thus the `[end()](end "cpp/container/unordered map/end")` iterator (which is valid, but is not dereferenceable) cannot be used as a value for `pos`. The order of the elements that are not erased is preserved. (This makes it possible to erase individual elements while iterating through the container.). ### Parameters | | | | | --- | --- | --- | | pos | - | iterator to the element to remove | | first, last | - | range of elements to remove | | key | - | key value of the elements to remove | | x | - | a value of any type that can be transparently compared with a key denoting the elements to remove | ### Return value 1-2) Iterator following the last removed element. 3,4) Number of elements removed (`0` or `1`). ### Exceptions 1,2) Throws nothing. 3,4) Any exceptions thrown by the `Hash` and `KeyEqual` object. ### Complexity Given an instance `c` of `unordered_map`: 1) Average case: constant, worst case: `c.size()` 2) Average case: `[std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(first, last)`, worst case: `c.size()` 3) Average case: `c.count(key)`, worst case: `c.size()` 4) Average case: `c.count(x)`, worst case: `c.size()` ### Notes | [Feature-test](../../utility/feature_test "cpp/utility/feature test") macro | Comment | | --- | --- | | [`__cpp_lib_associative_heterogeneous_erasure`](../../feature_test#Library_features "cpp/feature test") | for overload (4) | ### Example ``` #include <unordered_map> #include <iostream> int main() { std::unordered_map<int, std::string> c = { {1, "one" }, {2, "two" }, {3, "three"}, {4, "four"}, {5, "five"}, {6, "six" } }; // erase all odd numbers from c for(auto it = c.begin(); it != c.end(); ) { if(it->first % 2 != 0) it = c.erase(it); else ++it; } for(auto& p : c) { std::cout << p.second << ' '; } } ``` Possible output: ``` two four six ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 2059](https://cplusplus.github.io/LWG/issue2059) | C++11 | overload for one `const_iterator` introduced new ambiguity | overload for `iterator` added | | [LWG 2356](https://cplusplus.github.io/LWG/issue2356) | C++11 | the order of element that are not erased was unspecified | required to be preserved | ### See also | | | | --- | --- | | [clear](clear "cpp/container/unordered map/clear") (C++11) | clears the contents (public member function) |
programming_docs
cpp std::unordered_map<Key,T,Hash,KeyEqual,Allocator>::load_factor std::unordered\_map<Key,T,Hash,KeyEqual,Allocator>::load\_factor ================================================================ | | | | | --- | --- | --- | | ``` float load_factor() const; ``` | | (since C++11) | Returns the average number of elements per bucket, that is, `[size()](size "cpp/container/unordered map/size")` divided by `[bucket\_count()](bucket_count "cpp/container/unordered map/bucket count")`. ### Parameters (none). ### Return value Average number of elements per bucket. ### Complexity Constant. ### See also | | | | --- | --- | | [max\_load\_factor](max_load_factor "cpp/container/unordered map/max load factor") (C++11) | manages maximum average number of elements per bucket (public member function) | cpp std::swap(std::unordered_map) std::swap(std::unordered\_map) ============================== | Defined in header `[<unordered\_map>](../../header/unordered_map "cpp/header/unordered map")` | | | | --- | --- | --- | | ``` template< class Key, class T, class Hash, class KeyEqual, class Alloc > void swap( std::unordered_map<Key,T,Hash,KeyEqual,Alloc>& lhs, std::unordered_map<Key,T,Hash,KeyEqual,Alloc>& rhs ); ``` | | (since C++11) (until C++17) | | ``` template< class Key, class T, class Hash, class KeyEqual, class Alloc > void swap( std::unordered_map<Key,T,Hash,KeyEqual,Alloc>& lhs, std::unordered_map<Key,T,Hash,KeyEqual,Alloc>& rhs ) noexcept(/* see below */); ``` | | (since C++17) | Specializes the `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` algorithm for `[std::unordered\_map](http://en.cppreference.com/w/cpp/container/unordered_map)`. Swaps the contents of `lhs` and `rhs`. Calls `lhs.swap(rhs)`. ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | containers whose contents to swap | ### Return value (none). ### Complexity Constant. ### Exceptions | | | | --- | --- | | [`noexcept`](../../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept(noexcept(lhs.swap(rhs)))` | (since C++17) | ### Notes Although the overloads of `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` for container adaptors are introduced in C++11, container adaptors can already be swapped by `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` in C++98. Such calls to `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` usually have linear time complexity, but better complexity may be provided. ### Example ``` #include <algorithm> #include <iostream> #include <unordered_map> int main() { std::unordered_map<int, char> alice{{1, 'a'}, {2, 'b'}, {3, 'c'}}; std::unordered_map<int, char> bob{{7, 'Z'}, {8, 'Y'}, {9, 'X'}, {10, 'W'}}; auto print = [](std::pair<const int, char>& n) { std::cout << " " << n.first << '(' << n.second << ')'; }; // Print state before swap std::cout << "alice:"; std::for_each(alice.begin(), alice.end(), print); std::cout << "\n" "bob :"; std::for_each(bob.begin(), bob.end(), print); std::cout << '\n'; std::cout << "-- SWAP\n"; std::swap(alice, bob); // Print state after swap std::cout << "alice:"; std::for_each(alice.begin(), alice.end(), print); std::cout << "\n" "bob :"; std::for_each(bob.begin(), bob.end(), print); std::cout << '\n'; } ``` Possible output: ``` alice: 1(a) 2(b) 3(c) bob : 7(Z) 8(Y) 9(X) 10(W) -- SWAP alice: 7(Z) 8(Y) 9(X) 10(W) bob : 1(a) 2(b) 3(c) ``` ### See also | | | | --- | --- | | [swap](swap "cpp/container/unordered map/swap") (C++11) | swaps the contents (public member function) | cpp std::unordered_map<Key,T,Hash,KeyEqual,Allocator>::try_emplace std::unordered\_map<Key,T,Hash,KeyEqual,Allocator>::try\_emplace ================================================================ | | | | | --- | --- | --- | | ``` template< class... Args > pair<iterator, bool> try_emplace( const Key& k, Args&&... args ); ``` | (1) | (since C++17) | | ``` template< class... Args > pair<iterator, bool> try_emplace( Key&& k, Args&&... args ); ``` | (2) | (since C++17) | | ``` template< class... Args > iterator try_emplace( const_iterator hint, const Key& k, Args&&... args ); ``` | (3) | (since C++17) | | ``` template< class... Args > iterator try_emplace( const_iterator hint, Key&& k, Args&&... args ); ``` | (4) | (since C++17) | Inserts a new element into the container with key `k` and value constructed with `args`, if there is no element with the key in the container. 1) If a key equivalent to `k` already exists in the container, does nothing. Otherwise, behaves like [`emplace`](emplace "cpp/container/unordered map/emplace") except that the element is constructed as `value_type([std::piecewise\_construct](http://en.cppreference.com/w/cpp/utility/piecewise_construct), [std::forward\_as\_tuple](http://en.cppreference.com/w/cpp/utility/tuple/forward_as_tuple)(k), [std::forward\_as\_tuple](http://en.cppreference.com/w/cpp/utility/tuple/forward_as_tuple). ([std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Args>(args)...))` 2) If a key equivalent to `k` already exists in the container, does nothing. Otherwise, behaves like [`emplace`](emplace "cpp/container/unordered map/emplace") except that the element is constructed as `value_type([std::piecewise\_construct](http://en.cppreference.com/w/cpp/utility/piecewise_construct), [std::forward\_as\_tuple](http://en.cppreference.com/w/cpp/utility/tuple/forward_as_tuple)(std::move(k)), [std::forward\_as\_tuple](http://en.cppreference.com/w/cpp/utility/tuple/forward_as_tuple). ([std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Args>(args)...))` 3) If a key equivalent to `k` already exists in the container, does nothing. Otherwise, behaves like [`emplace_hint`](emplace_hint "cpp/container/unordered map/emplace hint") except that the element is constructed as `value_type([std::piecewise\_construct](http://en.cppreference.com/w/cpp/utility/piecewise_construct), [std::forward\_as\_tuple](http://en.cppreference.com/w/cpp/utility/tuple/forward_as_tuple)(k), [std::forward\_as\_tuple](http://en.cppreference.com/w/cpp/utility/tuple/forward_as_tuple). ([std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Args>(args)...))` 4) If a key equivalent to `k` already exists in the container, does nothing. Otherwise, behaves like [`emplace_hint`](emplace_hint "cpp/container/unordered map/emplace hint") except that the element is constructed as `value_type([std::piecewise\_construct](http://en.cppreference.com/w/cpp/utility/piecewise_construct), [std::forward\_as\_tuple](http://en.cppreference.com/w/cpp/utility/tuple/forward_as_tuple)(std::move(k)), [std::forward\_as\_tuple](http://en.cppreference.com/w/cpp/utility/tuple/forward_as_tuple). ([std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Args>(args)...))` If rehashing occurs due to the insertion, all iterators are invalidated. Otherwise iterators are not affected. References are not invalidated. Rehashing occurs only if the new number of elements is greater than `max_load_factor()*bucket_count()`. ### Parameters | | | | | --- | --- | --- | | k | - | the key used both to look up and to insert if not found | | hint | - | iterator to the position before which the new element will be inserted | | args | - | arguments to forward to the constructor of the element | ### Return value 1,2) Same as for [`emplace`](emplace "cpp/container/unordered map/emplace") 3,4) Same as for [`emplace_hint`](emplace_hint "cpp/container/unordered map/emplace hint") ### Complexity 1,2) Same as for [`emplace`](emplace "cpp/container/unordered map/emplace") 3,4) Same as for [`emplace_hint`](emplace_hint "cpp/container/unordered map/emplace hint") ### Notes Unlike [`insert`](insert "cpp/container/unordered map/insert") or [`emplace`](emplace "cpp/container/unordered map/emplace"), these functions do not move from rvalue arguments if the insertion does not happen, which makes it easy to manipulate maps whose values are move-only types, such as `[std::unordered\_map](http://en.cppreference.com/w/cpp/container/unordered_map)<[std::string](http://en.cppreference.com/w/cpp/string/basic_string), [std::unique\_ptr](http://en.cppreference.com/w/cpp/memory/unique_ptr)<foo>>`. In addition, `try_emplace` treats the key and the arguments to the `mapped_type` separately, unlike [`emplace`](emplace "cpp/container/unordered map/emplace"), which requires the arguments to construct a `value_type` (that is, a `[std::pair](../../utility/pair "cpp/utility/pair")`). | [Feature-test](../../utility/feature_test "cpp/utility/feature test") macro | | --- | | [`__cpp_lib_unordered_map_try_emplace`](../../feature_test#Library_features "cpp/feature test") | ### Example ``` #include <iostream> #include <utility> #include <string> #include <unordered_map> auto print_node = [](const auto &node) { std::cout << "[" << node.first << "] = " << node.second << '\n'; }; auto print_result = [](auto const &pair) { std::cout << (pair.second ? "inserted: " : "ignored: "); print_node(*pair.first); }; int main() { using namespace std::literals; std::unordered_map<std::string, std::string> m; print_result( m.try_emplace("a", "a"s) ); print_result( m.try_emplace("b", "abcd") ); print_result( m.try_emplace("c", 10, 'c') ); print_result( m.try_emplace("c", "Won't be inserted") ); for (const auto &p : m) { print_node(p); } } ``` Possible output: ``` inserted: [a] = a inserted: [b] = abcd inserted: [c] = cccccccccc ignored: [c] = cccccccccc [a] = a [b] = abcd [c] = cccccccccc ``` ### See also | | | | --- | --- | | [emplace](emplace "cpp/container/unordered map/emplace") (C++11) | constructs element in-place (public member function) | | [emplace\_hint](emplace_hint "cpp/container/unordered map/emplace hint") (C++11) | constructs elements in-place using a hint (public member function) | | [insert](insert "cpp/container/unordered map/insert") (C++11) | inserts elements or nodes (since C++17) (public member function) | cpp std::unordered_map<Key,T,Hash,KeyEqual,Allocator>::operator= std::unordered\_map<Key,T,Hash,KeyEqual,Allocator>::operator= ============================================================= | | | | | --- | --- | --- | | ``` unordered_map& operator=( const unordered_map& other ); ``` | (1) | (since C++11) | | | (2) | | | ``` unordered_map& operator=( unordered_map&& other ); ``` | (since C++11) (until C++17) | | ``` unordered_map& operator=( unordered_map&& other ) noexcept(/* see below */); ``` | (since C++17) | | ``` unordered_map& operator=( std::initializer_list<value_type> ilist ); ``` | (3) | (since C++11) | Replaces the contents of the container. 1) Copy assignment operator. Replaces the contents with a copy of the contents of `other`. If `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<allocator_type>::propagate\_on\_container\_copy\_assignment::value` is `true`, the allocator of `*this` is replaced by a copy of that of `other`. If the allocator of `*this` after assignment would compare unequal to its old value, the old allocator is used to deallocate the memory, then the new allocator is used to allocate it before copying the elements. Otherwise, the memory owned by `*this` may be reused when possible. In any case, the elements originally belonging to `*this` may be either destroyed or replaced by element-wise copy-assignment. 2) Move assignment operator. Replaces the contents with those of `other` using move semantics (i.e. the data in `other` is moved from `other` into this container). `other` is in a valid but unspecified state afterwards. If `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<allocator_type>::propagate\_on\_container\_move\_assignment::value` is `true`, the allocator of `*this` is replaced by a copy of that of `other`. If it is `false` and the allocators of `*this` and `other` do not compare equal, `*this` cannot take ownership of the memory owned by `other` and must move-assign each element individually, allocating additional memory using its own allocator as needed. In any case, all elements originally belonging to `*this` are either destroyed or replaced by element-wise move-assignment. 3) Replaces the contents with those identified by initializer list `ilist`. ### Parameters | | | | | --- | --- | --- | | other | - | another container to use as data source | | ilist | - | initializer list to use as data source | ### Return value `*this`. ### Complexity 1) Linear in the size of `*this` and `other`. 2) Linear in the size of `*this` unless the allocators do not compare equal and do not propagate, in which case linear in the size of `*this` and `other`. 3) Linear in the size of `*this` and `ilist`. ### Exceptions | | | | --- | --- | | May throw implementation-defined exceptions. | (until C++17) | | 1,3) May throw implementation-defined exceptions. 2) [`noexcept`](../../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept([std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<Allocator>::is\_always\_equal::value && [std::is\_nothrow\_move\_assignable](http://en.cppreference.com/w/cpp/types/is_move_assignable)<Hash>::value. && [std::is\_nothrow\_move\_assignable](http://en.cppreference.com/w/cpp/types/is_move_assignable)<Pred>::value)` | (since C++17) | ### Notes After container move assignment (overload (2)), unless element-wise move assignment is forced by incompatible allocators, references, pointers, and iterators (other than the end iterator) to `other` remain valid, but refer to elements that are now in `*this`. The current standard makes this guarantee via the blanket statement in [[container.requirements.general]/12](https://eel.is/c++draft/container.requirements.general#12), and a more direct guarantee is under consideration via [LWG 2321](https://cplusplus.github.io/LWG/issue2321). ### Example The following code uses `operator=` to assign one `[std::unordered\_map](../unordered_map "cpp/container/unordered map")` to another: ``` #include <unordered_map> #include <iterator> #include <iostream> #include <utility> #include <initializer_list> void print(auto const comment, auto const& container) { auto size = std::size(container); std::cout << comment << "{ "; for (auto const& [key, value]: container) std::cout << '{' << key << ',' << value << (--size ? "}, " : "} "); std::cout << "}\n"; } int main() { std::unordered_map<int, int> x { {1,1}, {2,2}, {3,3} }, y, z; const auto w = { std::pair<const int, int>{4,4}, {5,5}, {6,6}, {7,7} }; std::cout << "Initially:\n"; print("x = ", x); print("y = ", y); print("z = ", z); std::cout << "Copy assignment copies data from x to y:\n"; y = x; print("x = ", x); print("y = ", y); std::cout << "Move assignment moves data from x to z, modifying both x and z:\n"; z = std::move(x); print("x = ", x); print("z = ", z); std::cout << "Assignment of initializer_list w to z:\n"; z = w; print("w = ", w); print("z = ", z); } ``` Possible output: ``` Initially: x = { {3,3}, {2,2}, {1,1} } y = { } z = { } Copy assignment copies data from x to y: x = { {3,3}, {2,2}, {1,1} } y = { {3,3}, {2,2}, {1,1} } Move assignment moves data from x to z, modifying both x and z: x = { } z = { {3,3}, {2,2}, {1,1} } Assignment of initializer_list w to z: w = { {4,4}, {5,5}, {6,6}, {7,7} } z = { {7,7}, {6,6}, {5,5}, {4,4} } ``` ### See also | | | | --- | --- | | [(constructor)](unordered_map "cpp/container/unordered map/unordered map") (C++11) | constructs the `unordered_map` (public member function) | cpp std::unordered_map<Key,T,Hash,KeyEqual,Allocator>::clear std::unordered\_map<Key,T,Hash,KeyEqual,Allocator>::clear ========================================================= | | | | | --- | --- | --- | | ``` void clear() noexcept; ``` | | (since C++11) | Erases all elements from the container. After this call, `[size()](size "cpp/container/unordered map/size")` returns zero. Invalidates any references, pointers, or iterators referring to contained elements. May also invalidate past-the-end iterators. ### Parameters (none). ### Return value (none). ### Complexity Linear in the size of the container, i.e., the number of elements. ### Example ``` #include <algorithm> #include <iostream> #include <unordered_map> int main() { std::unordered_map<int, char> container{{1, 'x'}, {2, 'y'}, {3, 'z'}}; auto print = [](std::pair<const int, char>& n) { std::cout << " " << n.first << '(' << n.second << ')'; }; std::cout << "Before clear:"; std::for_each(container.begin(), container.end(), print); std::cout << "\nSize=" << container.size() << '\n'; std::cout << "Clear\n"; container.clear(); std::cout << "After clear:"; std::for_each(container.begin(), container.end(), print); std::cout << "\nSize=" << container.size() << '\n'; } ``` Possible output: ``` Before clear: 1(x) 2(y) 3(z) Size=3 Clear After clear: Size=0 ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 2550](https://cplusplus.github.io/LWG/issue2550) | C++11 | for unordered associative containers, unclear if complexity is linear in the number of elements or buckets | clarified that it's linear in the number of elements | ### See also | | | | --- | --- | | [erase](erase "cpp/container/unordered map/erase") (C++11) | erases elements (public member function) | cpp std::unordered_map<Key,T,Hash,KeyEqual,Allocator>::rehash std::unordered\_map<Key,T,Hash,KeyEqual,Allocator>::rehash ========================================================== | | | | | --- | --- | --- | | ``` void rehash( size_type count ); ``` | | (since C++11) | Sets the number of buckets to `count` and rehashes the container, i.e. puts the elements into appropriate buckets considering that total number of buckets has changed. If the new number of buckets makes load factor more than maximum load factor (`count < size() / max_load_factor()`), then the new number of buckets is at least `size() / max_load_factor()`. ### Parameters | | | | | --- | --- | --- | | count | - | new number of buckets | ### Return value (none). ### Complexity Average case linear in the size of the container, worst case quadratic. ### Notes `rehash(0)` may be used to force an unconditional rehash, such as after suspension of automatic rehashing by temporarily increasing `max_load_factor()`. ### See also | | | | --- | --- | | [reserve](reserve "cpp/container/unordered map/reserve") (C++11) | reserves space for at least the specified number of elements and regenerates the hash table (public member function) | cpp std::unordered_map<Key,T,Hash,KeyEqual,Allocator>::key_eq std::unordered\_map<Key,T,Hash,KeyEqual,Allocator>::key\_eq =========================================================== | | | | | --- | --- | --- | | ``` key_equal key_eq() const; ``` | | (since C++11) | Returns the function that compares keys for equality. ### Parameters (none). ### Return value The key comparison function. ### Complexity Constant. ### See also | | | | --- | --- | | [hash\_function](hash_function "cpp/container/unordered map/hash function") (C++11) | returns function used to hash the keys (public member function) |
programming_docs
cpp std::unordered_map<Key,T,Hash,KeyEqual,Allocator>::end(size_type), std::unordered_map<Key,T,Hash,KeyEqual,Allocator>::cend(size_type) std::unordered\_map<Key,T,Hash,KeyEqual,Allocator>::end(size\_type), std::unordered\_map<Key,T,Hash,KeyEqual,Allocator>::cend(size\_type) ========================================================================================================================================= | | | | | --- | --- | --- | | ``` local_iterator end( size_type n ); ``` | | (since C++11) | | ``` const_local_iterator end( size_type n ) const; ``` | | (since C++11) | | ``` const_local_iterator cend( size_type n ) const; ``` | | (since C++11) | Returns an iterator to the element following the last element of the bucket with index `n`. . This element acts as a placeholder, attempting to access it results in undefined behavior. ### Parameters | | | | | --- | --- | --- | | n | - | the index of the bucket to access | ### Return value iterator to the element following the last element. ### Complexity Constant. ### See also | | | | --- | --- | | [begin(size\_type) cbegin(size\_type)](begin2 "cpp/container/unordered map/begin2") (C++11) | returns an iterator to the beginning of the specified bucket (public member function) | cpp operator==,!=(std::unordered_map) operator==,!=(std::unordered\_map) ================================== | | | | | --- | --- | --- | | ``` template< class Key, class T, class Hash, class KeyEqual, class Alloc > bool operator==( const std::unordered_map<Key,T,Hash,KeyEqual,Alloc>& lhs, const std::unordered_map<Key,T,Hash,KeyEqual,Alloc>& rhs ); ``` | (1) | | | ``` template< class Key, class T, class Hash, class KeyEqual, class Alloc > bool operator!=( const std::unordered_map<Key,T,Hash,KeyEqual,Alloc>& lhs, const std::unordered_map<Key,T,Hash,KeyEqual,Alloc>& rhs ); ``` | (2) | (until C++20) | Compares the contents of two unordered containers. The contents of two unordered containers `lhs` and `rhs` are equal if the following conditions hold: * `lhs.size() == rhs.size()` * each group of equivalent elements `[lhs_eq1, lhs_eq2)` obtained from `lhs.equal_range(lhs_eq1)` has a corresponding group of equivalent elements in the other container `[rhs_eq1, rhs_eq2)` obtained from `rhs.equal_range(rhs_eq1)`, that has the following properties: + `[std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(lhs_eq1, lhs_eq2) == [std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(rhs_eq1, rhs_eq2)`. + `[std::is\_permutation](http://en.cppreference.com/w/cpp/algorithm/is_permutation)(lhs_eq1, lhs_eq2, rhs_eq1) == true`. The behavior is undefined if `Key` or `T` are not [EqualityComparable](../../named_req/equalitycomparable "cpp/named req/EqualityComparable"). The behavior is also undefined if `hash_function()` and `key_eq()` do (until C++20)`key_eq()` does (since C++20) not have the same behavior on `lhs` and `rhs` or if `operator==` for `Key` is not a refinement of the partition into equivalent-key groups introduced by `key_eq()` (that is, if two elements that compare equal using `operator==` fall into different partitions). | | | | --- | --- | | The `!=` operator is [synthesized](../../language/operators#Relational_operators "cpp/language/operators") from `operator==`. | (since C++20) | ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | unordered containers to compare | ### Return value 1) `true` if the contents of the containers are equal, `false` otherwise 2) `true` if the contents of the containers are not equal, `false` otherwise ### Complexity Proportional to *N* calls to `operator==` on `value_type`, calls to the predicate returned by [`key_eq`](key_eq "cpp/container/unordered map/key eq"), and calls to the hasher returned by [`hash_function`](hash_function "cpp/container/unordered map/hash function"), in the average case, proportional to *N2* in the worst case where *N* is the size of the container. cpp std::unordered_map<Key,T,Hash,KeyEqual,Allocator>::reserve std::unordered\_map<Key,T,Hash,KeyEqual,Allocator>::reserve =========================================================== | | | | | --- | --- | --- | | ``` void reserve( size_type count ); ``` | | (since C++11) | Sets the number of buckets to the number needed to accomodate at least `count` elements without exceeding maximum load factor and rehashes the container, i.e. puts the elements into appropriate buckets considering that total number of buckets has changed. Effectively calls `rehash([std::ceil](http://en.cppreference.com/w/cpp/numeric/math/ceil)(count / max_load_factor()))`. ### Parameters | | | | | --- | --- | --- | | count | - | new capacity of the container | ### Return value (none). ### Complexity Average case linear in the size of the container, worst case quadratic. ### See also | | | | --- | --- | | [rehash](rehash "cpp/container/unordered map/rehash") (C++11) | reserves at least the specified number of buckets and regenerates the hash table (public member function) | cpp std::unordered_map<Key,T,Hash,KeyEqual,Allocator>::empty std::unordered\_map<Key,T,Hash,KeyEqual,Allocator>::empty ========================================================= | | | | | --- | --- | --- | | ``` bool empty() const noexcept; ``` | | (since C++11) (until C++20) | | ``` [[nodiscard]] bool empty() const noexcept; ``` | | (since C++20) | Checks if the container has no elements, i.e. whether `begin() == end()`. ### Parameters (none). ### Return value `true` if the container is empty, `false` otherwise. ### Complexity Constant. ### Example The following code uses `empty` to check if a `[std::unordered\_map](http://en.cppreference.com/w/cpp/container/unordered_map)<int,int>` contains any elements: ``` #include <unordered_map> #include <iostream> #include <utility> int main() { std::unordered_map<int, int> numbers; std::cout << std::boolalpha; std::cout << "Initially, numbers.empty(): " << numbers.empty() << '\n'; numbers.emplace(42, 13); numbers.insert(std::make_pair(13317, 123)); std::cout << "After adding elements, numbers.empty(): " << numbers.empty() << '\n'; } ``` Output: ``` Initially, numbers.empty(): true After adding elements, numbers.empty(): false ``` ### See also | | | | --- | --- | | [size](size "cpp/container/unordered map/size") (C++11) | returns the number of elements (public member function) | | [empty](../../iterator/empty "cpp/iterator/empty") (C++17) | checks whether the container is empty (function template) | cpp std::unordered_map<Key,T,Hash,KeyEqual,Allocator>::begin, std::unordered_map<Key,T,Hash,KeyEqual,Allocator>::cbegin std::unordered\_map<Key,T,Hash,KeyEqual,Allocator>::begin, std::unordered\_map<Key,T,Hash,KeyEqual,Allocator>::cbegin ===================================================================================================================== | | | | | --- | --- | --- | | ``` iterator begin() noexcept; ``` | | (since C++11) | | ``` const_iterator begin() const noexcept; ``` | | (since C++11) | | ``` const_iterator cbegin() const noexcept; ``` | | (since C++11) | Returns an iterator to the first element of the `unordered_map`. If the `unordered_map` is empty, the returned iterator will be equal to `[end()](end "cpp/container/unordered map/end")`. ![range-begin-end.svg]() ### Parameters (none). ### Return value Iterator to the first element. ### Complexity Constant. ### Example ``` #include <cmath> #include <iostream> #include <unordered_map> struct Node { double x, y; }; int main() { Node nodes[3] = { {1, 0}, {2, 0}, {3, 0} }; //mag is a map mapping the address of a Node to its magnitude in the plane std::unordered_map<Node *, double> mag = { { nodes, 1 }, { nodes + 1, 2 }, { nodes + 2, 3 } }; //Change each y-coordinate from 0 to the magnitude for(auto iter = mag.begin(); iter != mag.end(); ++iter){ auto cur = iter->first; // pointer to Node cur->y = mag[cur]; // could also have used cur->y = iter->second; } //Update and print the magnitude of each node for(auto iter = mag.begin(); iter != mag.end(); ++iter){ auto cur = iter->first; mag[cur] = std::hypot(cur->x, cur->y); std::cout << "The magnitude of (" << cur->x << ", " << cur->y << ") is "; std::cout << iter->second << '\n'; } //Repeat the above with the range-based for loop for(auto i : mag) { auto cur = i.first; cur->y = i.second; mag[cur] = std::hypot(cur->x, cur->y); std::cout << "The magnitude of (" << cur->x << ", " << cur->y << ") is "; std::cout << mag[cur] << '\n'; //Note that in contrast to std::cout << iter->second << '\n'; above, // std::cout << i.second << '\n'; will NOT print the updated magnitude } } ``` Possible output: ``` The magnitude of (3, 3) is 4.24264 The magnitude of (1, 1) is 1.41421 The magnitude of (2, 2) is 2.82843 The magnitude of (3, 4.24264) is 5.19615 The magnitude of (1, 1.41421) is 1.73205 The magnitude of (2, 2.82843) is 3.4641 ``` ### See also | | | | --- | --- | | [end cend](end "cpp/container/unordered map/end") (C++11) | returns an iterator to the end (public member function) | | [begincbegin](../../iterator/begin "cpp/iterator/begin") (C++11)(C++14) | returns an iterator to the beginning of a container or array (function template) | cpp std::unordered_map<Key,T,Hash,KeyEqual,Allocator>::begin(size_type), std::unordered_map<Key,T,Hash,KeyEqual,Allocator>::cbegin(size_type) std::unordered\_map<Key,T,Hash,KeyEqual,Allocator>::begin(size\_type), std::unordered\_map<Key,T,Hash,KeyEqual,Allocator>::cbegin(size\_type) ============================================================================================================================================= | | | | | --- | --- | --- | | ``` local_iterator begin( size_type n ); ``` | | (since C++11) | | ``` const_local_iterator begin( size_type n ) const; ``` | | (since C++11) | | ``` const_local_iterator cbegin( size_type n ) const; ``` | | (since C++11) | Returns an iterator to the first element of the bucket with index `n`. ### Parameters | | | | | --- | --- | --- | | n | - | the index of the bucket to access | ### Return value Iterator to the first element. ### Complexity Constant. ### See also | | | | --- | --- | | [end(size\_type) cend(size\_type)](end2 "cpp/container/unordered map/end2") (C++11) | returns an iterator to the end of the specified bucket (public member function) | cpp std::unordered_map<Key,T,Hash,KeyEqual,Allocator>::end, std::unordered_map<Key,T,Hash,KeyEqual,Allocator>::cend std::unordered\_map<Key,T,Hash,KeyEqual,Allocator>::end, std::unordered\_map<Key,T,Hash,KeyEqual,Allocator>::cend ================================================================================================================= | | | | | --- | --- | --- | | ``` iterator end() noexcept; ``` | | (since C++11) | | ``` const_iterator end() const noexcept; ``` | | (since C++11) | | ``` const_iterator cend() const noexcept; ``` | | (since C++11) | Returns an iterator to the element following the last element of the `unordered_map`. This element acts as a placeholder; attempting to access it results in undefined behavior. ![range-begin-end.svg]() ### Parameters (none). ### Return value Iterator to the element following the last element. ### Complexity Constant. ### Example ``` #include <cmath> #include <iostream> #include <unordered_map> struct Node { double x, y; }; int main() { Node nodes[3] = { {1, 0}, {2, 0}, {3, 0} }; //mag is a map mapping the address of a Node to its magnitude in the plane std::unordered_map<Node *, double> mag = { { nodes, 1 }, { nodes + 1, 2 }, { nodes + 2, 3 } }; //Change each y-coordinate from 0 to the magnitude for(auto iter = mag.begin(); iter != mag.end(); ++iter){ auto cur = iter->first; // pointer to Node cur->y = mag[cur]; // could also have used cur->y = iter->second; } //Update and print the magnitude of each node for(auto iter = mag.begin(); iter != mag.end(); ++iter){ auto cur = iter->first; mag[cur] = std::hypot(cur->x, cur->y); std::cout << "The magnitude of (" << cur->x << ", " << cur->y << ") is "; std::cout << iter->second << '\n'; } //Repeat the above with the range-based for loop for(auto i : mag) { auto cur = i.first; cur->y = i.second; mag[cur] = std::hypot(cur->x, cur->y); std::cout << "The magnitude of (" << cur->x << ", " << cur->y << ") is "; std::cout << mag[cur] << '\n'; //Note that in contrast to std::cout << iter->second << '\n'; above, // std::cout << i.second << '\n'; will NOT print the updated magnitude } } ``` Possible output: ``` The magnitude of (3, 3) is 4.24264 The magnitude of (1, 1) is 1.41421 The magnitude of (2, 2) is 2.82843 The magnitude of (3, 4.24264) is 5.19615 The magnitude of (1, 1.41421) is 1.73205 The magnitude of (2, 2.82843) is 3.4641 ``` ### See also | | | | --- | --- | | [begin cbegin](begin "cpp/container/unordered map/begin") (C++11) | returns an iterator to the beginning (public member function) | | [endcend](../../iterator/end "cpp/iterator/end") (C++11)(C++14) | returns an iterator to the end of a container or array (function template) | cpp std::unordered_map<Key,T,Hash,KeyEqual,Allocator>::bucket std::unordered\_map<Key,T,Hash,KeyEqual,Allocator>::bucket ========================================================== | | | | | --- | --- | --- | | ``` size_type bucket( const Key& key ) const; ``` | | (since C++11) | Returns the index of the bucket for key `key`. Elements (if any) with keys equivalent to `key` are always found in this bucket. The returned value is valid only for instances of the container for which `[bucket\_count()](bucket_count "cpp/container/unordered map/bucket count")` returns the same value. The behavior is undefined if `[bucket\_count()](bucket_count "cpp/container/unordered map/bucket count")` is zero. ### Parameters | | | | | --- | --- | --- | | key | - | the value of the key to examine | ### Return value Bucket index for the key `key`. ### Complexity Constant. ### See also | | | | --- | --- | | [bucket\_size](bucket_size "cpp/container/unordered map/bucket size") (C++11) | returns the number of elements in specific bucket (public member function) | cpp std::priority_queue<T,Container,Compare>::pop std::priority\_queue<T,Container,Compare>::pop ============================================== | | | | | --- | --- | --- | | ``` void pop(); ``` | | | Removes the top element from the priority queue. Effectively calls `[std::pop\_heap](http://en.cppreference.com/w/cpp/algorithm/pop_heap)(c.begin(), c.end(), comp); c.pop\_back();` ### Parameters (none). ### Return value (none). ### Complexity Logarithmic number of comparisons plus the complexity of `Container::pop_back`. ### Example ``` #include <queue> #include <iostream> struct Event { int priority{}; char data{' '}; friend bool operator< (Event const& lhs, Event const& rhs) { return lhs.priority < rhs.priority; } friend std::ostream& operator<< (std::ostream& os, Event const& e) { return os << "{ " << e.priority << ", '" << e.data << "' } "; } }; int main() { std::priority_queue<Event> events; std::cout << "Fill the events queue:\n"; for (auto const e: { Event{6,'L'}, {8,'I'}, {9,'S'}, {1,'T'}, {5,'E'}, {3,'N'} }) { std::cout << e << ' '; events.push(e); } std::cout << "\n" "Process events:\n"; for (; !events.empty(); events.pop()) { Event const& e = events.top(); std::cout << e << ' '; } } ``` Output: ``` Fill the events queue: { 6, 'L' } { 8, 'I' } { 9, 'S' } { 1, 'T' } { 5, 'E' } { 3, 'N' } Process events: { 9, 'S' } { 8, 'I' } { 6, 'L' } { 5, 'E' } { 3, 'N' } { 1, 'T' } ``` ### See also | | | | --- | --- | | [emplace](emplace "cpp/container/priority queue/emplace") (C++11) | constructs element in-place and sorts the underlying container (public member function) | | [push](push "cpp/container/priority queue/push") | inserts element and sorts the underlying container (public member function) | | [top](top "cpp/container/priority queue/top") | accesses the top element (public member function) | cpp std::priority_queue<T,Container,Compare>::size std::priority\_queue<T,Container,Compare>::size =============================================== | | | | | --- | --- | --- | | ``` size_type size() const; ``` | | | Returns the number of elements in the underlying container, that is, `c.size()`. ### Parameters (none). ### Return value The number of elements in the container. ### Complexity Constant. ### Example ``` #include <algorithm> #include <iostream> #include <queue> int main() { std::priority_queue<int> container; std::cout << "Initially, container.size(): " << container.size() << '\n'; for (int i = 0; i < 7; ++i) container.push(i); std::cout << "After adding elements, container.size(): " << container.size() << '\n'; } ``` Output: ``` Initially, container.size(): 0 After adding elements, container.size(): 7 ``` ### See also | | | | --- | --- | | [empty](empty "cpp/container/priority queue/empty") | checks whether the underlying container is empty (public member function) | cpp deduction guides for std::priority_queue deduction guides for `std::priority_queue` ========================================== | Defined in header `[<queue>](../../header/queue "cpp/header/queue")` | | | | --- | --- | --- | | ``` template <class Comp, class Container> priority_queue(Comp, Container) -> priority_queue<typename Container::value_type, Container, Comp>; ``` | (1) | (since C++17) | | ``` template<class InputIt, class Comp = std::less</*iter-value-type*/<InputIt>>, class Container = std::vector</*iter-value-type*/<InputIt>> priority_queue(InputIt, InputIt, Comp = Comp(), Container = Container()) -> priority_queue</*iter-value-type*/<InputIt>, Container, Comp>; ``` | (2) | (since C++17) | | ``` template<class Comp, class Container, class Alloc> priority_queue(Comp, Container, Alloc) -> priority_queue<typename Container::value_type, Container, Comp>; ``` | (3) | (since C++17) | | ``` template<class InputIt, class Alloc> priority_queue(InputIt, InputIt, Alloc) -> priority_queue</*iter-value-type*/<InputIt>, std::vector</*iter-value-type*/<InputIt>, Alloc>, std::less</*iter-value-type*/<InputIt>>>; ``` | (4) | (since C++17) | | ``` template<class InputIt, class Comp, class Alloc> priority_queue(InputIt, InputIt, Comp, Alloc) -> priority_queue</*iter-value-type*/<InputIt>, std::vector</*iter-value-type*/<InputIt>, Alloc>, Comp>; ``` | (5) | (since C++17) | | ``` template<class InputIt, class Comp, class Container, class Alloc> priority_queue(InputIt, InputIt, Comp, Container, Alloc) -> priority_queue<typename Container::value_type, Container, Comp>; ``` | (6) | (since C++17) | These [deduction guides](../../language/class_template_argument_deduction "cpp/language/class template argument deduction") are provided for `[std::priority\_queue](../priority_queue "cpp/container/priority queue")` to allow deduction from underlying container type and from an iterator range. `/*iter-value-type*/<It>` denotes `typename [std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<It>::value\_type` for any type `It`. These overloads participate in overload resolution only if. * `InputIt` satisfies [LegacyInputIterator](../../named_req/inputiterator "cpp/named req/InputIterator"), * `Comp` does not satisfy [Allocator](../../named_req/allocator "cpp/named req/Allocator"), * `Container` does not satisfy [Allocator](../../named_req/allocator "cpp/named req/Allocator"), * for overloads (4) and (5), (since C++23) `Alloc` satisfies [Allocator](../../named_req/allocator "cpp/named req/Allocator"), and * for overloads (3) and (6), `[std::uses\_allocator\_v](http://en.cppreference.com/w/cpp/memory/uses_allocator)<Container, Alloc>` is `true`. Note: the extent to which the library determines that a type does not satisfy [LegacyInputIterator](../../named_req/inputiterator "cpp/named req/InputIterator") is unspecified, except that as a minimum integral types do not qualify as input iterators. Likewise, the extent to which it determines that a type does not satisfy [Allocator](../../named_req/allocator "cpp/named req/Allocator") is unspecified, except that as a minimum the member type `Alloc::value_type` must exist and the expression `[std::declval](http://en.cppreference.com/w/cpp/utility/declval)<Alloc&>().allocate([std::size\_t](http://en.cppreference.com/w/cpp/types/size_t){})` must be well-formed when treated as an unevaluated operand. ### Example ``` #include <queue> #include <vector> #include <iostream> #include <functional> int main() { const std::vector<int> v = {1,2,3,4}; std::priority_queue pq1{std::greater<int>{}, v}; // deduces std::priority_queue< // int, std::vector<int>, // std::greater<int>> for (; !pq1.empty(); pq1.pop()) std::cout << pq1.top() << ' '; std::cout << '\n'; std::priority_queue pq2{v.begin(), v.end()}; // deduces std::priority_queue<int> for (; !pq2.empty(); pq2.pop()) std::cout << pq2.top() << ' '; std::cout << '\n'; } ``` Output: ``` 1 2 3 4 4 3 2 1 ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 3506](https://cplusplus.github.io/LWG/issue3506) | C++17 | deduction guides from iterator and allocator were missing | added |
programming_docs
cpp std::priority_queue<T,Container,Compare>::emplace std::priority\_queue<T,Container,Compare>::emplace ================================================== | | | | | --- | --- | --- | | ``` template< class... Args > void emplace( Args&&... args ); ``` | | (since C++11) | Pushes a new element to the priority queue. The element is constructed in-place, i.e. no copy or move operations are performed. The constructor of the element is called with exactly the same arguments as supplied to the function. Effectively calls `c.emplace\_back([std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Args>(args)...); [std::push\_heap](http://en.cppreference.com/w/cpp/algorithm/push_heap)(c.begin(), c.end(), comp);` ### Parameters | | | | | --- | --- | --- | | args | - | arguments to forward to the constructor of the element | ### Return value (none). ### Complexity Logarithmic number of comparisons plus the complexity of `Container::emplace_back`. ### Example ``` #include <iostream> #include <queue> struct S { int id; S(int i, double d, std::string s) : id{i} { std::cout << "S::S(" << i << ", " << d << ", \"" << s << "\");\n"; } friend bool operator< (S const& x, S const& y) { return x.id < y.id; } }; int main() { std::priority_queue<S> adaptor; adaptor.emplace(42, 3.14, "C++"); std::cout << "id: " << adaptor.top().id << '\n'; } ``` Output: ``` S::S(42, 3.14, "C++") id = 42 ``` ### See also | | | | --- | --- | | [push](push "cpp/container/priority queue/push") | inserts element and sorts the underlying container (public member function) | | [pop](pop "cpp/container/priority queue/pop") | removes the top element (public member function) | cpp std::priority_queue<T,Container,Compare>::~priority_queue std::priority\_queue<T,Container,Compare>::~priority\_queue =========================================================== | | | | | --- | --- | --- | | ``` ~priority_queue(); ``` | | | Destructs the `priority_queue`. The destructors of the elements are called and the used storage is deallocated. Note, that if the elements are pointers, the pointed-to objects are not destroyed. ### Complexity Linear in the size of the `priority_queue`. cpp std::priority_queue<T,Container,Compare>::swap std::priority\_queue<T,Container,Compare>::swap =============================================== | | | | | --- | --- | --- | | ``` void swap( priority_queue& other ) noexcept(/* see below */); ``` | | (since C++11) | Exchanges the contents of the container adaptor with those of `other`. Effectively calls `using [std::swap](http://en.cppreference.com/w/cpp/algorithm/swap); swap(c, other.c); swap(comp, other.comp);` ### Parameters | | | | | --- | --- | --- | | other | - | container adaptor to exchange the contents with | ### Return value (none). ### Exceptions | | | | --- | --- | | [`noexcept`](../../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept(noexcept(swap(c, other.c)) && noexcept(swap(comp, other.comp)))` In the expression above, the identifier `swap` is looked up in the same manner as the one used by the C++17 `[std::is\_nothrow\_swappable](../../types/is_swappable "cpp/types/is swappable")` trait. | (since C++11)(until C++17) | | [`noexcept`](../../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept([std::is\_nothrow\_swappable\_v](http://en.cppreference.com/w/cpp/types/is_swappable)<Container> && [std::is\_nothrow\_swappable\_v](http://en.cppreference.com/w/cpp/types/is_swappable)<Compare>)` | (since C++17) | ### Complexity Same as underlying container (typically constant). ### Notes Some implementations (e.g. libc++) provide the `swap` member function as an extension to pre-C++11 modes. ### Example ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 2456](https://cplusplus.github.io/LWG/issue2456) | C++11 | the `noexcept` specification is ill-formed | made to work | ### See also | | | | --- | --- | | [std::swap(std::priority\_queue)](swap2 "cpp/container/priority queue/swap2") (C++11) | specializes the `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | cpp std::priority_queue<T,Container,Compare>::top std::priority\_queue<T,Container,Compare>::top ============================================== | | | | | --- | --- | --- | | ``` const_reference top() const; ``` | | | Returns reference to the top element in the priority queue. This element will be removed on a call to `[pop()](pop "cpp/container/priority queue/pop")`. If default comparison function is used, the returned element is also the greatest among the elements in the queue. ### Parameters (none). ### Return value Reference to the top element as if obtained by a call to `c.front()`. ### Complexity Constant. ### Example ``` #include <queue> #include <iostream> struct Event { int priority{}; char data{' '}; friend bool operator< (Event const& lhs, Event const& rhs) { return lhs.priority < rhs.priority; } friend std::ostream& operator<< (std::ostream& os, Event const& e) { return os << "{ " << e.priority << ", '" << e.data << "' } "; } }; int main() { std::priority_queue<Event> events; std::cout << "Fill the events queue:\n"; for (auto const e: { Event{6,'L'}, {8,'I'}, {9,'S'}, {1,'T'}, {5,'E'}, {3,'N'} }) { std::cout << e << ' '; events.push(e); } std::cout << "\n" "Process events:\n"; for (; !events.empty(); events.pop()) { Event const& e = events.top(); std::cout << e << ' '; } } ``` Output: ``` Fill the events queue: { 6, 'L' } { 8, 'I' } { 9, 'S' } { 1, 'T' } { 5, 'E' } { 3, 'N' } Process events: { 9, 'S' } { 8, 'I' } { 6, 'L' } { 5, 'E' } { 3, 'N' } { 1, 'T' } ``` ### See also | | | | --- | --- | | [pop](pop "cpp/container/priority queue/pop") | removes the top element (public member function) | cpp std::priority_queue<T,Container,Compare>::priority_queue std::priority\_queue<T,Container,Compare>::priority\_queue ========================================================== | | | | | --- | --- | --- | | ``` priority_queue() : priority_queue(Compare(), Container()) { } ``` | (1) | (since C++11) | | ``` explicit priority_queue( const Compare& compare ) : priority_queue(compare, Container()) { } ``` | (2) | (since C++11) | | | (3) | | | ``` explicit priority_queue( const Compare& compare = Compare(), const Container& cont = Container() ); ``` | (until C++11) | | ``` priority_queue( const Compare& compare, const Container& cont ); ``` | (since C++11) | | ``` priority_queue( const Compare& compare, Container&& cont ); ``` | (4) | (since C++11) | | ``` priority_queue( const priority_queue& other ); ``` | (5) | | | ``` priority_queue( priority_queue&& other ); ``` | (6) | (since C++11) | | ``` template< class InputIt > priority_queue( InputIt first, InputIt last, const Compare& compare = Compare() ); ``` | (7) | (since C++11) | | | (8) | | | ``` template< class InputIt > priority_queue( InputIt first, InputIt last, const Compare& compare = Compare(), const Container& cont = Container() ); ``` | (until C++11) | | ``` template< class InputIt > priority_queue( InputIt first, InputIt last, const Compare& compare, const Container& cont ); ``` | (since C++11) | | ``` template< class InputIt > priority_queue( InputIt first, InputIt last, const Compare& compare, Container&& cont ); ``` | (9) | (since C++11) | | ``` template< class Alloc > explicit priority_queue( const Alloc& alloc ); ``` | (10) | (since C++11) | | ``` template< class Alloc > priority_queue( const Compare& compare, const Alloc& alloc ); ``` | (11) | (since C++11) | | ``` template< class Alloc > priority_queue( const Compare& compare, const Container& cont, const Alloc& alloc ); ``` | (12) | (since C++11) | | ``` template< class Alloc > priority_queue( const Compare& compare, Container&& cont, const Alloc& alloc ); ``` | (13) | (since C++11) | | ``` template< class Alloc > priority_queue( const priority_queue& other, const Alloc& alloc ); ``` | (14) | (since C++11) | | ``` template< class Alloc > priority_queue( priority_queue&& other, const Alloc& alloc ); ``` | (15) | (since C++11) | | ``` template< class InputIt, class Alloc > priority_queue( InputIt first, InputIt last, const Alloc& alloc ); ``` | (16) | (since C++11) | | ``` template< class InputIt, class Alloc > priority_queue( InputIt first, InputIt last, const Compare& compare, const Alloc& alloc ); ``` | (17) | (since C++11) | | ``` template< class InputIt, class Alloc > priority_queue( InputIt first, InputIt last, const Compare& compare, const Container& cont, const Alloc& alloc ); ``` | (18) | (since C++11) | | ``` template< class InputIt, class Alloc > priority_queue( InputIt first, InputIt last, const Compare& compare, Container&& cont, const Alloc& alloc ); ``` | (19) | (since C++11) | Constructs new underlying container of the container adaptor from a variety of data sources. 1) Default constructor. Value-initializes the comparator and the underlying container. 2) Copy-constructs the comparison functor `comp` with the contents of `compare`. Value-initializes the underlying container `c`. 3) Copy-constructs the underlying container `c` with the contents of `cont`. Copy-constructs the comparison functor `comp` with the contents of `compare`. Calls `[std::make\_heap](http://en.cppreference.com/w/cpp/algorithm/make_heap)(c.begin(), c.end(), comp)`. This is also the default constructor. (until C++11) 4) Move-constructs the underlying container `c` with `std::move(cont)`. Copy-constructs the comparison functor `comp` with `compare`. Calls `[std::make\_heap](http://en.cppreference.com/w/cpp/algorithm/make_heap)(c.begin(), c.end(), comp)`. 5) Copy constructor. The underlying container is copy-constructed with `other.c`. The comparison functor is copy-constructed with `other.comp`. (implicitly declared) 6) Move constructor. The underlying container is constructed with `std::move(other.c)`.The comparison functor is constructed with `std::move(other.comp)`. (implicitly declared) 7-9) Iterator-pair constructors. These overloads participate in overload resolution only if `InputIt` satisfies [LegacyInputIterator](../../named_req/inputiterator "cpp/named req/InputIterator"). 7) Constructs `c` as if by `c(first, last)` and `comp` from `compare`. Then calls `[std::make\_heap](http://en.cppreference.com/w/cpp/algorithm/make_heap)(c.begin(), c.end(), comp);`. 8) Copy-constructs `c` from `cont` and `comp` from `compare`. Then calls `c.insert(c.end(), first, last);`, and then calls `[std::make\_heap](http://en.cppreference.com/w/cpp/algorithm/make_heap)(c.begin(), c.end(), comp);`. 9) Move-constructs `c` from `std::move(cont)` and copy-constructs `comp` from `compare`. Then calls `c.insert(c.end(), first, last);`, and then calls `[std::make\_heap](http://en.cppreference.com/w/cpp/algorithm/make_heap)(c.begin(), c.end(), comp);`. 10-15) Allocator-extended constructors. These overloads participate in overload resolution only if `[std::uses\_allocator](http://en.cppreference.com/w/cpp/memory/uses_allocator)<container_type, Alloc>::value` is `true`, that is, if the underlying container is an allocator-aware container (true for all standard library containers). 10) Constructs the underlying container using `alloc` as allocator. Effectively calls `c(alloc)`. `comp` is value-initialized. 11) Constructs the underlying container using `alloc` as allocator. Effectively calls `c(alloc)`. Copy-constructs `comp` from `compare`. 12) Constructs the underlying container with the contents of `cont` and using `alloc` as allocator, as if by `c(cont, alloc)`. Copy-constructs `comp` from `compare`. Then calls `[std::make\_heap](http://en.cppreference.com/w/cpp/algorithm/make_heap)(c.begin(), c.end(), comp)`. 13) Constructs the underlying container with the contents of `cont` using move semantics while using `alloc` as allocator, as if by `c(std::move(cont), alloc)`. Copy-constructs `comp` from `compare`. Then calls `[std::make\_heap](http://en.cppreference.com/w/cpp/algorithm/make_heap)(c.begin(), c.end(), comp)`. 14) Constructs the underlying container with the contents of `other.c` and using `alloc` as allocator. Effectively calls `c(other.c, alloc)`. Copy-constructs `comp` from `other.comp`. 15) Constructs the underlying container with the contents of `other` using move semantics while utilising `alloc` as allocator. Effectively calls `c(std::move(other.c), alloc)`. Move-constructs `comp` from `other.comp`. 16-19) Allocator-extended iterator-pair constructors. Same as (7-9), except that `alloc` is used for constructing the underlying container. These overloads participate in overload resolution only if `[std::uses\_allocator](http://en.cppreference.com/w/cpp/memory/uses_allocator)<container_type, Alloc>::value` is `true` and `InputIt` satisfies [LegacyInputIterator](../../named_req/inputiterator "cpp/named req/InputIterator"). Note that how an implementation checks whether a type satisfies [LegacyInputIterator](../../named_req/inputiterator "cpp/named req/InputIterator") is unspecified, except that integral types are required to be rejected. ### Parameters | | | | | --- | --- | --- | | alloc | - | allocator to use for all memory allocations of the underlying container | | other | - | another container adaptor to be used as source to initialize the underlying container | | cont | - | container to be used as source to initialize the underlying container | | compare | - | the comparison function object to initialize the underlying comparison functor | | first, last | - | range of elements to initialize with | | Type requirements | | -`Alloc` must meet the requirements of [Allocator](../../named_req/allocator "cpp/named req/Allocator"). | | -`Container` must meet the requirements of [Container](../../named_req/container "cpp/named req/Container"). The allocator-extended constructors are only defined if `Container` meets the requirements of [AllocatorAwareContainer](../../named_req/allocatorawarecontainer "cpp/named req/AllocatorAwareContainer") | | -`InputIt` must meet the requirements of [LegacyInputIterator](../../named_req/inputiterator "cpp/named req/InputIterator"). | ### Complexity 1-2) Constant. 3,5) \(\scriptsize \mathcal{O}{(N)}\)O(N) comparisons and \(\scriptsize \mathcal{O}{(N)}\)O(N) calls to the constructor of `value_type`, where \(\scriptsize N\)N is `cont.size()`. 4) \(\scriptsize \mathcal{O}{(N)}\)O(N) comparisons, where \(\scriptsize N\)N is `cont.size()`. 6) Constant. 7,16-17) \(\scriptsize \mathcal{O}{(M)}\)O(M) comparisons, where \(\scriptsize M\)M is `[std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(first, last)`. 8,18) \(\scriptsize \mathcal{O}{(N+M)}\)O(N+M) comparisons and \(\scriptsize \mathcal{O}{(N)}\)O(N) calls to the constructor of `value_type`, where \(\scriptsize N\)N and \(\scriptsize M\)M are `cont.size()` and `[std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(first, last)` respectively. 9) \(\scriptsize \mathcal{O}{(N)}\)O(N) comparisons, where \(\scriptsize N\)N is `cont.size() + [std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(first, last)`. 10-11) Constant. 12) \(\scriptsize \mathcal{O}{(N)}\)O(N) comparisons and \(\scriptsize \mathcal{O}{(N)}\)O(N) calls to the constructor of `value_type`, where \(\scriptsize N\)N is `cont.size()`. 13) \(\scriptsize \mathcal{O}{(N)}\)O(N) comparisons, where \(\scriptsize N\)N is `cont.size()`. 14) Linear in size of `other`. 15) Constant if `Alloc` compares equal to the allocator of `other`. Linear in size of `other` otherwise. 19) \(\scriptsize \mathcal{O}{(N+M)}\)O(N+M) comparisons and possibly present \(\scriptsize \mathcal{O}{(N)}\)O(N) calls to the constructor of `value_type` (present if `Alloc` does not compare equal to the allocator of `other`), where \(\scriptsize N\)N and \(\scriptsize M\)M are `cont.size()` and `[std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(first, last)` respectively. ### Example ``` #include <complex> #include <functional> #include <iostream> #include <queue> #include <vector> int main() { std::priority_queue<int> pq1; pq1.push(5); std::cout << "pq1.size() = " << pq1.size() << '\n'; std::priority_queue<int> pq2 {pq1}; std::cout << "pq2.size() = " << pq2.size() << '\n'; std::vector<int> vec {3, 1, 4, 1, 5}; std::priority_queue<int> pq3 {std::less<int>(), vec}; std::cout << "pq3.size() = " << pq3.size() << '\n'; for (std::cout << "pq3 : "; !pq3.empty(); pq3.pop()) { std::cout << pq3.top() << ' '; } std::cout << '\n'; // Demo With Custom Comparator: using my_value_t = std::complex<double>; using my_container_t = std::vector<my_value_t>; auto my_comp = [](const my_value_t& z1, const my_value_t& z2) { return z2.real() < z1.real(); }; std::priority_queue<my_value_t, my_container_t, decltype(my_comp)> pq4 {my_comp}; using namespace std::complex_literals; pq4.push(5.0 + 1i); pq4.push(3.0 + 2i); pq4.push(7.0 + 3i); for (; !pq4.empty(); pq4.pop()) { const auto& z = pq4.top(); std::cout << "pq4.top() = " << z << '\n'; } } ``` Output: ``` pq1.size() = 1 pq2.size() = 1 pq3.size() = 5 pq3 : 5 4 3 1 1 pq4.top() = (3,2) pq4.top() = (5,1) pq4.top() = (7,3) ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [P0935R0](https://wg21.link/P0935R0) | C++11 | default constructor and constructor (4) were explicit | made implicit | | [LWG 3506](https://cplusplus.github.io/LWG/issue3506) | C++11 | allocator-extended iterator-pair constructors were missing | added | | [LWG 3522](https://cplusplus.github.io/LWG/issue3522) | C++11 | constraints on iterator-pair constructors were missing | added | | [LWG 3529](https://cplusplus.github.io/LWG/issue3529) | C++11 | construction from a pair of iterators called `insert` | constructs the container from them | ### See also | | | | --- | --- | | [operator=](operator= "cpp/container/priority queue/operator=") | assigns values to the container adaptor (public member function) | cpp std::priority_queue<T,Container,Compare>::push std::priority\_queue<T,Container,Compare>::push =============================================== | | | | | --- | --- | --- | | ``` void push( const value_type& value ); ``` | | | | ``` void push( value_type&& value ); ``` | | (since C++11) | Pushes the given element `value` to the priority queue. 1) Effectively calls `c.push\_back(value); [std::push\_heap](http://en.cppreference.com/w/cpp/algorithm/push_heap)(c.begin(), c.end(), comp);` 2) Effectively calls `c.push\_back(std::move(value)); [std::push\_heap](http://en.cppreference.com/w/cpp/algorithm/push_heap)(c.begin(), c.end(), comp);` ### Parameters | | | | | --- | --- | --- | | value | - | the value of the element to push | ### Return value (none). ### Complexity Logarithmic number of comparisons plus the complexity of `Container::push_back`. ### Example ``` #include <queue> #include <iostream> struct Event { int priority{}; char data{' '}; friend bool operator< (Event const& lhs, Event const& rhs) { return lhs.priority < rhs.priority; } friend std::ostream& operator<< (std::ostream& os, Event const& e) { return os << "{ " << e.priority << ", '" << e.data << "' } "; } }; int main() { std::priority_queue<Event> events; std::cout << "Fill the events queue:\n"; for (auto const e: { Event{6,'L'}, {8,'I'}, {9,'S'}, {1,'T'}, {5,'E'}, {3,'N'} }) { std::cout << e << ' '; events.push(e); } std::cout << "\n" "Process events:\n"; for (; !events.empty(); events.pop()) { Event const& e = events.top(); std::cout << e << ' '; } } ``` Output: ``` Fill the events queue: { 6, 'L' } { 8, 'I' } { 9, 'S' } { 1, 'T' } { 5, 'E' } { 3, 'N' } Process events: { 9, 'S' } { 8, 'I' } { 6, 'L' } { 5, 'E' } { 3, 'N' } { 1, 'T' } ``` ### See also | | | | --- | --- | | [emplace](emplace "cpp/container/priority queue/emplace") (C++11) | constructs element in-place and sorts the underlying container (public member function) | | [pop](pop "cpp/container/priority queue/pop") | removes the top element (public member function) |
programming_docs
cpp std::swap(std::priority_queue) std::swap(std::priority\_queue) =============================== | Defined in header `[<queue>](../../header/queue "cpp/header/queue")` | | | | --- | --- | --- | | ``` template< class T, class Container, class Compare > void swap( std::priority_queue<T,Container,Compare>& lhs, std::priority_queue<T,Container,Compare>& rhs ); ``` | | (since C++11) (until C++17) | | ``` template< class T, class Container, class Compare > void swap( std::priority_queue<T,Container,Compare>& lhs, std::priority_queue<T,Container,Compare>& rhs ) noexcept(/* see below */); ``` | | (since C++17) | Specializes the `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` algorithm for `[std::priority\_queue](http://en.cppreference.com/w/cpp/container/priority_queue)`. Swaps the contents of `lhs` and `rhs`. Calls `lhs.swap(rhs)`. | | | | --- | --- | | This overload participates in overload resolution only if `[std::is\_swappable\_v](http://en.cppreference.com/w/cpp/types/is_swappable)<Container>` and `[std::is\_swappable\_v](http://en.cppreference.com/w/cpp/types/is_swappable)<Compare>` are both `true`. | (since C++17) | ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | containers whose contents to swap | ### Return value (none). ### Complexity Same as swapping the underlying container. ### Exceptions | | | | --- | --- | | [`noexcept`](../../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept(noexcept(lhs.swap(rhs)))` | (since C++17) | ### Notes Although the overloads of `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` for container adaptors are introduced in C++11, container adaptors can already be swapped by `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` in C++98. Such calls to `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` usually have linear time complexity, but better complexity may be provided. ### Example ``` #include <algorithm> #include <iostream> #include <queue> int main() { std::priority_queue<int> alice; std::priority_queue<int> bob; auto print = [](const auto & title, const auto &cont) { std::cout << title << " size=" << cont.size(); std::cout << " top=" << cont.top() << '\n'; }; for (int i = 1; i < 4; ++i) alice.push(i); for (int i = 7; i < 11; ++i) bob.push(i); // Print state before swap print("alice:", alice); print("bob :", bob); std::cout << "-- SWAP\n"; std::swap(alice, bob); // Print state after swap print("alice:", alice); print("bob :", bob); } ``` Output: ``` alice: size=3 top=3 bob : size=4 top=10 -- SWAP alice: size=4 top=10 bob : size=3 top=3 ``` ### See also | | | | --- | --- | | [swap](swap "cpp/container/priority queue/swap") (C++11) | swaps the contents (public member function) | cpp std::priority_queue<T,Container,Compare>::operator= std::priority\_queue<T,Container,Compare>::operator= ==================================================== | | | | | --- | --- | --- | | ``` priority_queue& operator=( const priority_queue& other ); ``` | (1) | | | ``` priority_queue& operator=( priority_queue&& other ); ``` | (2) | (since C++11) | Replaces the contents of the container adaptor with those of `other`. 1) Copy assignment operator. Replaces the contents with a copy of the contents of `other`. Effectively calls `c = other.c; comp = other.comp;`. (implicitly declared) 2) Move assignment operator. Replaces the contents with those of `other` using move semantics. Effectively calls `c = std::move(other.c); comp = std::move(other.comp);` (implicitly declared) ### Parameters | | | | | --- | --- | --- | | other | - | another container adaptor to be used as source | ### Return value `*this`. ### Complexity Equivalent to that of `operator=` of the underlying container. ### See also | | | | --- | --- | | [(constructor)](priority_queue "cpp/container/priority queue/priority queue") | constructs the `priority_queue` (public member function) | cpp std::priority_queue<T,Container,Compare>::empty std::priority\_queue<T,Container,Compare>::empty ================================================ | | | | | --- | --- | --- | | ``` bool empty() const; ``` | | (until C++20) | | ``` [[nodiscard]] bool empty() const; ``` | | (since C++20) | Checks if the underlying container has no elements, i.e. whether `c.empty()`. ### Parameters (none). ### Return value `true` if the underlying container is empty, `false` otherwise. ### Complexity Constant. ### Example ``` #include <algorithm> #include <iostream> #include <queue> int main() { std::cout << std::boolalpha; std::priority_queue<int> container; std::cout << "Initially, container.empty(): " << container.empty() << '\n'; container.push(42); std::cout << "After adding elements, container.empty(): " << container.empty() << '\n'; } ``` Output: ``` Initially, container.empty(): true After adding elements, container.empty(): false ``` ### See also | | | | --- | --- | | [size](size "cpp/container/priority queue/size") | returns the number of elements (public member function) | cpp std::unordered_multimap<Key,T,Hash,KeyEqual,Allocator>::contains std::unordered\_multimap<Key,T,Hash,KeyEqual,Allocator>::contains ================================================================= | | | | | --- | --- | --- | | ``` bool contains( const Key& key ) const; ``` | (1) | (since C++20) | | ``` template< class K > bool contains( const K& x ) const; ``` | (2) | (since C++20) | 1) Checks if there is an element with key equivalent to `key` in the container. 2) Checks if there is an element with key that compares *equivalent* to the value `x`. This overload participates in overload resolution only if `Hash::is_transparent` and `KeyEqual::is_transparent` are valid and each denotes a type. This assumes that such `Hash` is callable with both `K` and `Key` type, and that the `KeyEqual` is transparent, which, together, allows calling this function without constructing an instance of `Key`. ### Parameters | | | | | --- | --- | --- | | key | - | key value of the element to search for | | x | - | a value of any type that can be transparently compared with a key | ### Return value `true` if there is such an element, otherwise `false`. ### Complexity Constant on average, worst case linear in the size of the container. ### Example ``` #include <iostream> #include <unordered_map> int main() { std::unordered_multimap<int,char> example = {{1,'a'},{2,'b'}}; for(int x: {2, 5}) { if(example.contains(x)) { std::cout << x << ": Found\n"; } else { std::cout << x << ": Not found\n"; } } } ``` Output: ``` 2: Found 5: Not found ``` ### See also | | | | --- | --- | | [find](find "cpp/container/unordered multimap/find") (C++11) | finds element with specific key (public member function) | | [count](count "cpp/container/unordered multimap/count") (C++11) | returns the number of elements matching specific key (public member function) | | [equal\_range](equal_range "cpp/container/unordered multimap/equal range") (C++11) | returns range of elements matching a specific key (public member function) | cpp std::unordered_multimap<Key,T,Hash,KeyEqual,Allocator>::size std::unordered\_multimap<Key,T,Hash,KeyEqual,Allocator>::size ============================================================= | | | | | --- | --- | --- | | ``` size_type size() const noexcept; ``` | | (since C++11) | Returns the number of elements in the container, i.e. `[std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(begin(), end())`. ### Parameters (none). ### Return value The number of elements in the container. ### Complexity Constant. ### Example The following code uses `size` to display the number of elements in a `[std::unordered\_multimap](../unordered_multimap "cpp/container/unordered multimap")`: ``` #include <unordered_map> #include <iostream> int main() { std::unordered_multimap<int,char> nums {{1, 'a'}, {3, 'b'}, {5, 'c'}, {7, 'd'}}; std::cout << "nums contains " << nums.size() << " elements.\n"; } ``` Output: ``` nums contains 4 elements. ``` ### See also | | | | --- | --- | | [empty](empty "cpp/container/unordered multimap/empty") (C++11) | checks whether the container is empty (public member function) | | [max\_size](max_size "cpp/container/unordered multimap/max size") (C++11) | returns the maximum possible number of elements (public member function) | | [sizessize](../../iterator/size "cpp/iterator/size") (C++17)(C++20) | returns the size of a container or array (function template) | cpp std::unordered_multimap<Key,T,Hash,KeyEqual,Allocator>::bucket_count std::unordered\_multimap<Key,T,Hash,KeyEqual,Allocator>::bucket\_count ====================================================================== | | | | | --- | --- | --- | | ``` size_type bucket_count() const; ``` | | (since C++11) | Returns the number of buckets in the container. ### Parameters (none). ### Return value The number of buckets in the container. ### Complexity Constant. ### See also | | | | --- | --- | | [bucket\_size](bucket_size "cpp/container/unordered multimap/bucket size") (C++11) | returns the number of elements in specific bucket (public member function) | | [max\_bucket\_count](max_bucket_count "cpp/container/unordered multimap/max bucket count") (C++11) | returns the maximum number of buckets (public member function) | cpp deduction guides for std::unordered_multimap deduction guides for `std::unordered_multimap` ============================================== | Defined in header `[<unordered\_map>](../../header/unordered_map "cpp/header/unordered map")` | | | | --- | --- | --- | | ``` template<class InputIt, class Hash = std::hash<iter_key_t<InputIt>>, class Pred = std::equal_to<iter_key_t<InputIt>>, class Alloc = std::allocator<iter_to_alloc_t<InputIt>>> unordered_multimap(InputIt, InputIt, typename /*see below*/::size_type = /*see below*/, Hash = Hash(), Pred = Pred(), Alloc = Alloc()) -> unordered_multimap<iter_key_t<InputIt>, iter_val_t<InputIt>, Hash, Pred, Alloc>; ``` | (1) | (since C++17) | | ``` template<class Key, class T, class Hash = std::hash<Key>, class Pred = std::equal_to<Key>, class Alloc = std::allocator<std::pair<const Key, T>>> unordered_multimap(std::initializer_list<std::pair<Key, T>>, typename /*see below*/::size_type = /*see below*/, Hash = Hash(), Pred = Pred(), Alloc = Alloc()) -> unordered_multimap<Key, T, Hash, Pred, Alloc>; ``` | (2) | (since C++17) | | ``` template<class InputIt, class Alloc> unordered_multimap(InputIt, InputIt, typename /*see below*/::size_type, Alloc) -> unordered_multimap<iter_key_t<InputIt>, iter_val_t<InputIt>, std::hash<iter_key_t<InputIt>>, std::equal_to<iter_key_t<InputIt>>, Alloc>; ``` | (3) | (since C++17) | | ``` template<class InputIt, class Alloc> unordered_multimap(InputIt, InputIt, Alloc) -> unordered_multimap<iter_key_t<InputIt>, iter_val_t<InputIt>, std::hash<iter_key_t<InputIt>>, std::equal_to<iter_key_t<InputIt>>, Alloc>; ``` | (4) | (since C++17) | | ``` template<class InputIt, class Hash, class Alloc> unordered_multimap(InputIt, InputIt, typename /*see below*/::size_type, Hash, Alloc) -> unordered_multimap<iter_key_t<InputIt>, iter_val_t<InputIt>, Hash, std::equal_to<iter_key_t<InputIt>>, Alloc>; ``` | (5) | (since C++17) | | ``` template<class Key, class T, typename Alloc> unordered_multimap(std::initializer_list<std::pair<Key, T>>, typename /*see below*/::size_type, Alloc) -> unordered_multimap<Key, T, std::hash<Key>, std::equal_to<Key>, Alloc>; ``` | (6) | (since C++17) | | ``` template<class Key, class T, typename Alloc> unordered_multimap(std::initializer_list<std::pair<Key, T>>, Alloc) -> unordered_multimap<Key, T, std::hash<Key>, std::equal_to<Key>, Alloc>; ``` | (7) | (since C++17) | | ``` template<class Key, class T, class Hash, class Alloc> unordered_multimap(std::initializer_list<std::pair<Key, T>>, typename /*see below*/::size_type, Hash, Alloc) -> unordered_multimap<Key, T, Hash, std::equal_to<Key>, Alloc>; ``` | (8) | (since C++17) | where the type aliases `iter_key_t`, `iter_val_t`, `iter_to_alloc_t` are defined as if as follows. | | | | | --- | --- | --- | | ``` template< class InputIt > using iter_key_t = std::remove_const_t< typename std::iterator_traits<InputIt>::value_type::first_type>; ``` | | (exposition only) | | ``` template< class InputIt > using iter_val_t = typename std::iterator_traits<InputIt>::value_type::second_type; ``` | | (exposition only) | | ``` template< class InputIt > using iter_to_alloc_t = std::pair< std::add_const_t<typename std::iterator_traits<InputIt>::value_type::first_type>, typename std::iterator_traits<InputIt>::value_type::second_type > ``` | | (exposition only) | These [deduction guide](../../language/class_template_argument_deduction "cpp/language/class template argument deduction") are provided for unordered\_multimap to allow deduction from an iterator range (overloads (1,3-5)) and `[std::initializer\_list](../../utility/initializer_list "cpp/utility/initializer list")` (overloads (2,6-8)). These overloads participate in overload resolution only if `InputIt` satisfies [LegacyInputIterator](../../named_req/inputiterator "cpp/named req/InputIterator"), `Alloc` satisfies [Allocator](../../named_req/allocator "cpp/named req/Allocator"), neither `Hash` nor `Pred` satisfy [Allocator](../../named_req/allocator "cpp/named req/Allocator"), and `Hash` is not an integral type. Note: the extent to which the library determines that a type does not satisfy [LegacyInputIterator](../../named_req/inputiterator "cpp/named req/InputIterator") is unspecified, except that as a minimum integral types do not qualify as input iterators. Likewise, the extent to which it determines that a type does not satisfy [Allocator](../../named_req/allocator "cpp/named req/Allocator") is unspecified, except that as a minimum the member type `Alloc::value_type` must exist and the expression `[std::declval](http://en.cppreference.com/w/cpp/utility/declval)<Alloc&>().allocate([std::size\_t](http://en.cppreference.com/w/cpp/types/size_t){})` must be well-formed when treated as an unevaluated operand. The `size_type` parameter type in these guides in an refers to the `size_type` member type of the type deduced by the deduction guide. ### Example ``` #include <unordered_map> int main() { // std::unordered_multimap m1 = {{"foo", 1}, {"bar", 2}}; // Error: braced-init-list has no type // cannot deduce pair<Key, T> from // {"foo", 1} or {"bar", 2} std::unordered_multimap m1 = {std::pair{"foo", 2}, {"bar", 3}}; // guide #2 std::unordered_multimap m2(m1.begin(), m1.end()); // guide #1 } ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 3025](https://cplusplus.github.io/LWG/issue3025) | C++17 | initializer-list guides take `[std::pair](http://en.cppreference.com/w/cpp/utility/pair)<const Key, T>` | use `[std::pair](http://en.cppreference.com/w/cpp/utility/pair)<Key, T>` | cpp std::unordered_multimap<Key,T,Hash,KeyEqual,Allocator>::emplace std::unordered\_multimap<Key,T,Hash,KeyEqual,Allocator>::emplace ================================================================ | | | | | --- | --- | --- | | ``` template< class... Args > iterator emplace( Args&&... args ); ``` | | (since C++11) | Inserts a new element into the container constructed in-place with the given `args` . Careful use of `emplace` allows the new element to be constructed while avoiding unnecessary copy or move operations. The constructor of the new element (i.e. `[std::pair](http://en.cppreference.com/w/cpp/utility/pair)<const Key, T>`) is called with exactly the same arguments as supplied to `emplace`, forwarded via `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Args>(args)...`. If rehashing occurs due to the insertion, all iterators are invalidated. Otherwise iterators are not affected. References are not invalidated. Rehashing occurs only if the new number of elements is greater than `max_load_factor()*bucket_count()`. ### Parameters | | | | | --- | --- | --- | | args | - | arguments to forward to the constructor of the element | ### Return value Returns an iterator to the inserted element. ### Exceptions If an exception is thrown by any operation, this function has no effect (strong exception guarantee). ### Complexity Amortized constant on average, worst case linear in the size of the container. ### Example ``` #include <iostream> #include <utility> #include <string> #include <unordered_map> int main() { std::unordered_multimap<std::string, std::string> m; // uses pair's move constructor m.emplace(std::make_pair(std::string("a"), std::string("a"))); // uses pair's converting move constructor m.emplace(std::make_pair("b", "abcd")); // uses pair's template constructor m.emplace("d", "ddd"); // uses pair's piecewise constructor m.emplace(std::piecewise_construct, std::forward_as_tuple("c"), std::forward_as_tuple(10, 'c')); for (const auto &p : m) { std::cout << p.first << " => " << p.second << '\n'; } } ``` Possible output: ``` a => a b => abcd c => cccccccccc d => ddd ``` ### See also | | | | --- | --- | | [emplace\_hint](emplace_hint "cpp/container/unordered multimap/emplace hint") (C++11) | constructs elements in-place using a hint (public member function) | | [insert](insert "cpp/container/unordered multimap/insert") (C++11) | inserts elements or nodes (since C++17) (public member function) | cpp std::unordered_multimap<Key,T,Hash,KeyEqual,Allocator>::insert std::unordered\_multimap<Key,T,Hash,KeyEqual,Allocator>::insert =============================================================== | Defined in header `[<unordered\_map>](../../header/unordered_map "cpp/header/unordered map")` | | | | --- | --- | --- | | ``` iterator insert( const value_type& value ); ``` | (1) | (since C++11) | | ``` iterator insert( value_type&& value ); ``` | (1) | (since C++17) | | ``` template< class P > iterator insert( P&& value ); ``` | (2) | (since C++11) | | ``` iterator insert( const_iterator hint, const value_type& value ); ``` | (3) | (since C++11) | | ``` iterator insert( const_iterator hint, value_type&& value ); ``` | (3) | (since C++17) | | ``` template< class P > iterator insert( const_iterator hint, P&& value ); ``` | (4) | (since C++11) | | ``` template< class InputIt > void insert( InputIt first, InputIt last ); ``` | (5) | (since C++11) | | ``` void insert( std::initializer_list<value_type> ilist ); ``` | (6) | (since C++11) | | ``` iterator insert( node_type&& nh ); ``` | (7) | (since C++17) | | ``` iterator insert( const_iterator hint, node_type&& nh ); ``` | (8) | (since C++17) | Inserts element(s) into the container. 1-2) inserts `value`. The overload (2) is equivalent to `emplace([std::forward](http://en.cppreference.com/w/cpp/utility/forward)<P>(value))` and only participates in overload resolution if `[std::is\_constructible](http://en.cppreference.com/w/cpp/types/is_constructible)<value_type, P&&>::value == true`. 3-4) inserts `value`, using `hint` as a non-binding suggestion to where the search should start. The overload (4) is equivalent to `emplace_hint(hint, [std::forward](http://en.cppreference.com/w/cpp/utility/forward)<P>(value))` and only participates in overload resolution if `[std::is\_constructible](http://en.cppreference.com/w/cpp/types/is_constructible)<value_type, P&&>::value == true`. 5) inserts elements from range `[first, last)`. 6) inserts elements from initializer list `ilist`. 7) If `nh` is an empty [node handle](../node_handle "cpp/container/node handle"), does nothing. Otherwise, inserts the element owned by `nh` into the container and returns an iterator pointing at the inserted element.. The behavior is undefined if `nh` is not empty and `get_allocator() != nh.get_allocator()`. 8) If `nh` is an empty [node handle](../node_handle "cpp/container/node handle"), does nothing and returns the end iterator. Otherwise, inserts the element owned by `nh` into the container, and returns the iterator pointing to the element with key equivalent to `nh.key()` The element is inserted as close as possible to `hint`. The behavior is undefined if `nh` is not empty and `get_allocator() != nh.get_allocator()`. If rehashing occurs due to the insertion, all iterators are invalidated. Otherwise iterators are not affected. References are not invalidated. Rehashing occurs only if the new number of elements is greater than `max_load_factor()*bucket_count()`. If the insertion is successful, pointers and references to the element obtained while it is held in the node handle are invalidated, and pointers and references obtained to that element before it was extracted become valid. (since C++17). ### Parameters | | | | | --- | --- | --- | | hint | - | iterator, used as a suggestion as to where to insert the content | | value | - | element value to insert | | first, last | - | range of elements to insert | | ilist | - | initializer list to insert the values from | | nh | - | a compatible [node handle](../node_handle "cpp/container/node handle") | | Type requirements | | -`InputIt` must meet the requirements of [LegacyInputIterator](../../named_req/inputiterator "cpp/named req/InputIterator"). | ### Return value 1-4) Returns an iterator to the inserted element. 5-6) (none) 7,8) End iterator if `nh` was empty, iterator pointing to the inserted element otherwise. ### Exceptions 1-4) If an exception is thrown by any operation, the insertion has no effect. ### Complexity 1-4) Average case: `O(1)`, worst case `O(size())` 5-6) Average case: `O(N)`, where N is the number of elements to insert. Worse case: `O(N*size()+N)` 7-8) Average case: `O(1)`, worst case `O(size())` ### Example ### See also | | | | --- | --- | | [emplace](emplace "cpp/container/unordered multimap/emplace") (C++11) | constructs element in-place (public member function) | | [emplace\_hint](emplace_hint "cpp/container/unordered multimap/emplace hint") (C++11) | constructs elements in-place using a hint (public member function) | | [inserter](../../iterator/inserter "cpp/iterator/inserter") | creates a `[std::insert\_iterator](../../iterator/insert_iterator "cpp/iterator/insert iterator")` of type inferred from the argument (function template) |
programming_docs
cpp std::unordered_multimap<Key,T,Hash,KeyEqual,Allocator>::get_allocator std::unordered\_multimap<Key,T,Hash,KeyEqual,Allocator>::get\_allocator ======================================================================= | | | | | --- | --- | --- | | ``` allocator_type get_allocator() const noexcept; ``` | | (since C++11) | Returns the allocator associated with the container. ### Parameters (none). ### Return value The associated allocator. ### Complexity Constant. cpp std::unordered_multimap<Key,T,Hash,KeyEqual,Allocator>::merge std::unordered\_multimap<Key,T,Hash,KeyEqual,Allocator>::merge ============================================================== | | | | | --- | --- | --- | | ``` template<class H2, class P2> void merge( std::unordered_map<Key, T, H2, P2, Allocator>& source ); ``` | (1) | (since C++17) | | ``` template<class H2, class P2> void merge( std::unordered_map<Key, T, H2, P2, Allocator>&& source ); ``` | (2) | (since C++17) | | ``` template<class H2, class P2> void merge( std::unordered_multimap<Key, T, H2, P2, Allocator>& source ); ``` | (3) | (since C++17) | | ``` template<class H2, class P2> void merge( std::unordered_multimap<Key, T, H2, P2, Allocator>&& source ); ``` | (4) | (since C++17) | Attempts to extract ("splice") each element in `source` and insert it into `*this` using the hash function and key equality predicate of `*this`. No elements are copied or moved, only the internal pointers of the container nodes are repointed. All pointers and references to the transferred elements remain valid, but now refer into `*this`, not into `source`. Iterators referring to the transferred elements and all iterators referring to `*this` are invalidated. The behavior is undefined if `get_allocator() != source.get_allocator()`. ### Parameters | | | | | --- | --- | --- | | source | - | compatible container to transfer the nodes from | ### Return value (none). ### Complexity Average case O(N), worst case O(N\*size()+N), where N is `source.size()`. ### Example ``` #include <iostream> #include <string> #include <utility> #include <unordered_map> // print out a std::pair template <class Os, class U, class V> Os& operator<<(Os& os, const std::pair<U,V>& p) { return os << '{' << p.first << ", " << p.second << '}'; } // print out an associative container template <class Os, class K, class V> Os& operator<<(Os& os, const std::unordered_multimap<K, V>& v) { os << '[' << v.size() << "] { "; bool o{}; for (const auto& e : v) os << (o ? ", " : (o = 1, "")) << e; return os << " }\n"; } int main() { std::unordered_multimap<std::string, int> p{ {"C", 3}, {"B", 2}, {"A", 1}, {"A", 0} }, q{ {"E", 6}, {"E", 7}, {"D", 5}, {"A", 4} }; std::cout << "p: " << p << "q: " << q; p.merge(q); std::cout << "p.merge(q);\n" << "p: " << p << "q: " << q; } ``` Possible output: ``` p: [4] { {A, 1}, {A, 0}, {B, 2}, {C, 3} } q: [4] { {A, 4}, {D, 5}, {E, 6}, {E, 7} } p.merge(q); p: [8] { {E, 6}, {E, 7}, {C, 3}, {A, 1}, {A, 0}, {A, 4}, {D, 5}, {B, 2} } q: [0] { } ``` ### See also | | | | --- | --- | | [extract](extract "cpp/container/unordered multimap/extract") (C++17) | extracts nodes from the container (public member function) | | [insert](insert "cpp/container/unordered multimap/insert") (C++11) | inserts elements or nodes (since C++17) (public member function) | cpp std::unordered_multimap<Key,T,Hash,KeyEqual,Allocator>::extract std::unordered\_multimap<Key,T,Hash,KeyEqual,Allocator>::extract ================================================================ | | | | | --- | --- | --- | | ``` node_type extract( const_iterator position ); ``` | (1) | (since C++17) | | ``` node_type extract( const Key& k ); ``` | (2) | (since C++17) | | ``` template< class K > node_type extract( K&& x ); ``` | (3) | (since C++23) | 1) Unlinks the node that contains the element pointed to by `position` and returns a [node handle](../node_handle "cpp/container/node handle") that owns it. 2) If the container has an element with key equivalent to `k`, unlinks the node that contains the first such element from the container and returns a [node handle](../node_handle "cpp/container/node handle") that owns it. Otherwise, returns an empty node handle. 3) Same as (2). This overload participates in overload resolution only if `Hash::is_transparent` and `KeyEqual::is_transparent` are valid and each denotes a type, and neither `iterator` nor `const_iterator` is implicitly convertible from `K`. This assumes that such `Hash` is callable with both `K` and `Key` type, and that the `KeyEqual` is transparent, which, together, allows calling this function without constructing an instance of `Key`. In either case, no elements are copied or moved, only the internal pointers of the container nodes are repointed . Extracting a node invalidates only the iterators to the extracted element, and preserves the relative order of the elements that are not erased. Pointers and references to the extracted element remain valid, but cannot be used while element is owned by a node handle: they become usable if the element is inserted into a container. ### Parameters | | | | | --- | --- | --- | | position | - | a valid iterator into this container | | k | - | a key to identify the node to be extracted | | x | - | a value of any type that can be transparently compared with a key identifying the node to be extracted | ### Return value A [node handle](../node_handle "cpp/container/node handle") that owns the extracted element, or empty node handle in case the element is not found in (2,3). ### Exceptions 1) Throws nothing. 2,3) Any exceptions thrown by the `Hash` and `KeyEqual` object. ### Complexity 1,2,3) Average case O(1), worst case O(`a.size()`). ### Notes extract is the only way to change a key of a map element without reallocation: ``` std::map<int, std::string> m{{1, "mango"}, {2, "papaya"}, {3, "guava"}}; auto nh = m.extract(2); nh.key() = 4; m.insert(std::move(nh)); // m == {{1, "mango"}, {3, "guava"}, {4, "papaya"}} ``` | [Feature-test](../../utility/feature_test "cpp/utility/feature test") macro | Comment | | --- | --- | | [`__cpp_lib_associative_heterogeneous_erasure`](../../feature_test#Library_features "cpp/feature test") | for overload (3) | ### Example ``` #include <algorithm> #include <iostream> #include <string_view> #include <unordered_map> void print(std::string_view comment, const auto& data) { std::cout << comment; for (auto [k, v] : data) std::cout << ' ' << k << '(' << v << ')'; std::cout << '\n'; } int main() { std::unordered_multimap<int, char> cont{{1, 'a'}, {2, 'b'}, {3, 'c'}}; print("Start:", cont); // Extract node handle and change key auto nh = cont.extract(1); nh.key() = 4; print("After extract and before insert:", cont); // Insert node handle back cont.insert(std::move(nh)); print("End:", cont); } ``` Possible output: ``` Start: 1(a) 2(b) 3(c) After extract and before insert: 2(b) 3(c) End: 2(b) 3(c) 4(a) ``` ### See also | | | | --- | --- | | [merge](merge "cpp/container/unordered multimap/merge") (C++17) | splices nodes from another container (public member function) | | [insert](insert "cpp/container/unordered multimap/insert") (C++11) | inserts elements or nodes (since C++17) (public member function) | | [erase](erase "cpp/container/unordered multimap/erase") (C++11) | erases elements (public member function) | cpp std::unordered_multimap<Key,T,Hash,KeyEqual,Allocator>::max_load_factor std::unordered\_multimap<Key,T,Hash,KeyEqual,Allocator>::max\_load\_factor ========================================================================== | | | | | --- | --- | --- | | ``` float max_load_factor() const; ``` | (1) | (since C++11) | | ``` void max_load_factor( float ml ); ``` | (2) | (since C++11) | Manages the maximum load factor (number of elements per bucket). The container automatically increases the number of buckets if the load factor exceeds this threshold. 1) Returns current maximum load factor. 2) Sets the maximum load factor to `ml`. ### Parameters | | | | | --- | --- | --- | | ml | - | new maximum load factor setting | ### Return value 1) current maximum load factor. 2) none. ### Complexity Constant. ### See also | | | | --- | --- | | [load\_factor](load_factor "cpp/container/unordered multimap/load factor") (C++11) | returns average number of elements per bucket (public member function) | cpp std::unordered_multimap<Key,T,Hash,KeyEqual,Allocator>::emplace_hint std::unordered\_multimap<Key,T,Hash,KeyEqual,Allocator>::emplace\_hint ====================================================================== | | | | | --- | --- | --- | | ``` template <class... Args> iterator emplace_hint( const_iterator hint, Args&&... args ); ``` | | (since C++11) | Inserts a new element to the container, using `hint` as a suggestion where the element should go. The element is constructed in-place, i.e. no copy or move operations are performed. The constructor of the element type (`value_type`, that is, `[std::pair](http://en.cppreference.com/w/cpp/utility/pair)<const Key, T>`) is called with exactly the same arguments as supplied to the function, forwarded with `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Args>(args)...`. If rehashing occurs due to the insertion, all iterators are invalidated. Otherwise iterators are not affected. References are not invalidated. Rehashing occurs only if the new number of elements is greater than `max_load_factor()*bucket_count()`. ### Parameters | | | | | --- | --- | --- | | hint | - | iterator, used as a suggestion as to where to insert the new element | | args | - | arguments to forward to the constructor of the element | ### Return value Returns an iterator to the newly inserted element. ### Exceptions If an exception is thrown by any operation, this function has no effect (strong exception guarantee). ### Complexity Amortized constant on average, worst case linear in the size of the container. ### See also | | | | --- | --- | | [emplace](emplace "cpp/container/unordered multimap/emplace") (C++11) | constructs element in-place (public member function) | | [insert](insert "cpp/container/unordered multimap/insert") (C++11) | inserts elements or nodes (since C++17) (public member function) | cpp std::unordered_multimap<Key,T,Hash,KeyEqual,Allocator>::hash_function std::unordered\_multimap<Key,T,Hash,KeyEqual,Allocator>::hash\_function ======================================================================= | | | | | --- | --- | --- | | ``` hasher hash_function() const; ``` | | (since C++11) | Returns the function that hashes the keys. ### Parameters (none). ### Return value The hash function. ### Complexity Constant. ### See also | | | | --- | --- | | [key\_eq](key_eq "cpp/container/unordered multimap/key eq") (C++11) | returns the function used to compare keys for equality (public member function) | cpp std::unordered_multimap<Key,T,Hash,KeyEqual,Allocator>::~unordered_multimap std::unordered\_multimap<Key,T,Hash,KeyEqual,Allocator>::~unordered\_multimap ============================================================================= | | | | | --- | --- | --- | | ``` ~unordered_multimap(); ``` | | (since C++11) | Destructs the `unordered_multimap`. The destructors of the elements are called and the used storage is deallocated. Note, that if the elements are pointers, the pointed-to objects are not destroyed. ### Complexity Linear in the size of the `unordered_multimap`. cpp std::unordered_multimap<Key,T,Hash,KeyEqual,Allocator>::swap std::unordered\_multimap<Key,T,Hash,KeyEqual,Allocator>::swap ============================================================= | | | | | --- | --- | --- | | ``` void swap( unordered_multimap& other ); ``` | | (since C++11) (until C++17) | | ``` void swap( unordered_multimap& other ) noexcept(/* see below */); ``` | | (since C++17) | Exchanges the contents of the container with those of `other`. Does not invoke any move, copy, or swap operations on individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated. The `Hash` and `KeyEqual` objects must be [Swappable](../../named_req/swappable "cpp/named req/Swappable"), and they are exchanged using unqualified calls to non-member `swap`. | | | | --- | --- | | If `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<allocator_type>::propagate\_on\_container\_swap::value` is true, then the allocators are exchanged using an unqualified call to non-member `swap`. Otherwise, they are not swapped (and if `get_allocator() != other.get_allocator()`, the behavior is undefined). | (since C++11) | ### Parameters | | | | | --- | --- | --- | | other | - | container to exchange the contents with | ### Return value (none). ### Exceptions | | | | --- | --- | | Any exception thrown by the swap of the `Hash` or `KeyEqual` objects. | (until C++17) | | [`noexcept`](../../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept([std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<Allocator>::is\_always\_equal::value && [std::is\_nothrow\_swappable](http://en.cppreference.com/w/cpp/types/is_swappable)<Hash>::value. && [std::is\_nothrow\_swappable](http://en.cppreference.com/w/cpp/types/is_swappable)<key_equal>::value)` | (since C++17) | ### Complexity Constant. ### Example ``` #include <iostream> #include <string> #include <utility> #include <unordered_map> // print out a std::pair template <class Os, class U, class V> Os& operator<<(Os& os, const std::pair<U, V>& p) { return os << p.first << ":" << p.second; } // print out a container template <class Os, class Co> Os& operator<<(Os& os, const Co& co) { os << "{"; for (auto const& i : co) { os << ' ' << i; } return os << " }\n"; } int main() { std::unordered_multimap<std::string, std::string> m1 { {"γ", "gamma"}, {"β", "beta"}, {"α", "alpha"}, {"γ", "gamma"}, }, m2 { {"ε", "epsilon"}, {"δ", "delta"}, {"ε", "epsilon"} }; const auto& ref = *(m1.begin()); const auto iter = std::next(m1.cbegin()); std::cout << "──────── before swap ────────\n" << "m1: " << m1 << "m2: " << m2 << "ref: " << ref << "\niter: " << *iter << '\n'; m1.swap(m2); std::cout << "──────── after swap ────────\n" << "m1: " << m1 << "m2: " << m2 << "ref: " << ref << "\niter: " << *iter << '\n'; // Note that every iterator referring to an element in one container before // the swap refers to the same element in the other container after the swap. // Same is true for references. } ``` Possible output: ``` ──────── before swap ──────── m1: { α:alpha β:beta γ:gamma γ:gamma } m2: { δ:delta ε:epsilon ε:epsilon } ref: α:alpha iter: β:beta ──────── after swap ──────── m1: { δ:delta ε:epsilon ε:epsilon } m2: { α:alpha β:beta γ:gamma γ:gamma } ref: α:alpha iter: β:beta ``` ### See also | | | | --- | --- | | [std::swap(std::unordered\_multimap)](swap2 "cpp/container/unordered multimap/swap2") (C++11) | specializes the `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | cpp std::unordered_multimap<Key,T,Hash,KeyEqual,Allocator>::max_size std::unordered\_multimap<Key,T,Hash,KeyEqual,Allocator>::max\_size ================================================================== | | | | | --- | --- | --- | | ``` size_type max_size() const noexcept; ``` | | (since C++11) | Returns the maximum number of elements the container is able to hold due to system or library implementation limitations, i.e. `[std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(begin(), end())` for the largest container. ### Parameters (none). ### Return value Maximum number of elements. ### Complexity Constant. ### Notes This value typically reflects the theoretical limit on the size of the container, at most `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<difference_type>::max()`. At runtime, the size of the container may be limited to a value smaller than `max_size()` by the amount of RAM available. ### Example ``` #include <iostream> #include <locale> #include <unordered_map> int main() { std::unordered_multimap<char, char> q; std::cout.imbue(std::locale("en_US.UTF-8")); std::cout << "Maximum size of a std::unordered_multimap is " << q.max_size() << '\n'; } ``` Possible output: ``` Maximum size of a std::unordered_multimap is 768,614,336,404,564,650 ``` ### See also | | | | --- | --- | | [size](size "cpp/container/unordered multimap/size") (C++11) | returns the number of elements (public member function) | cpp std::unordered_multimap<Key,T,Hash,KeyEqual,Allocator>::count std::unordered\_multimap<Key,T,Hash,KeyEqual,Allocator>::count ============================================================== | | | | | --- | --- | --- | | ``` size_type count( const Key& key ) const; ``` | (1) | (since C++11) | | ``` template< class K > size_type count( const K& x ) const; ``` | (2) | (since C++20) | 1) Returns the number of elements with key that compares equal to the specified argument `key`. 2) Returns the number of elements with key that compares equivalent to the specified argument `x`. This overload participates in overload resolution only if `Hash::is_transparent` and `KeyEqual::is_transparent` are valid and each denotes a type. This assumes that such `Hash` is callable with both `K` and `Key` type, and that the `KeyEqual` is transparent, which, together, allows calling this function without constructing an instance of `Key`. ### Parameters | | | | | --- | --- | --- | | key | - | key value of the elements to count | | x | - | a value of any type that can be transparently compared with a key | ### Return value 1) Number of elements with key `key`. 2) Number of elements with key that compares equivalent to `x`. ### Complexity linear in the number of elements with key `key` on average, worst case linear in the size of the container. ### Notes | [Feature-test](../../utility/feature_test "cpp/utility/feature test") macro | Comment | | --- | --- | | [`__cpp_lib_generic_unordered_lookup`](../../feature_test#Library_features "cpp/feature test") | for overload (2) | ### Example ``` #include <string> #include <iostream> #include <unordered_map> int main() { std::unordered_multimap<int, std::string> dict = { {1, "one"}, {6, "six"}, {3, "three"} }; dict.insert({4, "four"}); dict.insert({5, "five"}); dict.insert({6, "six"}); std::cout << "dict: { "; for (auto const& [key, value] : dict) { std::cout << "[" << key << "]=" << value << " "; } std::cout << "}\n\n"; for (int i{1}; i != 8; ++i) { std::cout << "dict.count(" << i << ") = " << dict.count(i) << '\n'; } } ``` Possible output: ``` dict: { [5]=five [4]=four [1]=one [6]=six [6]=six [3]=three } dict.count(1) = 1 dict.count(2) = 0 dict.count(3) = 1 dict.count(4) = 1 dict.count(5) = 1 dict.count(6) = 2 dict.count(7) = 0 ``` ### See also | | | | --- | --- | | [find](find "cpp/container/unordered multimap/find") (C++11) | finds element with specific key (public member function) | | [contains](contains "cpp/container/unordered multimap/contains") (C++20) | checks if the container contains element with specific key (public member function) | | [equal\_range](equal_range "cpp/container/unordered multimap/equal range") (C++11) | returns range of elements matching a specific key (public member function) |
programming_docs
cpp std::unordered_multimap<Key,T,Hash,KeyEqual,Allocator>::unordered_multimap std::unordered\_multimap<Key,T,Hash,KeyEqual,Allocator>::unordered\_multimap ============================================================================ | | | | | --- | --- | --- | | ``` unordered_multimap() : unordered_multimap( size_type(/*implementation-defined*/) ) {} explicit unordered_multimap( size_type bucket_count, const Hash& hash = Hash(), const key_equal& equal = key_equal(), const Allocator& alloc = Allocator() ); ``` | (1) | (since C++11) | | ``` unordered_multimap( size_type bucket_count, const Allocator& alloc ) : unordered_multimap(bucket_count, Hash(), key_equal(), alloc) {} unordered_multimap( size_type bucket_count, const Hash& hash, const Allocator& alloc ) : unordered_multimap(bucket_count, hash, key_equal(), alloc) {} ``` | (1) | (since C++14) | | ``` explicit unordered_multimap( const Allocator& alloc ); ``` | (1) | (since C++11) | | ``` template< class InputIt > unordered_multimap( InputIt first, InputIt last, size_type bucket_count = /*implementation-defined*/, const Hash& hash = Hash(), const key_equal& equal = key_equal(), const Allocator& alloc = Allocator() ); ``` | (2) | (since C++11) | | ``` template< class InputIt > unordered_multimap( InputIt first, InputIt last, size_type bucket_count, const Allocator& alloc ) : unordered_multimap(first, last, bucket_count, Hash(), key_equal(), alloc) {} ``` | (2) | (since C++14) | | ``` template< class InputIt > unordered_multimap( InputIt first, InputIt last, size_type bucket_count, const Hash& hash, const Allocator& alloc ) : unordered_multimap(first, last, bucket_count, hash, key_equal(), alloc) {} ``` | (2) | (since C++14) | | ``` unordered_multimap( const unordered_multimap& other ); ``` | (3) | (since C++11) | | ``` unordered_multimap( const unordered_multimap& other, const Allocator& alloc ); ``` | (3) | (since C++11) | | ``` unordered_multimap( unordered_multimap&& other ); ``` | (4) | (since C++11) | | ``` unordered_multimap( unordered_multimap&& other, const Allocator& alloc ); ``` | (4) | (since C++11) | | ``` unordered_multimap( std::initializer_list<value_type> init, size_type bucket_count = /*implementation-defined*/, const Hash& hash = Hash(), const key_equal& equal = key_equal(), const Allocator& alloc = Allocator() ); ``` | (5) | (since C++11) | | ``` unordered_multimap( std::initializer_list<value_type> init, size_type bucket_count, const Allocator& alloc ) : unordered_multimap(init, bucket_count, Hash(), key_equal(), alloc) {} ``` | (5) | (since C++14) | | ``` unordered_multimap( std::initializer_list<value_type> init, size_type bucket_count, const Hash& hash, const Allocator& alloc ) : unordered_multimap(init, bucket_count, hash, key_equal(), alloc) {} ``` | (5) | (since C++14) | Constructs new container from a variety of data sources. Optionally uses user supplied `bucket_count` as a minimal number of buckets to create, `hash` as the hash function, `equal` as the function to compare keys and `alloc` as the allocator. 1) Constructs empty container. Sets `[max\_load\_factor()](max_load_factor "cpp/container/unordered multimap/max load factor")` to 1.0. For the default constructor, the number of buckets is implementation-defined. 2) constructs the container with the contents of the range `[first, last)`. Sets `[max\_load\_factor()](max_load_factor "cpp/container/unordered multimap/max load factor")` to 1.0. 3) copy constructor. Constructs the container with the copy of the contents of `other`, copies the load factor, the predicate, and the hash function as well. If `alloc` is not provided, allocator is obtained by calling `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<allocator_type>::select\_on\_container\_copy\_construction(other.get\_allocator())`. | | | | --- | --- | | The template parameter `Allocator` is only deduced from the first argument while used in [class template argument deduction](../../language/class_template_argument_deduction "cpp/language/class template argument deduction"). | (since C++23) | 4) move constructor. Constructs the container with the contents of `other` using move semantics. If `alloc` is not provided, allocator is obtained by move-construction from the allocator belonging to `other`. | | | | --- | --- | | The template parameter `Allocator` is only deduced from the first argument while used in [class template argument deduction](../../language/class_template_argument_deduction "cpp/language/class template argument deduction"). | (since C++23) | 5) constructs the container with the contents of the initializer list `init`, same as `unordered_multimap(init.begin(), init.end())`. ### Parameters | | | | | --- | --- | --- | | alloc | - | allocator to use for all memory allocations of this container | | bucket\_count | - | minimal number of buckets to use on initialization. If it is not specified, implementation-defined default value is used | | hash | - | hash function to use | | equal | - | comparison function to use for all key comparisons of this container | | first, last | - | the range to copy the elements from | | other | - | another container to be used as source to initialize the elements of the container with | | init | - | initializer list to initialize the elements of the container with | | Type requirements | | -`InputIt` must meet the requirements of [LegacyInputIterator](../../named_req/inputiterator "cpp/named req/InputIterator"). | ### Complexity 1) constant 2) average case linear worst case quadratic in distance between `first` and `last` 3) linear in size of `other` 4) constant. If `alloc` is given and `alloc != other.get_allocator()`, then linear. 5) average case linear worst case quadratic in size of `init` ### Exceptions Calls to `Allocator::allocate` may throw. ### Notes After container move construction (overload (4)), references, pointers, and iterators (other than the end iterator) to `other` remain valid, but refer to elements that are now in `*this`. The current standard makes this guarantee via the blanket statement in [[container.requirements.general]/12](https://eel.is/c++draft/container.requirements.general#12), and a more direct guarantee is under consideration via [LWG 2321](https://cplusplus.github.io/LWG/issue2321). Although not formally required until C++23, some implementations has already put the template parameter `Allocator` into [non-deduced contexts](../../language/template_argument_deduction#Non-deduced_contexts "cpp/language/template argument deduction") in earlier modes. ### Example ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 2193](https://cplusplus.github.io/LWG/issue2193) | C++11 | the default constructor is explicit | made non-explicit | ### See also | | | | --- | --- | | [operator=](operator= "cpp/container/unordered multimap/operator=") (C++11) | assigns values to the container (public member function) | cpp std::unordered_multimap<Key,T,Hash,KeyEqual,Allocator>::bucket_size std::unordered\_multimap<Key,T,Hash,KeyEqual,Allocator>::bucket\_size ===================================================================== | | | | | --- | --- | --- | | ``` size_type bucket_size( size_type n ) const; ``` | | (since C++11) | Returns the number of elements in the bucket with index `n`. ### Parameters | | | | | --- | --- | --- | | n | - | the index of the bucket to examine | ### Return value The number of elements in the bucket `n`. ### Complexity Linear in the size of the bucket `n`. ### See also | | | | --- | --- | | [bucket\_count](bucket_count "cpp/container/unordered multimap/bucket count") (C++11) | returns the number of buckets (public member function) | cpp std::unordered_multimap<Key,T,Hash,KeyEqual,Allocator>::max_bucket_count std::unordered\_multimap<Key,T,Hash,KeyEqual,Allocator>::max\_bucket\_count =========================================================================== | | | | | --- | --- | --- | | ``` size_type max_bucket_count() const; ``` | | (since C++11) | Returns the maximum number of buckets the container is able to hold due to system or library implementation limitations. ### Parameters (none). ### Return value Maximum number of buckets. ### Complexity Constant. ### Example ``` #include <iostream> #include <unordered_map> int main() { struct Ha { std::size_t operator()(long x) const { return std::hash<long>{}(x); }; }; auto c1 = std::unordered_multimap<char, long>{}; auto c2 = std::unordered_multimap<long, long>{}; auto c3 = std::unordered_multimap<long, long, std::hash<int>>{}; auto c4 = std::unordered_multimap<long, long, Ha>{}; std::cout << "Max bucket count of\n" << std::hex << std::showbase << "c1: " << c1.max_bucket_count() << '\n' << "c2: " << c2.max_bucket_count() << '\n' << "c3: " << c3.max_bucket_count() << '\n' << "c4: " << c4.max_bucket_count() << '\n' ; } ``` Possible output: ``` Max bucket count of c1: 0xfffffffffffffff c2: 0xfffffffffffffff c3: 0xfffffffffffffff c4: 0xaaaaaaaaaaaaaaa ``` ### See also | | | | --- | --- | | [bucket\_count](bucket_count "cpp/container/unordered multimap/bucket count") (C++11) | returns the number of buckets (public member function) | cpp std::unordered_multimap<Key,T,Hash,KeyEqual,Allocator>::find std::unordered\_multimap<Key,T,Hash,KeyEqual,Allocator>::find ============================================================= | | | | | --- | --- | --- | | ``` iterator find( const Key& key ); ``` | (1) | | | ``` const_iterator find( const Key& key ) const; ``` | (2) | | | ``` template< class K > iterator find( const K& x ); ``` | (3) | (since C++20) | | ``` template< class K > const_iterator find( const K& x ) const; ``` | (4) | (since C++20) | 1,2) Finds an element with key equivalent to `key`. 3,4) Finds an element with key that compares *equivalent* to the value `x`. This overload participates in overload resolution only if `Hash::is_transparent` and `KeyEqual::is_transparent` are valid and each denotes a type. This assumes that such `Hash` is callable with both `K` and `Key` type, and that the `KeyEqual` is transparent, which, together, allows calling this function without constructing an instance of `Key`. ### Parameters | | | | | --- | --- | --- | | key | - | key value of the element to search for | | x | - | a value of any type that can be transparently compared with a key | ### Return value Iterator to an element with key equivalent to `key`. If no such element is found, past-the-end (see `[end()](end "cpp/container/unordered multimap/end")`) iterator is returned. ### Complexity Constant on average, worst case linear in the size of the container. ### Notes | [Feature-test](../../utility/feature_test "cpp/utility/feature test") macro | Comment | | --- | --- | | [`__cpp_lib_generic_unordered_lookup`](../../feature_test#Library_features "cpp/feature test") | for overloads (3,4) | ### Example ``` #include <iostream> #include <unordered_map> int main() { // simple comparison demo std::unordered_multimap<int,char> example = {{1,'a'},{2,'b'}}; auto search = example.find(2); if (search != example.end()) { std::cout << "Found " << search->first << " " << search->second << '\n'; } else { std::cout << "Not found\n"; } } ``` Output: ``` Found 2 b ``` ### See also | | | | --- | --- | | [count](count "cpp/container/unordered multimap/count") (C++11) | returns the number of elements matching specific key (public member function) | | [equal\_range](equal_range "cpp/container/unordered multimap/equal range") (C++11) | returns range of elements matching a specific key (public member function) | cpp std::unordered_multimap<Key,T,Hash,KeyEqual,Allocator>::equal_range std::unordered\_multimap<Key,T,Hash,KeyEqual,Allocator>::equal\_range ===================================================================== | | | | | --- | --- | --- | | ``` std::pair<iterator,iterator> equal_range( const Key& key ); ``` | (1) | (since C++11) | | ``` std::pair<const_iterator,const_iterator> equal_range( const Key& key ) const; ``` | (2) | (since C++11) | | ``` template< class K > std::pair<iterator,iterator> equal_range( const K& x ); ``` | (3) | (since C++20) | | ``` template< class K > std::pair<const_iterator,const_iterator> equal_range( const K& x ) const; ``` | (4) | (since C++20) | 1,2) Returns a range containing all elements with key `key` in the container. The range is defined by two iterators, the first pointing to the first element of the wanted range and the second pointing past the last element of the range. 3,4) Returns a range containing all elements in the container with key equivalent to `x`. This overload participates in overload resolution only if `Hash::is_transparent` and `KeyEqual::is_transparent` are valid and each denotes a type. This assumes that such `Hash` is callable with both `K` and `Key` type, and that the `KeyEqual` is transparent, which, together, allows calling this function without constructing an instance of `Key`. ### Parameters | | | | | --- | --- | --- | | key | - | key value to compare the elements to | | x | - | a value of any type that can be transparently compared with a key | ### Return value `[std::pair](../../utility/pair "cpp/utility/pair")` containing a pair of iterators defining the wanted range. If there are no such elements, past-the-end (see `[end()](end "cpp/container/unordered multimap/end")`) iterators are returned as both elements of the pair. ### Complexity Average case linear in the number of elements with the key `key`, worst case linear in the size of the container. ### Notes | [Feature-test](../../utility/feature_test "cpp/utility/feature test") macro | Comment | | --- | --- | | [`__cpp_lib_generic_unordered_lookup`](../../feature_test#Library_features "cpp/feature test") | for overloads (3,4) | ### Example ``` #include <iostream> #include <unordered_map> int main() { std::unordered_multimap<int,char> map = {{1,'a'},{1,'b'},{1,'d'},{2,'b'}}; auto range = map.equal_range(1); for (auto it = range.first; it != range.second; ++it) { std::cout << it->first << ' ' << it->second << '\n'; } } ``` Output: ``` 1 a 1 b 1 d ``` ### See also | | | | --- | --- | | [find](find "cpp/container/unordered multimap/find") (C++11) | finds element with specific key (public member function) | | [contains](contains "cpp/container/unordered multimap/contains") (C++20) | checks if the container contains element with specific key (public member function) | | [count](count "cpp/container/unordered multimap/count") (C++11) | returns the number of elements matching specific key (public member function) | | [equal\_range](../../algorithm/equal_range "cpp/algorithm/equal range") | returns range of elements matching a specific key (function template) | cpp std::unordered_multimap<Key,T,Hash,KeyEqual,Allocator>::erase std::unordered\_multimap<Key,T,Hash,KeyEqual,Allocator>::erase ============================================================== | | | | | --- | --- | --- | | | (1) | | | ``` iterator erase( iterator pos ); ``` | (since C++11) | | ``` iterator erase( const_iterator pos ); ``` | (since C++11) | | | (2) | | | ``` iterator erase( const_iterator first, const_iterator last ); ``` | (since C++11) | | ``` size_type erase( const Key& key ); ``` | (3) | (since C++11) | | ``` template< class K > size_type erase( K&& x ); ``` | (4) | (since C++23) | Removes specified elements from the container. 1) Removes the element at `pos`. 2) Removes the elements in the range `[first; last)`, which must be a valid range in `*this`. 3) Removes all elements with the key equivalent to `key`. 4) Removes all elements with key that compares *equivalent* to the value `x`. This overload participates in overload resolution only if `Hash::is_transparent` and `KeyEqual::is_transparent` are valid and each denotes a type, and neither `iterator` nor `const_iterator` is implicitly convertible from `K`. This assumes that such `Hash` is callable with both `K` and `Key` type, and that the `KeyEqual` is transparent, which, together, allows calling this function without constructing an instance of `Key`. References and iterators to the erased elements are invalidated. Other iterators and references are not invalidated. The iterator `pos` must be valid and dereferenceable. Thus the `[end()](end "cpp/container/unordered multimap/end")` iterator (which is valid, but is not dereferenceable) cannot be used as a value for `pos`. The order of the elements that are not erased is preserved. (This makes it possible to erase individual elements while iterating through the container.). ### Parameters | | | | | --- | --- | --- | | pos | - | iterator to the element to remove | | first, last | - | range of elements to remove | | key | - | key value of the elements to remove | | x | - | a value of any type that can be transparently compared with a key denoting the elements to remove | ### Return value 1-2) Iterator following the last removed element. 3,4) Number of elements removed. ### Exceptions 1,2) Throws nothing. 3,4) Any exceptions thrown by the `Hash` and `KeyEqual` object. ### Complexity Given an instance `c` of `unordered_multimap`: 1) Average case: constant, worst case: `c.size()` 2) Average case: `[std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(first, last)`, worst case: `c.size()` 3) Average case: `c.count(key)`, worst case: `c.size()` 4) Average case: `c.count(x)`, worst case: `c.size()` ### Notes | [Feature-test](../../utility/feature_test "cpp/utility/feature test") macro | Comment | | --- | --- | | [`__cpp_lib_associative_heterogeneous_erasure`](../../feature_test#Library_features "cpp/feature test") | for overload (4) | ### Example ``` #include <unordered_map> #include <iostream> int main() { std::unordered_multimap<int, std::string> c = { {1, "one" }, {2, "two" }, {3, "three"}, {4, "four"}, {5, "five"}, {6, "six" } }; // erase all odd numbers from c for(auto it = c.begin(); it != c.end(); ) { if(it->first % 2 != 0) it = c.erase(it); else ++it; } for(auto& p : c) { std::cout << p.second << ' '; } } ``` Possible output: ``` two four six ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 2059](https://cplusplus.github.io/LWG/issue2059) | C++11 | overload for one `const_iterator` introduced new ambiguity | overload for `iterator` added | | [LWG 2356](https://cplusplus.github.io/LWG/issue2356) | C++11 | the order of element that are not erased was unspecified | required to be preserved | ### See also | | | | --- | --- | | [clear](clear "cpp/container/unordered multimap/clear") (C++11) | clears the contents (public member function) |
programming_docs
cpp std::unordered_multimap<Key,T,Hash,KeyEqual,Allocator>::load_factor std::unordered\_multimap<Key,T,Hash,KeyEqual,Allocator>::load\_factor ===================================================================== | | | | | --- | --- | --- | | ``` float load_factor() const; ``` | | (since C++11) | Returns the average number of elements per bucket, that is, `[size()](size "cpp/container/unordered multimap/size")` divided by `[bucket\_count()](bucket_count "cpp/container/unordered multimap/bucket count")`. ### Parameters (none). ### Return value Average number of elements per bucket. ### Complexity Constant. ### See also | | | | --- | --- | | [max\_load\_factor](max_load_factor "cpp/container/unordered multimap/max load factor") (C++11) | manages maximum average number of elements per bucket (public member function) | cpp std::swap(std::unordered_multimap) std::swap(std::unordered\_multimap) =================================== | Defined in header `[<unordered\_map>](../../header/unordered_map "cpp/header/unordered map")` | | | | --- | --- | --- | | ``` template< class Key, class T, class Hash, class KeyEqual, class Alloc > void swap( std::unordered_multimap<Key,T,Hash,KeyEqual,Alloc>& lhs, std::unordered_multimap<Key,T,Hash,KeyEqual,Alloc>& rhs ); ``` | | (since C++11) (until C++17) | | ``` template< class Key, class T, class Hash, class KeyEqual, class Alloc > void swap( std::unordered_multimap<Key,T,Hash,KeyEqual,Alloc>& lhs, std::unordered_multimap<Key,T,Hash,KeyEqual,Alloc>& rhs ) noexcept(/* see below */); ``` | | (since C++17) | Specializes the `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` algorithm for `[std::unordered\_multimap](http://en.cppreference.com/w/cpp/container/unordered_multimap)`. Swaps the contents of `lhs` and `rhs`. Calls `lhs.swap(rhs)`. ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | containers whose contents to swap | ### Return value (none). ### Complexity Constant. ### Exceptions | | | | --- | --- | | [`noexcept`](../../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept(noexcept(lhs.swap(rhs)))` | (since C++17) | ### Notes Although the overloads of `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` for container adaptors are introduced in C++11, container adaptors can already be swapped by `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` in C++98. Such calls to `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` usually have linear time complexity, but better complexity may be provided. ### Example ``` #include <algorithm> #include <iostream> #include <unordered_map> int main() { std::unordered_multimap<int, char> alice{{1, 'a'}, {2, 'b'}, {3, 'c'}}; std::unordered_multimap<int, char> bob{{7, 'Z'}, {8, 'Y'}, {9, 'X'}, {10, 'W'}}; auto print = [](std::pair<const int, char>& n) { std::cout << " " << n.first << '(' << n.second << ')'; }; // Print state before swap std::cout << "alice:"; std::for_each(alice.begin(), alice.end(), print); std::cout << "\n" "bob :"; std::for_each(bob.begin(), bob.end(), print); std::cout << '\n'; std::cout << "-- SWAP\n"; std::swap(alice, bob); // Print state after swap std::cout << "alice:"; std::for_each(alice.begin(), alice.end(), print); std::cout << "\n" "bob :"; std::for_each(bob.begin(), bob.end(), print); std::cout << '\n'; } ``` Possible output: ``` alice: 1(a) 2(b) 3(c) bob : 7(Z) 8(Y) 9(X) 10(W) -- SWAP alice: 7(Z) 8(Y) 9(X) 10(W) bob : 1(a) 2(b) 3(c) ``` ### See also | | | | --- | --- | | [swap](swap "cpp/container/unordered multimap/swap") (C++11) | swaps the contents (public member function) | cpp std::unordered_multimap<Key,T,Hash,KeyEqual,Allocator>::operator= std::unordered\_multimap<Key,T,Hash,KeyEqual,Allocator>::operator= ================================================================== | | | | | --- | --- | --- | | ``` unordered_multimap& operator=( const unordered_multimap& other ); ``` | (1) | (since C++11) | | | (2) | | | ``` unordered_multimap& operator=( unordered_multimap&& other ); ``` | (since C++11) (until C++17) | | ``` unordered_multimap& operator=( unordered_multimap&& other ) noexcept(/* see below */); ``` | (since C++17) | | ``` unordered_multimap& operator=( std::initializer_list<value_type> ilist ); ``` | (3) | (since C++11) | Replaces the contents of the container. 1) Copy assignment operator. Replaces the contents with a copy of the contents of `other`. If `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<allocator_type>::propagate\_on\_container\_copy\_assignment::value` is `true`, the allocator of `*this` is replaced by a copy of that of `other`. If the allocator of `*this` after assignment would compare unequal to its old value, the old allocator is used to deallocate the memory, then the new allocator is used to allocate it before copying the elements. Otherwise, the memory owned by `*this` may be reused when possible. In any case, the elements originally belonging to `*this` may be either destroyed or replaced by element-wise copy-assignment. 2) Move assignment operator. Replaces the contents with those of `other` using move semantics (i.e. the data in `other` is moved from `other` into this container). `other` is in a valid but unspecified state afterwards. If `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<allocator_type>::propagate\_on\_container\_move\_assignment::value` is `true`, the allocator of `*this` is replaced by a copy of that of `other`. If it is `false` and the allocators of `*this` and `other` do not compare equal, `*this` cannot take ownership of the memory owned by `other` and must move-assign each element individually, allocating additional memory using its own allocator as needed. In any case, all elements originally belonging to `*this` are either destroyed or replaced by element-wise move-assignment. 3) Replaces the contents with those identified by initializer list `ilist`. ### Parameters | | | | | --- | --- | --- | | other | - | another container to use as data source | | ilist | - | initializer list to use as data source | ### Return value `*this`. ### Complexity 1) Linear in the size of `*this` and `other`. 2) Linear in the size of `*this` unless the allocators do not compare equal and do not propagate, in which case linear in the size of `*this` and `other`. 3) Linear in the size of `*this` and `ilist`. ### Exceptions | | | | --- | --- | | May throw implementation-defined exceptions. | (until C++17) | | 1,3) May throw implementation-defined exceptions. 2) [`noexcept`](../../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept([std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<Allocator>::is\_always\_equal::value && [std::is\_nothrow\_move\_assignable](http://en.cppreference.com/w/cpp/types/is_move_assignable)<Hash>::value. && [std::is\_nothrow\_move\_assignable](http://en.cppreference.com/w/cpp/types/is_move_assignable)<Pred>::value)` | (since C++17) | ### Notes After container move assignment (overload (2)), unless element-wise move assignment is forced by incompatible allocators, references, pointers, and iterators (other than the end iterator) to `other` remain valid, but refer to elements that are now in `*this`. The current standard makes this guarantee via the blanket statement in [[container.requirements.general]/12](https://eel.is/c++draft/container.requirements.general#12), and a more direct guarantee is under consideration via [LWG 2321](https://cplusplus.github.io/LWG/issue2321). ### Example The following code uses `operator=` to assign one `[std::unordered\_multimap](../unordered_multimap "cpp/container/unordered multimap")` to another: ``` #include <unordered_map> #include <iterator> #include <iostream> #include <utility> #include <initializer_list> void print(auto const comment, auto const& container) { auto size = std::size(container); std::cout << comment << "{ "; for (auto const& [key, value]: container) std::cout << '{' << key << ',' << value << (--size ? "}, " : "} "); std::cout << "}\n"; } int main() { std::unordered_multimap<int, int> x { {1,1}, {2,2}, {3,3} }, y, z; const auto w = { std::pair<const int, int>{4,4}, {5,5}, {6,6}, {7,7} }; std::cout << "Initially:\n"; print("x = ", x); print("y = ", y); print("z = ", z); std::cout << "Copy assignment copies data from x to y:\n"; y = x; print("x = ", x); print("y = ", y); std::cout << "Move assignment moves data from x to z, modifying both x and z:\n"; z = std::move(x); print("x = ", x); print("z = ", z); std::cout << "Assignment of initializer_list w to z:\n"; z = w; print("w = ", w); print("z = ", z); } ``` Possible output: ``` Initially: x = { {3,3}, {2,2}, {1,1} } y = { } z = { } Copy assignment copies data from x to y: x = { {3,3}, {2,2}, {1,1} } y = { {3,3}, {2,2}, {1,1} } Move assignment moves data from x to z, modifying both x and z: x = { } z = { {3,3}, {2,2}, {1,1} } Assignment of initializer_list w to z: w = { {4,4}, {5,5}, {6,6}, {7,7} } z = { {7,7}, {6,6}, {5,5}, {4,4} } ``` ### See also | | | | --- | --- | | [(constructor)](unordered_multimap "cpp/container/unordered multimap/unordered multimap") (C++11) | constructs the `unordered_multimap` (public member function) | cpp std::unordered_multimap<Key,T,Hash,KeyEqual,Allocator>::clear std::unordered\_multimap<Key,T,Hash,KeyEqual,Allocator>::clear ============================================================== | | | | | --- | --- | --- | | ``` void clear() noexcept; ``` | | (since C++11) | Erases all elements from the container. After this call, `[size()](size "cpp/container/unordered multimap/size")` returns zero. Invalidates any references, pointers, or iterators referring to contained elements. May also invalidate past-the-end iterators. ### Parameters (none). ### Return value (none). ### Complexity Linear in the size of the container, i.e., the number of elements. ### Example ``` #include <algorithm> #include <iostream> #include <unordered_map> int main() { std::unordered_multimap<int, char> container{{1, 'x'}, {2, 'y'}, {3, 'z'}}; auto print = [](std::pair<const int, char>& n) { std::cout << " " << n.first << '(' << n.second << ')'; }; std::cout << "Before clear:"; std::for_each(container.begin(), container.end(), print); std::cout << "\nSize=" << container.size() << '\n'; std::cout << "Clear\n"; container.clear(); std::cout << "After clear:"; std::for_each(container.begin(), container.end(), print); std::cout << "\nSize=" << container.size() << '\n'; } ``` Possible output: ``` Before clear: 1(x) 2(y) 3(z) Size=3 Clear After clear: Size=0 ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 2550](https://cplusplus.github.io/LWG/issue2550) | C++11 | for unordered associative containers, unclear if complexity is linear in the number of elements or buckets | clarified that it's linear in the number of elements | ### See also | | | | --- | --- | | [erase](erase "cpp/container/unordered multimap/erase") (C++11) | erases elements (public member function) | cpp std::unordered_multimap<Key,T,Hash,KeyEqual,Allocator>::rehash std::unordered\_multimap<Key,T,Hash,KeyEqual,Allocator>::rehash =============================================================== | | | | | --- | --- | --- | | ``` void rehash( size_type count ); ``` | | (since C++11) | Sets the number of buckets to `count` and rehashes the container, i.e. puts the elements into appropriate buckets considering that total number of buckets has changed. If the new number of buckets makes load factor more than maximum load factor (`count < size() / max_load_factor()`), then the new number of buckets is at least `size() / max_load_factor()`. ### Parameters | | | | | --- | --- | --- | | count | - | new number of buckets | ### Return value (none). ### Complexity Average case linear in the size of the container, worst case quadratic. ### Notes `rehash(0)` may be used to force an unconditional rehash, such as after suspension of automatic rehashing by temporarily increasing `max_load_factor()`. ### See also | | | | --- | --- | | [reserve](reserve "cpp/container/unordered multimap/reserve") (C++11) | reserves space for at least the specified number of elements and regenerates the hash table (public member function) | cpp std::unordered_multimap<Key,T,Hash,KeyEqual,Allocator>::key_eq std::unordered\_multimap<Key,T,Hash,KeyEqual,Allocator>::key\_eq ================================================================ | | | | | --- | --- | --- | | ``` key_equal key_eq() const; ``` | | (since C++11) | Returns the function that compares keys for equality. ### Parameters (none). ### Return value The key comparison function. ### Complexity Constant. ### See also | | | | --- | --- | | [hash\_function](hash_function "cpp/container/unordered multimap/hash function") (C++11) | returns function used to hash the keys (public member function) | cpp std::unordered_multimap<Key,T,Hash,KeyEqual,Allocator>::end(size_type), std::unordered_multimap<Key,T,Hash,KeyEqual,Allocator>::cend(size_type) std::unordered\_multimap<Key,T,Hash,KeyEqual,Allocator>::end(size\_type), std::unordered\_multimap<Key,T,Hash,KeyEqual,Allocator>::cend(size\_type) =================================================================================================================================================== | | | | | --- | --- | --- | | ``` local_iterator end( size_type n ); ``` | | (since C++11) | | ``` const_local_iterator end( size_type n ) const; ``` | | (since C++11) | | ``` const_local_iterator cend( size_type n ) const; ``` | | (since C++11) | Returns an iterator to the element following the last element of the bucket with index `n`. . This element acts as a placeholder, attempting to access it results in undefined behavior. ### Parameters | | | | | --- | --- | --- | | n | - | the index of the bucket to access | ### Return value iterator to the element following the last element. ### Complexity Constant. ### See also | | | | --- | --- | | [begin(size\_type) cbegin(size\_type)](begin2 "cpp/container/unordered multimap/begin2") (C++11) | returns an iterator to the beginning of the specified bucket (public member function) | cpp operator==,!=(std::unordered_multimap) operator==,!=(std::unordered\_multimap) ======================================= | | | | | --- | --- | --- | | ``` template< class Key, class T, class Hash, class KeyEqual, class Alloc > bool operator==( const std::unordered_multimap<Key,T,Hash,KeyEqual,Alloc>& lhs, const std::unordered_multimap<Key,T,Hash,KeyEqual,Alloc>& rhs ); ``` | (1) | | | ``` template< class Key, class T, class Hash, class KeyEqual, class Alloc > bool operator!=( const std::unordered_multimap<Key,T,Hash,KeyEqual,Alloc>& lhs, const std::unordered_multimap<Key,T,Hash,KeyEqual,Alloc>& rhs ); ``` | (2) | (until C++20) | Compares the contents of two unordered containers. The contents of two unordered containers `lhs` and `rhs` are equal if the following conditions hold: * `lhs.size() == rhs.size()` * each group of equivalent elements `[lhs_eq1, lhs_eq2)` obtained from `lhs.equal_range(lhs_eq1)` has a corresponding group of equivalent elements in the other container `[rhs_eq1, rhs_eq2)` obtained from `rhs.equal_range(rhs_eq1)`, that has the following properties: + `[std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(lhs_eq1, lhs_eq2) == [std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(rhs_eq1, rhs_eq2)`. + `[std::is\_permutation](http://en.cppreference.com/w/cpp/algorithm/is_permutation)(lhs_eq1, lhs_eq2, rhs_eq1) == true`. The behavior is undefined if `Key` or `T` are not [EqualityComparable](../../named_req/equalitycomparable "cpp/named req/EqualityComparable"). The behavior is also undefined if `hash_function()` and `key_eq()` do (until C++20)`key_eq()` does (since C++20) not have the same behavior on `lhs` and `rhs` or if `operator==` for `Key` is not a refinement of the partition into equivalent-key groups introduced by `key_eq()` (that is, if two elements that compare equal using `operator==` fall into different partitions). | | | | --- | --- | | The `!=` operator is [synthesized](../../language/operators#Relational_operators "cpp/language/operators") from `operator==`. | (since C++20) | ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | unordered containers to compare | ### Return value 1) `true` if the contents of the containers are equal, `false` otherwise 2) `true` if the contents of the containers are not equal, `false` otherwise ### Complexity Proportional to *ΣSi2* calls to `operator==` on `value_type`, calls to the predicate returned by [`key_eq`](key_eq "cpp/container/unordered multimap/key eq"), and calls to the hasher returned by [`hash_function`](hash_function "cpp/container/unordered multimap/hash function") in the average case, where *S* is the size of the *i*th equivalent key group. Proportional to *N2* in the worst case, where *N* is the size of the container. Average case becomes proportional to *N* if the elements within each equivalent key group are arranged in the same order (happens when the containers are copies of each other). cpp std::unordered_multimap<Key,T,Hash,KeyEqual,Allocator>::reserve std::unordered\_multimap<Key,T,Hash,KeyEqual,Allocator>::reserve ================================================================ | | | | | --- | --- | --- | | ``` void reserve( size_type count ); ``` | | (since C++11) | Sets the number of buckets to the number needed to accomodate at least `count` elements without exceeding maximum load factor and rehashes the container, i.e. puts the elements into appropriate buckets considering that total number of buckets has changed. Effectively calls `rehash([std::ceil](http://en.cppreference.com/w/cpp/numeric/math/ceil)(count / max_load_factor()))`. ### Parameters | | | | | --- | --- | --- | | count | - | new capacity of the container | ### Return value (none). ### Complexity Average case linear in the size of the container, worst case quadratic. ### See also | | | | --- | --- | | [rehash](rehash "cpp/container/unordered multimap/rehash") (C++11) | reserves at least the specified number of buckets and regenerates the hash table (public member function) | cpp std::unordered_multimap<Key,T,Hash,KeyEqual,Allocator>::empty std::unordered\_multimap<Key,T,Hash,KeyEqual,Allocator>::empty ============================================================== | | | | | --- | --- | --- | | ``` bool empty() const noexcept; ``` | | (since C++11) (until C++20) | | ``` [[nodiscard]] bool empty() const noexcept; ``` | | (since C++20) | Checks if the container has no elements, i.e. whether `begin() == end()`. ### Parameters (none). ### Return value `true` if the container is empty, `false` otherwise. ### Complexity Constant. ### Example The following code uses `empty` to check if a `[std::unordered\_multimap](http://en.cppreference.com/w/cpp/container/unordered_multimap)<int,int>` contains any elements: ``` #include <unordered_map> #include <iostream> #include <utility> int main() { std::unordered_multimap<int, int> numbers; std::cout << std::boolalpha; std::cout << "Initially, numbers.empty(): " << numbers.empty() << '\n'; numbers.emplace(42, 13); numbers.insert(std::make_pair(13317, 123)); std::cout << "After adding elements, numbers.empty(): " << numbers.empty() << '\n'; } ``` Output: ``` Initially, numbers.empty(): true After adding elements, numbers.empty(): false ``` ### See also | | | | --- | --- | | [size](size "cpp/container/unordered multimap/size") (C++11) | returns the number of elements (public member function) | | [empty](../../iterator/empty "cpp/iterator/empty") (C++17) | checks whether the container is empty (function template) |
programming_docs
cpp std::unordered_multimap<Key,T,Hash,KeyEqual,Allocator>::begin, std::unordered_multimap<Key,T,Hash,KeyEqual,Allocator>::cbegin std::unordered\_multimap<Key,T,Hash,KeyEqual,Allocator>::begin, std::unordered\_multimap<Key,T,Hash,KeyEqual,Allocator>::cbegin =============================================================================================================================== | | | | | --- | --- | --- | | ``` iterator begin() noexcept; ``` | | (since C++11) | | ``` const_iterator begin() const noexcept; ``` | | (since C++11) | | ``` const_iterator cbegin() const noexcept; ``` | | (since C++11) | Returns an iterator to the first element of the `unordered_multimap`. If the `unordered_multimap` is empty, the returned iterator will be equal to `[end()](end "cpp/container/unordered multimap/end")`. ![range-begin-end.svg]() ### Parameters (none). ### Return value Iterator to the first element. ### Complexity Constant. ### Example ``` #include <unordered_map> #include <algorithm> #include <cassert> #include <iostream> #include <string> #include <utility> int main() { auto show_node = [](const std::pair<std::string, std::string>& node) { std::cout << node.first << " : " << node.second << '\n'; }; std::unordered_multimap<std::string, std::string> lemmas; assert(lemmas.begin() == lemmas.end()); // OK assert(lemmas.cbegin() == lemmas.cend()); // OK lemmas.insert({ "1. ∀x ∈ N ∃y ∈ N", "x ≤ y" }); show_node(*lemmas.cbegin()); assert(lemmas.begin() != lemmas.end()); // OK assert(lemmas.cbegin() != lemmas.cend()); // OK lemmas.begin()->second = "x < y"; show_node(*lemmas.cbegin()); lemmas.insert({ "2. ∀x,y ∈ N", "x = y V x ≠ y" }); show_node(*lemmas.cbegin()); lemmas.insert({ "3. ∀x ∈ N ∃y ∈ N", "y = x + 1" }); show_node(*lemmas.cbegin()); std::cout << "lemmas: \n"; std::for_each(lemmas.cbegin(), lemmas.cend(), [&](const auto& n) { show_node(n); }); std::cout << "\n"; } ``` Possible output: ``` 1. ∀x ∈ N ∃y ∈ N : x ≤ y 1. ∀x ∈ N ∃y ∈ N : x < y 2. ∀x,y ∈ N : x = y V x ≠ y 3. ∀x ∈ N ∃y ∈ N : y = x + 1 lemmas: 3. ∀x ∈ N ∃y ∈ N : y = x + 1 1. ∀x ∈ N ∃y ∈ N : x < y 2. ∀x,y ∈ N : x = y V x ≠ y ``` ### See also | | | | --- | --- | | [end cend](end "cpp/container/unordered multimap/end") (C++11) | returns an iterator to the end (public member function) | | [begincbegin](../../iterator/begin "cpp/iterator/begin") (C++11)(C++14) | returns an iterator to the beginning of a container or array (function template) | cpp std::unordered_multimap<Key,T,Hash,KeyEqual,Allocator>::begin(size_type), std::unordered_multimap<Key,T,Hash,KeyEqual,Allocator>::cbegin(size_type) std::unordered\_multimap<Key,T,Hash,KeyEqual,Allocator>::begin(size\_type), std::unordered\_multimap<Key,T,Hash,KeyEqual,Allocator>::cbegin(size\_type) ======================================================================================================================================================= | | | | | --- | --- | --- | | ``` local_iterator begin( size_type n ); ``` | | (since C++11) | | ``` const_local_iterator begin( size_type n ) const; ``` | | (since C++11) | | ``` const_local_iterator cbegin( size_type n ) const; ``` | | (since C++11) | Returns an iterator to the first element of the bucket with index `n`. ### Parameters | | | | | --- | --- | --- | | n | - | the index of the bucket to access | ### Return value Iterator to the first element. ### Complexity Constant. ### See also | | | | --- | --- | | [end(size\_type) cend(size\_type)](end2 "cpp/container/unordered multimap/end2") (C++11) | returns an iterator to the end of the specified bucket (public member function) | cpp std::unordered_multimap<Key,T,Hash,KeyEqual,Allocator>::end, std::unordered_multimap<Key,T,Hash,KeyEqual,Allocator>::cend std::unordered\_multimap<Key,T,Hash,KeyEqual,Allocator>::end, std::unordered\_multimap<Key,T,Hash,KeyEqual,Allocator>::cend =========================================================================================================================== | | | | | --- | --- | --- | | ``` iterator end() noexcept; ``` | | (since C++11) | | ``` const_iterator end() const noexcept; ``` | | (since C++11) | | ``` const_iterator cend() const noexcept; ``` | | (since C++11) | Returns an iterator to the element following the last element of the `unordered_multimap`. This element acts as a placeholder; attempting to access it results in undefined behavior. ![range-begin-end.svg]() ### Parameters (none). ### Return value Iterator to the element following the last element. ### Complexity Constant. ### Example ``` #include <unordered_map> #include <algorithm> #include <cassert> #include <iostream> #include <string> #include <utility> int main() { auto show_node = [](const std::pair<std::string, std::string>& node) { std::cout << node.first << " : " << node.second << '\n'; }; std::unordered_multimap<std::string, std::string> lemmas; assert(lemmas.begin() == lemmas.end()); // OK assert(lemmas.cbegin() == lemmas.cend()); // OK lemmas.insert({ "1. ∀x ∈ N ∃y ∈ N", "x ≤ y" }); show_node(*lemmas.cbegin()); assert(lemmas.begin() != lemmas.end()); // OK assert(lemmas.cbegin() != lemmas.cend()); // OK lemmas.begin()->second = "x < y"; show_node(*lemmas.cbegin()); lemmas.insert({ "2. ∀x,y ∈ N", "x = y V x ≠ y" }); show_node(*lemmas.cbegin()); lemmas.insert({ "3. ∀x ∈ N ∃y ∈ N", "y = x + 1" }); show_node(*lemmas.cbegin()); std::cout << "lemmas: \n"; std::for_each(lemmas.cbegin(), lemmas.cend(), [&](const auto& n) { show_node(n); }); std::cout << "\n"; } ``` Possible output: ``` 1. ∀x ∈ N ∃y ∈ N : x ≤ y 1. ∀x ∈ N ∃y ∈ N : x < y 2. ∀x,y ∈ N : x = y V x ≠ y 3. ∀x ∈ N ∃y ∈ N : y = x + 1 lemmas: 3. ∀x ∈ N ∃y ∈ N : y = x + 1 1. ∀x ∈ N ∃y ∈ N : x < y 2. ∀x,y ∈ N : x = y V x ≠ y ``` ### See also | | | | --- | --- | | [begin cbegin](begin "cpp/container/unordered multimap/begin") (C++11) | returns an iterator to the beginning (public member function) | | [endcend](../../iterator/end "cpp/iterator/end") (C++11)(C++14) | returns an iterator to the end of a container or array (function template) | cpp std::unordered_multimap<Key,T,Hash,KeyEqual,Allocator>::bucket std::unordered\_multimap<Key,T,Hash,KeyEqual,Allocator>::bucket =============================================================== | | | | | --- | --- | --- | | ``` size_type bucket( const Key& key ) const; ``` | | (since C++11) | Returns the index of the bucket for key `key`. Elements (if any) with keys equivalent to `key` are always found in this bucket. The returned value is valid only for instances of the container for which `[bucket\_count()](bucket_count "cpp/container/unordered multimap/bucket count")` returns the same value. The behavior is undefined if `[bucket\_count()](bucket_count "cpp/container/unordered multimap/bucket count")` is zero. ### Parameters | | | | | --- | --- | --- | | key | - | the value of the key to examine | ### Return value Bucket index for the key `key`. ### Complexity Constant. ### See also | | | | --- | --- | | [bucket\_size](bucket_size "cpp/container/unordered multimap/bucket size") (C++11) | returns the number of elements in specific bucket (public member function) | cpp std::to_array std::to\_array ============== | Defined in header `[<array>](../../header/array "cpp/header/array")` | | | | --- | --- | --- | | ``` template<class T, std::size_t N> constexpr std::array<std::remove_cv_t<T>, N> to_array(T (&a)[N]); ``` | (1) | (since C++20) | | ``` template<class T, std::size_t N> constexpr std::array<std::remove_cv_t<T>, N> to_array(T (&&a)[N]); ``` | (2) | (since C++20) | Creates a `[std::array](../array "cpp/container/array")` from the one dimensional built-in array `a`. The elements of the `std::array` are copy-initialized from the corresponding element of `a`. Copying or moving multidimensional built-in array is not supported. 1) For every `i` in `0, ..., N - 1`, copy-initializes result's correspond element with `a[i]`. This overload is ill-formed when `[std::is\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_constructible)<T, T&>` is `false`. 2) For every `i` in `0, ..., N - 1`, move-initializes result's correspond element with `std::move(a[i])`. This overload is ill-formed when `[std::is\_move\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_move_constructible)<T>` is `false`. Both overloads are ill-formed when `[std::is\_array\_v](http://en.cppreference.com/w/cpp/types/is_array)<T>` is `true`. ### Parameters | | | | | --- | --- | --- | | a | - | the built-in array to be converted the `[std::array](../array "cpp/container/array")` | | Type requirements | | -`T` must meet the requirements of [CopyConstructible](../../named_req/copyconstructible "cpp/named req/CopyConstructible") in order to use overload (1). | | -`T` must meet the requirements of [MoveConstructible](../../named_req/moveconstructible "cpp/named req/MoveConstructible") in order to use overload (2). | ### Return value 1) `[std::array](http://en.cppreference.com/w/cpp/container/array)<[std::remove\_cv\_t](http://en.cppreference.com/w/cpp/types/remove_cv)<T>, N>{ a[0], ..., a[N - 1] }` 2) `[std::array](http://en.cppreference.com/w/cpp/container/array)<[std::remove\_cv\_t](http://en.cppreference.com/w/cpp/types/remove_cv)<T>, N>{ std::move(a[0]), ..., std::move(a[N - 1]) }` ### Notes There are some occasions where [class template argument deduction](../../language/class_template_argument_deduction "cpp/language/class template argument deduction") of `[std::array](../array "cpp/container/array")` cannot be used while `to_array` being available: * `to_array` can be used when the element type of the `std::array` is manually specified and the length is deduced, which is preferable when implicit conversion is wanted. * `to_array` can copy a string literal, while class template argument deduction constructs a `std::array` of a single pointer to its first character. ``` std::to_array<long>({3, 4}); // OK: implicit conversion // std::array<long>{3, 4}; // error: too few template arguments std::to_array("foo"); // creates std::array<char, 4>{ 'f', 'o', 'o', '\0' } std::array{"foo"}; // creates std::array<const char*, 1>{ +"foo" } ``` | [Feature-test](../../utility/feature_test "cpp/utility/feature test") macro | | --- | | [`__cpp_lib_to_array`](../../feature_test#Library_features "cpp/feature test") | ### Possible implementation | First version | | --- | | ``` namespace detail { template <class T, std::size_t N, std::size_t... I> constexpr std::array<std::remove_cv_t<T>, N> to_array_impl(T (&a)[N], std::index_sequence<I...>) { return { {a[I]...} }; } } template <class T, std::size_t N> constexpr std::array<std::remove_cv_t<T>, N> to_array(T (&a)[N]) { return detail::to_array_impl(a, std::make_index_sequence<N>{}); } ``` | | Second version | | ``` namespace detail { template <class T, std::size_t N, std::size_t... I> constexpr std::array<std::remove_cv_t<T>, N> to_array_impl(T (&&a)[N], std::index_sequence<I...>) { return { {std::move(a[I])...} }; } } template <class T, std::size_t N> constexpr std::array<std::remove_cv_t<T>, N> to_array(T (&&a)[N]) { return detail::to_array_impl(std::move(a), std::make_index_sequence<N>{}); } ``` | ### Example ``` #include <type_traits> #include <utility> #include <array> #include <memory> int main() { // copies a string literal auto a1 = std::to_array("foo"); static_assert(a1.size() == 4); // deduces both element type and length auto a2 = std::to_array({ 0, 2, 1, 3 }); static_assert(std::is_same_v<decltype(a2), std::array<int, 4>>); // deduces length with element type specified // implicit conversion happens auto a3 = std::to_array<long>({ 0, 1, 3 }); static_assert(std::is_same_v<decltype(a3), std::array<long, 3>>); auto a4 = std::to_array<std::pair<int, float>>( { { 3, .0f }, { 4, .1f }, { 4, .1e23f } }); static_assert(a4.size() == 3); // creates a non-copyable std::array auto a5 = std::to_array({ std::make_unique<int>(3) }); static_assert(a5.size() == 1); // error: copying multidimensional arrays is not supported // char s[2][6] = { "nice", "thing" }; // auto a6 = std::to_array(s); } ``` ### See also | | | | --- | --- | | [make\_array](https://en.cppreference.com/w/cpp/experimental/make_array "cpp/experimental/make array") (library fundamentals TS v2) | Creates a `[std::array](../array "cpp/container/array")` object whose size and optionally element type are deduced from the arguments (function template) | cpp std::array<T,N>::size std::array<T,N>::size ===================== | | | | | --- | --- | --- | | ``` constexpr size_type size() const noexcept; ``` | | (since C++11) | Returns the number of elements in the container, i.e. `[std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(begin(), end())`. ### Parameters (none). ### Return value The number of elements in the container. ### Complexity Constant. ### Example The following code uses `size` to display the number of elements in a `[std::array](../array "cpp/container/array")`: ``` #include <array> #include <iostream> int main() { std::array<int, 4> nums {1, 3, 5, 7}; std::cout << "nums contains " << nums.size() << " elements.\n"; } ``` Output: ``` nums contains 4 elements. ``` ### See also | | | | --- | --- | | [empty](empty "cpp/container/array/empty") (C++11) | checks whether the container is empty (public member function) | | [max\_size](max_size "cpp/container/array/max size") (C++11) | returns the maximum possible number of elements (public member function) | | [sizessize](../../iterator/size "cpp/iterator/size") (C++17)(C++20) | returns the size of a container or array (function template) | cpp std::array<T,N>::fill std::array<T,N>::fill ===================== | | | | | --- | --- | --- | | ``` void fill( const T& value ); ``` | | (since C++11) (until C++20) | | ``` constexpr void fill( const T& value ); ``` | | (since C++20) | Assigns the `value` to all elements in the container. ### Parameters | | | | | --- | --- | --- | | value | - | the value to assign to the elements | ### Return value (none). ### Complexity Linear in the size of the container. ### Example ``` #include <array> #include <cstddef> #include <iostream> int main() { constexpr std::size_t xy = 4; using Cell = std::array<unsigned char, 8>; std::array<Cell, xy * xy> board; board.fill({ {0xE2, 0x96, 0x84, 0xE2, 0x96, 0x80, 0, 0} }); // "▄▀"; for (std::size_t count{}; Cell c : board) { std::cout << c.data() << ((++count % xy) ? "" : "\n"); } } ``` Possible output: ``` ▄▀▄▀▄▀▄▀ ▄▀▄▀▄▀▄▀ ▄▀▄▀▄▀▄▀ ▄▀▄▀▄▀▄▀ ``` ### See also | | | | --- | --- | | [fill](../../algorithm/fill "cpp/algorithm/fill") | copy-assigns the given value to every element in a range (function template) | | [fill\_n](../../algorithm/fill_n "cpp/algorithm/fill n") | copy-assigns the given value to N elements in a range (function template) | cpp deduction guides for std::array deduction guides for `std::array` ================================= | Defined in header `[<array>](../../header/array "cpp/header/array")` | | | | --- | --- | --- | | ``` template <class T, class... U> array(T, U...) -> array<T, 1 + sizeof...(U)>; ``` | | (since C++17) | One [deduction guide](../../language/class_template_argument_deduction "cpp/language/class template argument deduction") is provided for `[std::array](../array "cpp/container/array")` to provide an equivalent of `[std::experimental::make\_array](https://en.cppreference.com/w/cpp/experimental/make_array "cpp/experimental/make array")` for construction of std::array from a variadic parameter pack. The program is ill-formed if `([std::is\_same\_v](http://en.cppreference.com/w/cpp/types/is_same)<T, U> && ...)` is not true. Note that `([std::is\_same\_v](http://en.cppreference.com/w/cpp/types/is_same)<T, U> && ...)` is true when `sizeof...(U)` is zero. ### Example ``` #include <array> #include <cassert> int main() { int const x = 10; std::array a{1, 2, 3, 5, x}; // OK, creates std::array<int, 5> assert(a.back() == x); // std::array b{1, 2u}; // Error, all arguments must have same type // std::array<short> c{3, 2, 1}; // Error, wrong number of template args std::array c(std::to_array<short>({3, 2, 1})); // C++20 alternative, creates std::array<short, 3> } ``` cpp std::array<T,N>::rbegin, std::array<T,N>::crbegin std::array<T,N>::rbegin, std::array<T,N>::crbegin ================================================= | | | | | --- | --- | --- | | ``` reverse_iterator rbegin() noexcept; ``` | | (until C++17) | | ``` constexpr reverse_iterator rbegin() noexcept; ``` | | (since C++17) | | ``` const_reverse_iterator rbegin() const noexcept; ``` | | (until C++17) | | ``` constexpr const_reverse_iterator rbegin() const noexcept; ``` | | (since C++17) | | ``` const_reverse_iterator crbegin() const noexcept; ``` | | (until C++17) | | ``` constexpr const_reverse_iterator crbegin() const noexcept; ``` | | (since C++17) | Returns a reverse iterator to the first element of the reversed `array`. It corresponds to the last element of the non-reversed `array`. If the `array` is empty, the returned iterator is equal to `[rend()](rend "cpp/container/array/rend")`. ![range-rbegin-rend.svg]() ### Parameters (none). ### Return value Reverse iterator to the first element. ### Complexity Constant. ### Example ``` #include <algorithm> #include <iostream> #include <string> #include <string_view> #include <array> int main() { constexpr std::array<std::string_view, 8> data = {"▁","▂","▃","▄","▅","▆","▇","█"}; std::array<std::string, std::size(data)> arr; std::copy(data.cbegin(), data.cend(), arr.begin()); // ^ ^ ^ auto print = [](const std::string_view s) { std::cout << s << ' '; }; print("Print 'arr' in direct order using [cbegin, cend):\t"); std::for_each(arr.cbegin(), arr.cend(), print); // ^ ^ print("\n\nPrint 'arr' in reverse order using [crbegin, crend):\t"); std::for_each(arr.crbegin(), arr.crend(), print); // ^^ ^^ print("\n"); } ``` Output: ``` Print 'arr' in direct order using [cbegin, cend): ▁ ▂ ▃ ▄ ▅ ▆ ▇ █ Print 'arr' in reverse order using [crbegin, crend): █ ▇ ▆ ▅ ▄ ▃ ▂ ▁ ``` ### See also | | | | --- | --- | | [rendcrend](rend "cpp/container/array/rend") (C++11) | returns a reverse iterator to the end (public member function) | | [rbegincrbegin](../../iterator/rbegin "cpp/iterator/rbegin") (C++14) | returns a reverse iterator to the beginning of a container or array (function template) | cpp std::array<T,N>::at std::array<T,N>::at =================== | | | | | --- | --- | --- | | ``` reference at( size_type pos ); ``` | | (until C++17) | | ``` constexpr reference at( size_type pos ); ``` | | (since C++17) | | ``` const_reference at( size_type pos ) const; ``` | | (until C++14) | | ``` constexpr const_reference at( size_type pos ) const; ``` | | (since C++14) | Returns a reference to the element at specified location `pos`, with bounds checking. If `pos` is not within the range of the container, an exception of type `[std::out\_of\_range](../../error/out_of_range "cpp/error/out of range")` is thrown. ### Parameters | | | | | --- | --- | --- | | pos | - | position of the element to return | ### Return value Reference to the requested element. ### Exceptions `[std::out\_of\_range](../../error/out_of_range "cpp/error/out of range")` if `!(pos < size())`. ### Complexity Constant. ### Example ``` #include <iostream> #include <array> int main() { std::array<int,6> data = { 1, 2, 4, 5, 5, 6 }; // Set element 1 data.at(1) = 88; // Read element 2 std::cout << "Element at index 2 has value " << data.at(2) << '\n'; std::cout << "data size = " << data.size() << '\n'; try { // Set element 6 data.at(6) = 666; } catch (std::out_of_range const& exc) { std::cout << exc.what() << '\n'; } // Print final values std::cout << "data:"; for (int elem : data) std::cout << " " << elem; std::cout << '\n'; } ``` Possible output: ``` Element at index 2 has value 4 data size = 6 array::at: __n (which is 6) >= _Nm (which is 6) data: 1 88 4 5 5 6 ``` ### See also | | | | --- | --- | | [operator[]](operator_at "cpp/container/array/operator at") (C++11) | access specified element (public member function) |
programming_docs
cpp std::array<T,N>::operator[] std::array<T,N>::operator[] =========================== | | | | | --- | --- | --- | | ``` reference operator[]( size_type pos ); ``` | | (until C++17) | | ``` constexpr reference operator[]( size_type pos ); ``` | | (since C++17) | | ``` const_reference operator[]( size_type pos ) const; ``` | | (until C++14) | | ``` constexpr const_reference operator[]( size_type pos ) const; ``` | | (since C++14) | Returns a reference to the element at specified location `pos`. No bounds checking is performed. ### Parameters | | | | | --- | --- | --- | | pos | - | position of the element to return | ### Return value Reference to the requested element. ### Complexity Constant. ### Notes Unlike `[std::map::operator[]](../map/operator_at "cpp/container/map/operator at")`, this operator never inserts a new element into the container. Accessing a nonexistent element through this operator is undefined behavior. ### Example The following code uses `operator[]` to read from and write to a `[std::array](http://en.cppreference.com/w/cpp/container/array)<int>`: ``` #include <array> #include <iostream> int main() { std::array<int,4> numbers {2, 4, 6, 8}; std::cout << "Second element: " << numbers[1] << '\n'; numbers[0] = 5; std::cout << "All numbers:"; for (auto i : numbers) { std::cout << ' ' << i; } std::cout << '\n'; } ``` Output: ``` Second element: 4 All numbers: 5 4 6 8 ``` ### See also | | | | --- | --- | | [at](at "cpp/container/array/at") (C++11) | access specified element with bounds checking (public member function) | cpp std::array<T,N>::swap std::array<T,N>::swap ===================== | | | | | --- | --- | --- | | ``` void swap( array& other ) noexcept(/* see below */); ``` | | (since C++11) (until C++20) | | ``` constexpr void swap( array& other ) noexcept(/* see below */); ``` | | (since C++20) | Exchanges the contents of the container with those of `other`. Does not cause iterators and references to associate with the other container. ### Parameters | | | | | --- | --- | --- | | other | - | container to exchange the contents with | ### Return value (none). ### Exceptions | | | | --- | --- | | [`noexcept`](../../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept(noexcept(swap([std::declval](http://en.cppreference.com/w/cpp/utility/declval)<T&>(), [std::declval](http://en.cppreference.com/w/cpp/utility/declval)<T&>())))` In the expression above, the identifier `swap` is looked up in the same manner as the one used by the C++17 `[std::is\_nothrow\_swappable](../../types/is_swappable "cpp/types/is swappable")` trait. | (until C++17) | | [`noexcept`](../../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept([std::is\_nothrow\_swappable\_v](http://en.cppreference.com/w/cpp/types/is_swappable)<T>)` | (since C++17) | For zero-sized arrays, [`noexcept`](../../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept` ### Complexity Linear in size of the container. ### Example ``` #include <array> #include <iostream> template<class Os, class V> Os& operator<<(Os& os, const V& v) { os << "{"; for (auto i : v) os << ' ' << i; return os << " } "; } int main() { std::array<int, 3> a1{1, 2, 3}, a2{4, 5, 6}; auto it1 = a1.begin(); auto it2 = a2.begin(); int& ref1 = a1[1]; int& ref2 = a2[1]; std::cout << a1 << a2 << *it1 << ' ' << *it2 << ' ' << ref1 << ' ' << ref2 << '\n'; a1.swap(a2); std::cout << a1 << a2 << *it1 << ' ' << *it2 << ' ' << ref1 << ' ' << ref2 << '\n'; // Note that after swap iterators and references stay associated with their original // array, e.g. `it1` still points to element a1[0], `ref1` still refers to a1[1]. } ``` Output: ``` { 1 2 3 } { 4 5 6 } 1 4 2 5 { 4 5 6 } { 1 2 3 } 4 1 5 2 ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 2456](https://cplusplus.github.io/LWG/issue2456) | C++11 | the `noexcept` specification is ill-formed | made to work | ### See also | | | | --- | --- | | [std::swap(std::array)](swap2 "cpp/container/array/swap2") (C++11) | specializes the `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | cpp std::array<T,N>::max_size std::array<T,N>::max\_size ========================== | | | | | --- | --- | --- | | ``` constexpr size_type max_size() const noexcept; ``` | | (since C++11) | Returns the maximum number of elements the container is able to hold due to system or library implementation limitations, i.e. `[std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(begin(), end())` for the largest container. ### Parameters (none). ### Return value Maximum number of elements. ### Complexity Constant. ### Notes Because each `std::array<T, N>` is a fixed-size container, the value returned by `max_size` equals `N` (which is also the value returned by `[size](size "cpp/container/array/size")`). ### Example ``` #include <iostream> #include <locale> #include <array> int main() { std::array<char, 10> q; std::cout.imbue(std::locale("en_US.UTF-8")); std::cout << "Maximum size of the std::array is " << q.max_size() << '\n'; } ``` Output: ``` Maximum size of the std::array is 10 ``` ### See also | | | | --- | --- | | [size](size "cpp/container/array/size") (C++11) | returns the number of elements (public member function) | cpp std::array<T,N>::back std::array<T,N>::back ===================== | | | | | --- | --- | --- | | ``` reference back(); ``` | | (until C++17) | | ``` constexpr reference back(); ``` | | (since C++17) | | ``` const_reference back() const; ``` | | (until C++14) | | ``` constexpr const_reference back() const; ``` | | (since C++14) | Returns a reference to the last element in the container. Calling `back` on an empty container causes [undefined behavior](../../language/ub "cpp/language/ub"). ### Parameters (none). ### Return value Reference to the last element. ### Complexity Constant. ### Notes For a non-empty container `c`, the expression `c.back()` is equivalent to `\*[std::prev](http://en.cppreference.com/w/cpp/iterator/prev)(c.end())`. ### Example The following code uses `back` to display the last element of a `[std::array](http://en.cppreference.com/w/cpp/container/array)<char>`: ``` #include <array> #include <iostream> int main() { std::array<char, 6> letters {'a', 'b', 'c', 'd', 'e', 'f'}; if (!letters.empty()) { std::cout << "The last character is '" << letters.back() << "'.\n"; } } ``` Output: ``` The last character is 'f'. ``` ### See also | | | | --- | --- | | [front](front "cpp/container/array/front") (C++11) | access the first element (public member function) | cpp std::array<T,N>::data std::array<T,N>::data ===================== | | | | | --- | --- | --- | | ``` T* data() noexcept; ``` | | (since C++11) (until C++17) | | ``` constexpr T* data() noexcept; ``` | | (since C++17) | | ``` const T* data() const noexcept; ``` | | (since C++11) (until C++17) | | ``` constexpr const T* data() const noexcept; ``` | | (since C++17) | Returns pointer to the underlying array serving as element storage. The pointer is such that range `[``data(); data()+``[size()](size "cpp/container/array/size")``)` is always a valid range, even if the container is empty (`data()` is not dereferenceable in that case). ### Parameters (none). ### Return value Pointer to the underlying element storage. For non-empty containers, the returned pointer compares equal to the address of the first element. ### Complexity Constant. ### Notes If `[size()](size "cpp/container/array/size")` is `​0​`, `data()` may or may not return a null pointer. ### Example ``` #include <cstddef> #include <iostream> #include <span> #include <array> void pointer_func(const int* p, std::size_t size) { std::cout << "data = "; for (std::size_t i = 0; i < size; ++i) std::cout << p[i] << ' '; std::cout << '\n'; } void span_func(std::span<const int> data) // since C++20 { std::cout << "data = "; for (const int e : data) std::cout << e << ' '; std::cout << '\n'; } int main() { std::array<int, 4> container { 1, 2, 3, 4 }; // Prefer container.data() over &container[0] pointer_func(container.data(), container.size()); // std::span (C++20) is a safer alternative to separated pointer/size. span_func({container.data(), container.size()}); } ``` Output: ``` data = 1 2 3 4 data = 1 2 3 4 ``` ### See also | | | | --- | --- | | [front](front "cpp/container/array/front") (C++11) | access the first element (public member function) | | [back](back "cpp/container/array/back") (C++11) | access the last element (public member function) | | [size](size "cpp/container/array/size") (C++11) | returns the number of elements (public member function) | | [span](../span "cpp/container/span") (C++20) | a non-owning view over a contiguous sequence of objects (class template) | | [data](../../iterator/data "cpp/iterator/data") (C++17) | obtains the pointer to the underlying array (function template) | cpp std::swap(std::array) std::swap(std::array) ===================== | Defined in header `[<array>](../../header/array "cpp/header/array")` | | | | --- | --- | --- | | ``` template< class T, std::size_t N > void swap( std::array<T,N>& lhs, std::array<T,N>& rhs ); ``` | | (since C++11) (until C++17) | | ``` template< class T, std::size_t N > void swap( std::array<T,N>& lhs, std::array<T,N>& rhs ) noexcept(/* see below */); ``` | | (since C++17) (until C++20) | | ``` template< class T, std::size_t N > constexpr void swap( std::array<T,N>& lhs, std::array<T,N>& rhs ) noexcept(/* see below */); ``` | | (since C++20) | Specializes the `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` algorithm for `[std::array](http://en.cppreference.com/w/cpp/container/array)`. Swaps the contents of `lhs` and `rhs`. Calls `lhs.swap(rhs)`. | | | | --- | --- | | This overload participates in overload resolution only if `N == 0` or `[std::is\_swappable\_v](http://en.cppreference.com/w/cpp/types/is_swappable)<T>` is `true`. | (since C++17) | ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | containers whose contents to swap | ### Return value (none). ### Complexity Linear in size of the container. ### Exceptions | | | | --- | --- | | [`noexcept`](../../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept(noexcept(lhs.swap(rhs)))` | (since C++17) | ### Notes Although the overloads of `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` for container adaptors are introduced in C++11, container adaptors can already be swapped by `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` in C++98. Such calls to `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` usually have linear time complexity, but better complexity may be provided. ### Example ``` #include <algorithm> #include <iostream> #include <array> int main() { std::array<int, 3> alice{1, 2, 3}; std::array<int, 3> bob{7, 8, 9}; auto print = [](const int& n) { std::cout << ' ' << n; }; // Print state before swap std::cout << "alice:"; std::for_each(alice.begin(), alice.end(), print); std::cout << "\n" "bob :"; std::for_each(bob.begin(), bob.end(), print); std::cout << '\n'; std::cout << "-- SWAP\n"; std::swap(alice, bob); // Print state after swap std::cout << "alice:"; std::for_each(alice.begin(), alice.end(), print); std::cout << "\n" "bob :"; std::for_each(bob.begin(), bob.end(), print); std::cout << '\n'; } ``` Output: ``` alice: 1 2 3 bob : 7 8 9 -- SWAP alice: 7 8 9 bob : 1 2 3 ``` ### See also | | | | --- | --- | | [swap](swap "cpp/container/array/swap") (C++11) | swaps the contents (public member function) | cpp std::array<T,N>::front std::array<T,N>::front ====================== | | | | | --- | --- | --- | | ``` reference front(); ``` | | (until C++17) | | ``` constexpr reference front(); ``` | | (since C++17) | | ``` const_reference front() const; ``` | | (until C++14) | | ``` constexpr const_reference front() const; ``` | | (since C++14) | Returns a reference to the first element in the container. Calling `front` on an empty container is undefined. ### Parameters (none). ### Return value reference to the first element. ### Complexity Constant. ### Notes For a container `c`, the expression `c.front()` is equivalent to `*c.begin()`. ### Example The following code uses `front` to display the first element of a `[std::array](http://en.cppreference.com/w/cpp/container/array)<char, 6>`: ``` #include <array> #include <iostream> int main() { std::array<char, 6> letters {'o', 'm', 'g', 'w', 't', 'f'}; if (!letters.empty()) { std::cout << "The first character is '" << letters.front() << "'.\n"; } } ``` Output: ``` The first character is 'o'. ``` ### See also | | | | --- | --- | | [back](back "cpp/container/array/back") (C++11) | access the last element (public member function) | cpp std::array<T,N>::rend, std::array<T,N>::crend std::array<T,N>::rend, std::array<T,N>::crend ============================================= | | | | | --- | --- | --- | | ``` reverse_iterator rend() noexcept; ``` | | (until C++17) | | ``` constexpr reverse_iterator rend() noexcept; ``` | | (since C++17) | | ``` const_reverse_iterator rend() const noexcept; ``` | | (until C++17) | | ``` constexpr const_reverse_iterator rend() const noexcept; ``` | | (since C++17) | | ``` const_reverse_iterator crend() const noexcept; ``` | | (until C++17) | | ``` constexpr const_reverse_iterator crend() const noexcept; ``` | | (since C++17) | Returns a reverse iterator to the element following the last element of the reversed `array`. It corresponds to the element preceding the first element of the non-reversed `array`. This element acts as a placeholder, attempting to access it results in undefined behavior. ![range-rbegin-rend.svg]() ### Parameters (none). ### Return value Reverse iterator to the element following the last element. ### Complexity Constant. ### Example ``` #include <algorithm> #include <array> #include <iostream> int main() { std::array<int, 11> a {1, 11, 11, 35, 0, 12, 79, 76, 76, 69, 40}; // print elements of array in reverse order using const_reverse_iterator`s std::for_each(a.crbegin(), a.crend(), [](int e){ std::cout << e << ' '; }); // ^^ ^^ std::cout << '\n'; // modify each element of array using non-const reverse_iterator`s std::for_each(a.rbegin(), a.rend(), [](int& e){ e += 32; }); // ^ ^ ^ // print elements as chars in reverse order using const_reverse_iterator`s std::for_each(a.crbegin(), a.crend(), [](char e){ std::cout << e; }); // ^^ ^^ ^^^^ std::cout << '\n'; } ``` Output: ``` 40 69 76 76 79 12 0 35 11 11 1 Hello, C++! ``` ### See also | | | | --- | --- | | [rbegincrbegin](rbegin "cpp/container/array/rbegin") (C++11) | returns a reverse iterator to the beginning (public member function) | | [rendcrend](../../iterator/rend "cpp/iterator/rend") (C++14) | returns a reverse end iterator for a container or array (function template) | cpp std::tuple_size(std::array) std::tuple\_size(std::array) ============================ | Defined in header `[<array>](../../header/array "cpp/header/array")` | | | | --- | --- | --- | | ``` template< class T, std::size_t N > struct tuple_size< std::array<T, N> > : std::integral_constant<std::size_t, N> { }; ``` | | (since C++11) | Provides access to the number of elements in an `[std::array](../array "cpp/container/array")` as a compile-time constant expression. Inherited from [std::integral\_constant](../../types/integral_constant "cpp/types/integral constant") ------------------------------------------------------------------------------------------------------- ### Member constants | | | | --- | --- | | value [static] | `N`, the number of elements in the array (public static member constant) | ### Member functions | | | | --- | --- | | operator std::size\_t | converts the object to `[std::size\_t](http://en.cppreference.com/w/cpp/types/size_t)`, returns `value` (public member function) | | operator() (C++14) | returns `value` (public member function) | ### Member types | Type | Definition | | --- | --- | | `value_type` | `std::size_t` | | `type` | `[std::integral\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<[std::size\_t](http://en.cppreference.com/w/cpp/types/size_t), value>` | ### Example ``` #include <iostream> #include <array> template<class T> void test(T) { int a[std::tuple_size<T>::value]; // can be used at compile time std::cout << std::size(a) << '\n'; } int main() { std::array<float, 3> arr; test(arr); } ``` Output: ``` 3 ``` ### See also | | | | --- | --- | | [Structured binding](../../language/structured_binding "cpp/language/structured binding") (C++17) | binds the specified names to sub-objects or tuple elements of the initializer | | [std::tuple\_size<std::tuple>](../../utility/tuple/tuple_size "cpp/utility/tuple/tuple size") (C++11) | obtains the size of `tuple` at compile time (class template specialization) | cpp std::array<T,N>::empty std::array<T,N>::empty ====================== | | | | | --- | --- | --- | | ``` constexpr bool empty() const noexcept; ``` | | (since C++11) (until C++20) | | ``` [[nodiscard]] constexpr bool empty() const noexcept; ``` | | (since C++20) | Checks if the container has no elements, i.e. whether `begin() == end()`. ### Parameters (none). ### Return value `true` if the container is empty, `false` otherwise. ### Complexity Constant. ### Example The following code uses `empty` to check if a `[std::array](../array "cpp/container/array")` contains any elements: ``` #include <array> #include <iostream> int main() { std::array<int, 4> numbers {3, 1, 4, 1}; std::array<int, 0> no_numbers; std::cout << std::boolalpha; std::cout << "numbers.empty(): " << numbers.empty() << '\n'; std::cout << "no_numbers.empty(): " << no_numbers.empty() << '\n'; } ``` Output: ``` numbers.empty(): false no_numbers.empty(): true ``` ### See also | | | | --- | --- | | [size](size "cpp/container/array/size") (C++11) | returns the number of elements (public member function) | | [empty](../../iterator/empty "cpp/iterator/empty") (C++17) | checks whether the container is empty (function template) | cpp std::get(std::array) std::get(std::array) ==================== | Defined in header `[<array>](../../header/array "cpp/header/array")` | | | | --- | --- | --- | | | (1) | | | ``` template< std::size_t I, class T, std::size_t N > T& get( std::array<T,N>& a ) noexcept; ``` | (since C++11) (until C++14) | | ``` template< std::size_t I, class T, std::size_t N > constexpr T& get( std::array<T,N>& a ) noexcept; ``` | (since C++14) | | | (2) | | | ``` template< std::size_t I, class T, std::size_t N > T&& get( std::array<T,N>&& a ) noexcept; ``` | (since C++11) (until C++14) | | ``` template< std::size_t I, class T, std::size_t N > constexpr T&& get( std::array<T,N>&& a ) noexcept; ``` | (since C++14) | | | (3) | | | ``` template< std::size_t I, class T, std::size_t N > const T& get( const std::array<T,N>& a ) noexcept; ``` | (since C++11) (until C++14) | | ``` template< std::size_t I, class T, std::size_t N > constexpr const T& get( const std::array<T,N>& a ) noexcept; ``` | (since C++14) | | | (4) | | | ``` template< std::size_t I, class T, std::size_t N > const T&& get( const std::array<T,N>&& a ) noexcept; ``` | (since C++11) (until C++14) | | ``` template< std::size_t I, class T, std::size_t N > constexpr const T&& get( const std::array<T,N>&& a ) noexcept; ``` | (since C++14) | Extracts the `Ith` element element from the array. `I` must be an integer value in range `[0, N)`. This is enforced at compile time as opposed to `[at()](at "cpp/container/array/at")` or `[operator[]](operator_at "cpp/container/array/operator at")`. ### Parameters | | | | | --- | --- | --- | | a | - | array whose contents to extract | ### Return value A reference to the `Ith` element of `a`. ### Complexity Constant. ### Example ``` #include <iostream> #include <array> int main() { std::array<int, 3> arr; // set values: std::get<0>(arr) = 1; std::get<1>(arr) = 2; std::get<2>(arr) = 3; // get values: std::cout << "(" << std::get<0>(arr) << ", " << std::get<1>(arr) << ", " << std::get<2>(arr) << ")\n"; } ``` Output: ``` (1, 2, 3) ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 2485](https://cplusplus.github.io/LWG/issue2485) | C++11 | there are no overloads for const array&& | the overloads are added | ### See also | | | | --- | --- | | [Structured binding](../../language/structured_binding "cpp/language/structured binding") (C++17) | binds the specified names to sub-objects or tuple elements of the initializer | | [operator[]](operator_at "cpp/container/array/operator at") (C++11) | access specified element (public member function) | | [at](at "cpp/container/array/at") (C++11) | access specified element with bounds checking (public member function) | | [std::get(std::tuple)](../../utility/tuple/get "cpp/utility/tuple/get") (C++11) | tuple accesses specified element (function template) | | [std::get(std::pair)](../../utility/pair/get "cpp/utility/pair/get") (C++11) | accesses an element of a `pair` (function template) | | [std::get(std::variant)](../../utility/variant/get "cpp/utility/variant/get") (C++17) | reads the value of the variant given the index or the type (if the type is unique), throws on error (function template) | | [get(std::ranges::subrange)](../../ranges/subrange/get "cpp/ranges/subrange/get") (C++20) | obtains iterator or sentinel from a `[std::ranges::subrange](../../ranges/subrange "cpp/ranges/subrange")` (function template) |
programming_docs
cpp std::array<T,N>::begin, std::array<T,N>::cbegin std::array<T,N>::begin, std::array<T,N>::cbegin =============================================== | | | | | --- | --- | --- | | ``` iterator begin() noexcept; ``` | | (until C++17) | | ``` constexpr iterator begin() noexcept; ``` | | (since C++17) | | ``` const_iterator begin() const noexcept; ``` | | (until C++17) | | ``` constexpr const_iterator begin() const noexcept; ``` | | (since C++17) | | ``` const_iterator cbegin() const noexcept; ``` | | (until C++17) | | ``` constexpr const_iterator cbegin() const noexcept; ``` | | (since C++17) | Returns an iterator to the first element of the `array`. If the `array` is empty, the returned iterator will be equal to `[end()](end "cpp/container/array/end")`. ![range-begin-end.svg]() ### Parameters (none). ### Return value Iterator to the first element. ### Complexity Constant. ### Example ``` #include <array> #include <iostream> #include <algorithm> #include <iomanip> int main() { std::cout << std::boolalpha; std::array<int, 0> empty; std::cout << "1) " << (empty.begin() == empty.end()) << ' ' // true << (empty.cbegin() == empty.cend()) << '\n'; // true // *(empty.begin()) = 42; // => undefined behaviour at run-time std::array<int, 4> numbers{5, 2, 3, 4}; std::cout << "2) " << (numbers.begin() == numbers.end()) << ' ' // false << (numbers.cbegin() == numbers.cend()) << '\n' // false << "3) " << *(numbers.begin()) << ' ' // 5 << *(numbers.cbegin()) << '\n'; // 5 *numbers.begin() = 1; std::cout << "4) " << *(numbers.begin()) << '\n'; // 1 // *(numbers.cbegin()) = 42; // compile-time error: // read-only variable is not assignable // print out all elements std::cout << "5) "; std::for_each(numbers.cbegin(), numbers.cend(), [](int x) { std::cout << x << ' '; }); std::cout << '\n'; constexpr std::array constants{'A', 'B', 'C'}; static_assert(constants.begin() != constants.end()); // OK static_assert(constants.cbegin() != constants.cend()); // OK static_assert(*constants.begin() == 'A'); // OK static_assert(*constants.cbegin() == 'A'); // OK // *constants.begin() = 'Z'; // compile-time error: // read-only variable is not assignable } ``` Output: ``` 1) true true 2) false false 3) 5 5 4) 1 5) 1 2 3 4 ``` ### See also | | | | --- | --- | | [end cend](end "cpp/container/array/end") (C++11) | returns an iterator to the end (public member function) | | [begincbegin](../../iterator/begin "cpp/iterator/begin") (C++11)(C++14) | returns an iterator to the beginning of a container or array (function template) | cpp std::array<T,N>::end, std::array<T,N>::cend std::array<T,N>::end, std::array<T,N>::cend =========================================== | | | | | --- | --- | --- | | ``` iterator end() noexcept; ``` | | (until C++17) | | ``` constexpr iterator end() noexcept; ``` | | (since C++17) | | ``` const_iterator end() const noexcept; ``` | | (until C++17) | | ``` constexpr const_iterator end() const noexcept; ``` | | (since C++17) | | ``` const_iterator cend() const noexcept; ``` | | (until C++17) | | ``` constexpr const_iterator cend() const noexcept; ``` | | (since C++17) | Returns an iterator to the element following the last element of the `array`. This element acts as a placeholder; attempting to access it results in undefined behavior. ![range-begin-end.svg]() ### Parameters (none). ### Return value Iterator to the element following the last element. ### Complexity Constant. ### Example ``` #include <array> #include <iostream> #include <algorithm> #include <iomanip> int main() { std::cout << std::boolalpha; std::array<int, 0> empty; std::cout << "1) " << (empty.begin() == empty.end()) << ' ' // true << (empty.cbegin() == empty.cend()) << '\n'; // true // *(empty.begin()) = 42; // => undefined behaviour at run-time std::array<int, 4> numbers{5, 2, 3, 4}; std::cout << "2) " << (numbers.begin() == numbers.end()) << ' ' // false << (numbers.cbegin() == numbers.cend()) << '\n' // false << "3) " << *(numbers.begin()) << ' ' // 5 << *(numbers.cbegin()) << '\n'; // 5 *numbers.begin() = 1; std::cout << "4) " << *(numbers.begin()) << '\n'; // 1 // *(numbers.cbegin()) = 42; // compile-time error: // read-only variable is not assignable // print out all elements std::cout << "5) "; std::for_each(numbers.cbegin(), numbers.cend(), [](int x) { std::cout << x << ' '; }); std::cout << '\n'; constexpr std::array constants{'A', 'B', 'C'}; static_assert(constants.begin() != constants.end()); // OK static_assert(constants.cbegin() != constants.cend()); // OK static_assert(*constants.begin() == 'A'); // OK static_assert(*constants.cbegin() == 'A'); // OK // *constants.begin() = 'Z'; // compile-time error: // read-only variable is not assignable } ``` Output: ``` 1) true true 2) false false 3) 5 5 4) 1 5) 1 2 3 4 ``` ### See also | | | | --- | --- | | [begin cbegin](begin "cpp/container/array/begin") (C++11) | returns an iterator to the beginning (public member function) | | [endcend](../../iterator/end "cpp/iterator/end") (C++11)(C++14) | returns an iterator to the end of a container or array (function template) | cpp std::unordered_set<Key,Hash,KeyEqual,Allocator>::contains std::unordered\_set<Key,Hash,KeyEqual,Allocator>::contains ========================================================== | | | | | --- | --- | --- | | ``` bool contains( const Key& key ) const; ``` | (1) | (since C++20) | | ``` template< class K > bool contains( const K& x ) const; ``` | (2) | (since C++20) | 1) Checks if there is an element with key equivalent to `key` in the container. 2) Checks if there is an element with key that compares *equivalent* to the value `x`. This overload participates in overload resolution only if `Hash::is_transparent` and `KeyEqual::is_transparent` are valid and each denotes a type. This assumes that such `Hash` is callable with both `K` and `Key` type, and that the `KeyEqual` is transparent, which, together, allows calling this function without constructing an instance of `Key`. ### Parameters | | | | | --- | --- | --- | | key | - | key value of the element to search for | | x | - | a value of any type that can be transparently compared with a key | ### Return value `true` if there is such an element, otherwise `false`. ### Complexity Constant on average, worst case linear in the size of the container. ### Example ``` #include <iostream> #include <unordered_set> int main() { std::unordered_set<int> example = {1, 2, 3, 4}; for(int x: {2, 5}) { if(example.contains(x)) { std::cout << x << ": Found\n"; } else { std::cout << x << ": Not found\n"; } } } ``` Output: ``` 2: Found 5: Not found ``` ### See also | | | | --- | --- | | [find](find "cpp/container/unordered set/find") (C++11) | finds element with specific key (public member function) | | [count](count "cpp/container/unordered set/count") (C++11) | returns the number of elements matching specific key (public member function) | | [equal\_range](equal_range "cpp/container/unordered set/equal range") (C++11) | returns range of elements matching a specific key (public member function) | cpp std::unordered_set<Key,Hash,KeyEqual,Allocator>::size std::unordered\_set<Key,Hash,KeyEqual,Allocator>::size ====================================================== | | | | | --- | --- | --- | | ``` size_type size() const noexcept; ``` | | (since C++11) | Returns the number of elements in the container, i.e. `[std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(begin(), end())`. ### Parameters (none). ### Return value The number of elements in the container. ### Complexity Constant. ### Example The following code uses `size` to display the number of elements in a `[std::unordered\_set](http://en.cppreference.com/w/cpp/container/unordered_set)<int>`: ``` #include <unordered_set> #include <iostream> int main() { std::unordered_set<int> nums {1, 3, 5, 7}; std::cout << "nums contains " << nums.size() << " elements.\n"; } ``` Output: ``` nums contains 4 elements. ``` ### See also | | | | --- | --- | | [empty](empty "cpp/container/unordered set/empty") (C++11) | checks whether the container is empty (public member function) | | [max\_size](max_size "cpp/container/unordered set/max size") (C++11) | returns the maximum possible number of elements (public member function) | | [sizessize](../../iterator/size "cpp/iterator/size") (C++17)(C++20) | returns the size of a container or array (function template) | cpp std::unordered_set<Key,Hash,KeyEqual,Allocator>::bucket_count std::unordered\_set<Key,Hash,KeyEqual,Allocator>::bucket\_count =============================================================== | | | | | --- | --- | --- | | ``` size_type bucket_count() const; ``` | | (since C++11) | Returns the number of buckets in the container. ### Parameters (none). ### Return value The number of buckets in the container. ### Complexity Constant. ### See also | | | | --- | --- | | [bucket\_size](bucket_size "cpp/container/unordered set/bucket size") (C++11) | returns the number of elements in specific bucket (public member function) | | [max\_bucket\_count](max_bucket_count "cpp/container/unordered set/max bucket count") (C++11) | returns the maximum number of buckets (public member function) | cpp deduction guides for std::unordered_set deduction guides for `std::unordered_set` ========================================= | Defined in header `[<unordered\_set>](../../header/unordered_set "cpp/header/unordered set")` | | | | --- | --- | --- | | ``` template<class InputIt, class Hash = std::hash<typename std::iterator_traits<InputIt>::value_type>, class Pred = std::equal_to<typename std::iterator_traits<InputIt>::value_type>, class Alloc = std::allocator<typename std::iterator_traits<InputIt>::value_type>> unordered_set(InputIt, InputIt, typename /*see below*/::size_type = /*see below*/, Hash = Hash(), Pred = Pred(), Alloc = Alloc()) -> unordered_set<typename std::iterator_traits<InputIt>::value_type, Hash, Pred, Alloc>; ``` | (1) | (since C++17) | | ``` template<class T, class Hash = std::hash<T>, class Pred = std::equal_to<T>, class Alloc = std::allocator<T>> unordered_set(std::initializer_list<T>, typename /*see below*/::size_type = /*see below*/, Hash = Hash(), Pred = Pred(), Alloc = Alloc()) -> unordered_set<T, Hash, Pred, Alloc>; ``` | (2) | (since C++17) | | ``` template<class InputIt, class Alloc> unordered_set(InputIt, InputIt, typename /*see below*/::size_type, Alloc) -> unordered_set<typename std::iterator_traits<InputIt>::value_type, std::hash<typename std::iterator_traits<InputIt>::value_type>, std::equal_to<typename std::iterator_traits<InputIt>::value_type>, Alloc>; ``` | (3) | (since C++17) | | ``` template<class InputIt, class Hash, class Alloc> unordered_set(InputIt, InputIt, typename /*see below*/::size_type, Hash, Alloc) -> unordered_set<typename std::iterator_traits<InputIt>::value_type, Hash, std::equal_to<typename std::iterator_traits<InputIt>::value_type>, Allocator>; ``` | (4) | (since C++17) | | ``` template<class T, class Allocator> unordered_set(std::initializer_list<T>, typename /*see below*/::size_type, Allocator) -> unordered_set<T, std::hash<T>, std::equal_to<T>, Alloc>; ``` | (5) | (since C++17) | | ``` template<class T, class Hash, class Alloc> unordered_set(std::initializer_list<T>, typename /*see below*/::size_type, Hash, Alloc) -> unordered_set<T, Hash, std::equal_to<T>, Alloc>; ``` | (6) | (since C++17) | These [deduction guides](../../language/class_template_argument_deduction "cpp/language/class template argument deduction") are provided for unordered\_set to allow deduction from an iterator range (overloads (1,3,4)) and `[std::initializer\_list](../../utility/initializer_list "cpp/utility/initializer list")` (overloads (2,5.6)). This overload participates in overload resolution only if `InputIt` satisfies [LegacyInputIterator](../../named_req/inputiterator "cpp/named req/InputIterator"), `Alloc` satisfies [Allocator](../../named_req/allocator "cpp/named req/Allocator"), neither `Hash` nor `Pred` satisfy [Allocator](../../named_req/allocator "cpp/named req/Allocator"), `Hash` is not an integral type. Note: the extent to which the library determines that a type does not satisfy [LegacyInputIterator](../../named_req/inputiterator "cpp/named req/InputIterator") is unspecified, except that as a minimum integral types do not qualify as input iterators. Likewise, the extent to which it determines that a type does not satisfy [Allocator](../../named_req/allocator "cpp/named req/Allocator") is unspecified, except that as a minimum the member type `Alloc::value_type` must exist and the expression `[std::declval](http://en.cppreference.com/w/cpp/utility/declval)<Alloc&>().allocate([std::size\_t](http://en.cppreference.com/w/cpp/types/size_t){})` must be well-formed when treated as an unevaluated operand. The `size_type` parameter type in these guides refers to the `size_type` member type of the type deduced by the deduction guide. ### Example ``` #include <unordered_set> int main() { std::unordered_set s = {1,2,3,4}; // guide #2 deduces std::unordered_set<int> std::unordered_set s2(s.begin(), s.end()); // guide #1 deduces std::unordered_set<int> } ``` cpp std::unordered_set<Key,Hash,KeyEqual,Allocator>::emplace std::unordered\_set<Key,Hash,KeyEqual,Allocator>::emplace ========================================================= | | | | | --- | --- | --- | | ``` template< class... Args > std::pair<iterator,bool> emplace( Args&&... args ); ``` | | (since C++11) | Inserts a new element into the container constructed in-place with the given `args` if there is no element with the key in the container. Careful use of `emplace` allows the new element to be constructed while avoiding unnecessary copy or move operations. The constructor of the new element is called with exactly the same arguments as supplied to `emplace`, forwarded via `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Args>(args)...`. The element may be constructed even if there already is an element with the key in the container, in which case the newly constructed element will be destroyed immediately. If rehashing occurs due to the insertion, all iterators are invalidated. Otherwise iterators are not affected. References are not invalidated. Rehashing occurs only if the new number of elements is greater than `max_load_factor()*bucket_count()`. ### Parameters | | | | | --- | --- | --- | | args | - | arguments to forward to the constructor of the element | ### Return value Returns a pair consisting of an iterator to the inserted element, or the already-existing element if no insertion happened, and a `bool` denoting whether the insertion took place (`true` if insertion happened, `false` if it did not). ### Exceptions If an exception is thrown by any operation, this function has no effect (strong exception guarantee). ### Complexity Amortized constant on average, worst case linear in the size of the container. ### Example ### See also | | | | --- | --- | | [emplace\_hint](emplace_hint "cpp/container/unordered set/emplace hint") (C++11) | constructs elements in-place using a hint (public member function) | | [insert](insert "cpp/container/unordered set/insert") (C++11) | inserts elements or nodes (since C++17) (public member function) | cpp std::unordered_set<Key,Hash,KeyEqual,Allocator>::insert std::unordered\_set<Key,Hash,KeyEqual,Allocator>::insert ======================================================== | | | | | --- | --- | --- | | ``` std::pair<iterator,bool> insert( const value_type& value ); ``` | (1) | (since C++11) | | ``` std::pair<iterator,bool> insert( value_type&& value ); ``` | (2) | (since C++11) | | ``` iterator insert( const_iterator hint, const value_type& value ); ``` | (3) | (since C++11) | | ``` iterator insert( const_iterator hint, value_type&& value ); ``` | (4) | (since C++11) | | ``` template< class InputIt > void insert( InputIt first, InputIt last ); ``` | (5) | (since C++11) | | ``` void insert( std::initializer_list<value_type> ilist ); ``` | (6) | (since C++11) | | ``` insert_return_type insert( node_type&& nh ); ``` | (7) | (since C++17) | | ``` iterator insert( const_iterator hint, node_type&& nh ); ``` | (8) | (since C++17) | Inserts element(s) into the container, if the container doesn't already contain an element with an equivalent key. 1-2) Inserts `value`. 3-4) Inserts `value`, using `hint` as a non-binding suggestion to where the search should start. 5) Inserts elements from range `[first, last)`. If multiple elements in the range have keys that compare equivalent, it is unspecified which element is inserted (pending [LWG2844](https://cplusplus.github.io/LWG/issue2844)). 6) Inserts elements from initializer list `ilist`. If multiple elements in the range have keys that compare equivalent, it is unspecified which element is inserted (pending [LWG2844](https://cplusplus.github.io/LWG/issue2844)). 7) If `nh` is an empty [node handle](../node_handle "cpp/container/node handle"), does nothing. Otherwise, inserts the element owned by `nh` into the container , if the container doesn't already contain an element with a key equivalent to `nh.key()`. The behavior is undefined if `nh` is not empty and `get_allocator() != nh.get_allocator()`. 8) If `nh` is an empty [node handle](../node_handle "cpp/container/node handle"), does nothing and returns the end iterator. Otherwise, inserts the element owned by `nh` into the container, if the container doesn't already contain an element with a key equivalent to `nh.key()`, and returns the iterator pointing to the element with key equivalent to `nh.key()` (regardless of whether the insert succeeded or failed). If the insertion succeeds, `nh` is moved from, otherwise it retains ownership of the element. The element is inserted as close as possible to `hint`. The behavior is undefined if `nh` is not empty and `get_allocator() != nh.get_allocator()`. If rehashing occurs due to the insertion, all iterators are invalidated. Otherwise iterators are not affected. References are not invalidated. Rehashing occurs only if the new number of elements is greater than `max_load_factor()*bucket_count()`. If the insertion is successful, pointers and references to the element obtained while it is held in the node handle are invalidated, and pointers and references obtained to that element before it was extracted become valid. (since C++17). ### Parameters | | | | | --- | --- | --- | | hint | - | iterator, used as a suggestion as to where to insert the content | | value | - | element value to insert | | first, last | - | range of elements to insert | | ilist | - | initializer list to insert the values from | | nh | - | a compatible [node handle](../node_handle "cpp/container/node handle") | | Type requirements | | -`InputIt` must meet the requirements of [LegacyInputIterator](../../named_req/inputiterator "cpp/named req/InputIterator"). | ### Return value 1-2) Returns a pair consisting of an iterator to the inserted element (or to the element that prevented the insertion) and a `bool` denoting whether the insertion took place. 3-4) Returns an iterator to the inserted element, or to the element that prevented the insertion. 5-6) (none) 7) Returns an [`insert_return_type`](../unordered_set#Member_types "cpp/container/unordered set") with the members initialized as follows: * 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()`. 8) End iterator if `nh` was empty, iterator pointing to the inserted element if insertion took place, and iterator pointing to an element with a key equivalent to `nh.key()` if it failed. ### Exceptions 1-4) If an exception is thrown by any operation, the insertion has no effect. ### Complexity 1-4) Average case: `O(1)`, worst case `O(size())` 5-6) Average case: `O(N)`, where N is the number of elements to insert. Worst case: `O(N*size()+N)` 7-8) Average case: `O(1)`, worst case `O(size())` ### Notes The hinted insert (3,4) does not return a boolean in order to be signature-compatible with positional insert on sequential containers, such as `[std::vector::insert](../vector/insert "cpp/container/vector/insert")`. This makes it possible to create generic inserters such as `[std::inserter](../../iterator/inserter "cpp/iterator/inserter")`. One way to check success of a hinted insert is to compare [`size()`](size "cpp/container/unordered set/size") before and after. ### Example ``` #include <unordered_set> #include <iostream> #include <array> std::ostream& operator<< (std::ostream& os, std::unordered_set<int> const& s) { for (os << "[" << s.size() << "] { "; int i : s) os << i << ' '; return os << "}\n"; } int main () { std::unordered_set<int> nums = {2, 3, 4}; std::cout << "Initially: " << nums; auto p = nums.insert (1); // insert element std::cout << "'1' was inserted: " << std::boolalpha << p.second << '\n'; std::cout << "After insertion: " << nums; nums.insert (p.first, 0); // insert with hint std::cout << "After insertion: " << nums; std::array<int, 4> a = {10, 11, 12, 13}; nums.insert (a.begin (), a.end ()); // insert range std::cout << "After insertion: " << nums; nums.insert ({20, 21, 22, 23}); // insert initializer_list std::cout << "After insertion: " << nums; std::unordered_set<int> other_nums = {42, 43}; auto node = other_nums.extract (other_nums.find (42)); nums.insert (std::move (node)); // insert node std::cout << "After insertion: " << nums; node = other_nums.extract (other_nums.find (43)); nums.insert (nums.begin (), std::move (node)); // insert node with hint std::cout << "After insertion: " << nums; } ``` Possible output: ``` Initially: [3] { 4 3 2 } '1' was inserted: true After insertion: [4] { 1 2 3 4 } After insertion: [5] { 0 1 2 3 4 } After insertion: [9] { 13 12 11 10 4 3 2 1 0 } After insertion: [13] { 23 22 13 12 11 10 21 4 20 3 2 1 0 } After insertion: [14] { 42 23 22 13 12 11 10 21 4 20 3 2 1 0 } After insertion: [15] { 43 42 23 22 13 12 11 10 21 4 20 3 2 1 0 } ``` ### See also | | | | --- | --- | | [emplace](emplace "cpp/container/unordered set/emplace") (C++11) | constructs element in-place (public member function) | | [emplace\_hint](emplace_hint "cpp/container/unordered set/emplace hint") (C++11) | constructs elements in-place using a hint (public member function) | | [inserter](../../iterator/inserter "cpp/iterator/inserter") | creates a `[std::insert\_iterator](../../iterator/insert_iterator "cpp/iterator/insert iterator")` of type inferred from the argument (function template) |
programming_docs
cpp std::unordered_set<Key,Hash,KeyEqual,Allocator>::get_allocator std::unordered\_set<Key,Hash,KeyEqual,Allocator>::get\_allocator ================================================================ | | | | | --- | --- | --- | | ``` allocator_type get_allocator() const noexcept; ``` | | (since C++11) | Returns the allocator associated with the container. ### Parameters (none). ### Return value The associated allocator. ### Complexity Constant. cpp std::unordered_set<Key,Hash,KeyEqual,Allocator>::merge std::unordered\_set<Key,Hash,KeyEqual,Allocator>::merge ======================================================= | | | | | --- | --- | --- | | ``` template<class H2, class P2> void merge( std::unordered_set<Key, H2, P2, Allocator>& source ); ``` | (1) | (since C++17) | | ``` template<class H2, class P2> void merge( std::unordered_set<Key, H2, P2, Allocator>&& source ); ``` | (2) | (since C++17) | | ``` template<class H2, class P2> void merge( std::unordered_multiset<Key, H2, P2, Allocator>& source ); ``` | (3) | (since C++17) | | ``` template<class H2, class P2> void merge( std::unordered_multiset<Key, H2, P2, Allocator>&& source ); ``` | (4) | (since C++17) | Attempts to extract ("splice") each element in `source` and insert it into `*this` using the hash function and key equality predicate of `*this`. If there is an element in `*this` with key equivalent to the key of an element from `source`, then that element is not extracted from `source`. No elements are copied or moved, only the internal pointers of the container nodes are repointed. All pointers and references to the transferred elements remain valid, but now refer into `*this`, not into `source`. Iterators referring to the transferred elements and all iterators referring to `*this` are invalidated. Iterators to elements remaining in `source` remain valid. The behavior is undefined if `get_allocator() != source.get_allocator()`. ### Parameters | | | | | --- | --- | --- | | source | - | compatible container to transfer the nodes from | ### Return value (none). ### Complexity Average case O(N), worst case O(N\*size()+N), where N is `source.size()`. ### Example ``` #include <iostream> #include <unordered_set> // print out a container template <class Os, class K> Os& operator<<(Os& os, const std::unordered_set<K>& v) { os << '[' << v.size() << "] {"; bool o{}; for (const auto& e : v) os << (o ? ", " : (o = 1, " ")) << e; return os << " }\n"; } int main() { std::unordered_set<char> p{ 'C', 'B', 'B', 'A' }, q{ 'E', 'D', 'E', 'C' }; std::cout << "p: " << p << "q: " << q; p.merge(q); std::cout << "p.merge(q);\n" << "p: " << p << "q: " << q; } ``` Possible output: ``` p: [3] { A, B, C } q: [3] { C, D, E } p.merge(q); p: [5] { E, D, A, B, C } q: [1] { C } ``` ### See also | | | | --- | --- | | [extract](extract "cpp/container/unordered set/extract") (C++17) | extracts nodes from the container (public member function) | | [insert](insert "cpp/container/unordered set/insert") (C++11) | inserts elements or nodes (since C++17) (public member function) | cpp std::unordered_set<Key,Hash,KeyEqual,Allocator>::extract std::unordered\_set<Key,Hash,KeyEqual,Allocator>::extract ========================================================= | | | | | --- | --- | --- | | ``` node_type extract( const_iterator position ); ``` | (1) | (since C++17) | | ``` node_type extract( const Key& k ); ``` | (2) | (since C++17) | | ``` template< class K > node_type extract( K&& x ); ``` | (3) | (since C++23) | 1) Unlinks the node that contains the element pointed to by `position` and returns a [node handle](../node_handle "cpp/container/node handle") that owns it. 2) If the container has an element with key equivalent to `k`, unlinks the node that contains that element from the container and returns a [node handle](../node_handle "cpp/container/node handle") that owns it. Otherwise, returns an empty node handle. 3) Same as (2). This overload participates in overload resolution only if `Hash::is_transparent` and `KeyEqual::is_transparent` are valid and each denotes a type, and neither `iterator` nor `const_iterator` is implicitly convertible from `K`. This assumes that such `Hash` is callable with both `K` and `Key` type, and that the `KeyEqual` is transparent, which, together, allows calling this function without constructing an instance of `Key`. In either case, no elements are copied or moved, only the internal pointers of the container nodes are repointed . Extracting a node invalidates only the iterators to the extracted element, and preserves the relative order of the elements that are not erased. Pointers and references to the extracted element remain valid, but cannot be used while element is owned by a node handle: they become usable if the element is inserted into a container. ### Parameters | | | | | --- | --- | --- | | position | - | a valid iterator into this container | | k | - | a key to identify the node to be extracted | | x | - | a value of any type that can be transparently compared with a key identifying the node to be extracted | ### Return value A [node handle](../node_handle "cpp/container/node handle") that owns the extracted element, or empty node handle in case the element is not found in (2,3). ### Exceptions 1) Throws nothing. 2,3) Any exceptions thrown by the `Hash` and `KeyEqual` object. ### Complexity 1,2,3) Average case O(1), worst case O(`a.size()`). ### Notes extract is the only way to take a move-only object out of a set. ``` std::set<move_only_type> s; s.emplace(...); move_only_type mot = std::move(s.extract(s.begin()).value()); ``` | [Feature-test](../../utility/feature_test "cpp/utility/feature test") macro | Comment | | --- | --- | | [`__cpp_lib_associative_heterogeneous_erasure`](../../feature_test#Library_features "cpp/feature test") | for overload (3) | ### Example ``` #include <algorithm> #include <iostream> #include <string_view> #include <unordered_set> void print(std::string_view comment, const auto& data) { std::cout << comment; for (auto datum : data) std::cout << ' ' << datum; std::cout << '\n'; } int main() { std::unordered_set<int> cont{1, 2, 3}; print("Start:", cont); // Extract node handle and change key auto nh = cont.extract(1); nh.value() = 4; print("After extract and before insert:", cont); // Insert node handle back cont.insert(std::move(nh)); print("End:", cont); } ``` Possible output: ``` Start: 1 2 3 After extract and before insert: 2 3 End: 2 3 4 ``` ### See also | | | | --- | --- | | [merge](merge "cpp/container/unordered set/merge") (C++17) | splices nodes from another container (public member function) | | [insert](insert "cpp/container/unordered set/insert") (C++11) | inserts elements or nodes (since C++17) (public member function) | | [erase](erase "cpp/container/unordered set/erase") (C++11) | erases elements (public member function) | cpp std::unordered_set<Key,Hash,KeyEqual,Allocator>::max_load_factor std::unordered\_set<Key,Hash,KeyEqual,Allocator>::max\_load\_factor =================================================================== | | | | | --- | --- | --- | | ``` float max_load_factor() const; ``` | (1) | (since C++11) | | ``` void max_load_factor( float ml ); ``` | (2) | (since C++11) | Manages the maximum load factor (number of elements per bucket). The container automatically increases the number of buckets if the load factor exceeds this threshold. 1) Returns current maximum load factor. 2) Sets the maximum load factor to `ml`. ### Parameters | | | | | --- | --- | --- | | ml | - | new maximum load factor setting | ### Return value 1) current maximum load factor. 2) none. ### Complexity Constant. ### See also | | | | --- | --- | | [load\_factor](load_factor "cpp/container/unordered set/load factor") (C++11) | returns average number of elements per bucket (public member function) | cpp std::unordered_set<Key,Hash,KeyEqual,Allocator>::emplace_hint std::unordered\_set<Key,Hash,KeyEqual,Allocator>::emplace\_hint =============================================================== | | | | | --- | --- | --- | | ``` template <class... Args> iterator emplace_hint( const_iterator hint, Args&&... args ); ``` | | (since C++11) | Inserts a new element to the container, using `hint` as a suggestion where the element should go. The element is constructed in-place, i.e. no copy or move operations are performed. The constructor of the element is called with exactly the same arguments as supplied to the function, forwarded with `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Args>(args)...`. If rehashing occurs due to the insertion, all iterators are invalidated. Otherwise iterators are not affected. References are not invalidated. Rehashing occurs only if the new number of elements is greater than `max_load_factor()*bucket_count()`. ### Parameters | | | | | --- | --- | --- | | hint | - | iterator, used as a suggestion as to where to insert the new element | | args | - | arguments to forward to the constructor of the element | ### Return value Returns an iterator to the newly inserted element. If the insertion failed because the element already exists, returns an iterator to the already existing element with the equivalent key. ### Exceptions If an exception is thrown by any operation, this function has no effect (strong exception guarantee). ### Complexity Amortized constant on average, worst case linear in the size of the container. ### Example ### See also | | | | --- | --- | | [emplace](emplace "cpp/container/unordered set/emplace") (C++11) | constructs element in-place (public member function) | | [insert](insert "cpp/container/unordered set/insert") (C++11) | inserts elements or nodes (since C++17) (public member function) | cpp std::unordered_set<Key,Hash,KeyEqual,Allocator>::hash_function std::unordered\_set<Key,Hash,KeyEqual,Allocator>::hash\_function ================================================================ | | | | | --- | --- | --- | | ``` hasher hash_function() const; ``` | | (since C++11) | Returns the function that hashes the keys. ### Parameters (none). ### Return value The hash function. ### Complexity Constant. ### See also | | | | --- | --- | | [key\_eq](key_eq "cpp/container/unordered set/key eq") (C++11) | returns the function used to compare keys for equality (public member function) | cpp std::unordered_set<Key,Hash,KeyEqual,Allocator>::swap std::unordered\_set<Key,Hash,KeyEqual,Allocator>::swap ====================================================== | | | | | --- | --- | --- | | ``` void swap( unordered_set& other ); ``` | | (since C++11) (until C++17) | | ``` void swap( unordered_set& other ) noexcept(/* see below */); ``` | | (since C++17) | Exchanges the contents of the container with those of `other`. Does not invoke any move, copy, or swap operations on individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated. The `Hash` and `KeyEqual` objects must be [Swappable](../../named_req/swappable "cpp/named req/Swappable"), and they are exchanged using unqualified calls to non-member `swap`. | | | | --- | --- | | If `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<allocator_type>::propagate\_on\_container\_swap::value` is true, then the allocators are exchanged using an unqualified call to non-member `swap`. Otherwise, they are not swapped (and if `get_allocator() != other.get_allocator()`, the behavior is undefined). | (since C++11) | ### Parameters | | | | | --- | --- | --- | | other | - | container to exchange the contents with | ### Return value (none). ### Exceptions | | | | --- | --- | | Any exception thrown by the swap of the `Hash` or `KeyEqual` objects. | (until C++17) | | [`noexcept`](../../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept([std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<Allocator>::is\_always\_equal::value && [std::is\_nothrow\_swappable](http://en.cppreference.com/w/cpp/types/is_swappable)<Hash>::value. && [std::is\_nothrow\_swappable](http://en.cppreference.com/w/cpp/types/is_swappable)<key_equal>::value)` | (since C++17) | ### Complexity Constant. ### Example ``` #include <iostream> #include <unordered_set> template<class Os, class Co> Os& operator<<(Os& os, const Co& co) { os << "{"; for (auto const& i : co) { os << ' ' << i; } return os << " } "; } int main() { std::unordered_set<int> a1{3, 1, 3, 2}, a2{5, 4, 5}; auto it1 = std::next(a1.begin()); auto it2 = std::next(a2.begin()); const int& ref1 = *(a1.begin()); const int& ref2 = *(a2.begin()); std::cout << a1 << a2 << *it1 << ' ' << *it2 << ' ' << ref1 << ' ' << ref2 << '\n'; a1.swap(a2); std::cout << a1 << a2 << *it1 << ' ' << *it2 << ' ' << ref1 << ' ' << ref2 << '\n'; // Note that every iterator referring to an element in one container before the swap // refers to the same element in the other container after the swap. Same is true // for references. } ``` Possible output: ``` { 2 1 3 } { 4 5 } 1 5 2 4 { 4 5 } { 2 1 3 } 1 5 2 4 ``` ### See also | | | | --- | --- | | [std::swap(std::unordered\_set)](swap2 "cpp/container/unordered set/swap2") (C++11) | specializes the `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | cpp std::unordered_set<Key,Hash,KeyEqual,Allocator>::max_size std::unordered\_set<Key,Hash,KeyEqual,Allocator>::max\_size =========================================================== | | | | | --- | --- | --- | | ``` size_type max_size() const noexcept; ``` | | (since C++11) | Returns the maximum number of elements the container is able to hold due to system or library implementation limitations, i.e. `[std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(begin(), end())` for the largest container. ### Parameters (none). ### Return value Maximum number of elements. ### Complexity Constant. ### Notes This value typically reflects the theoretical limit on the size of the container, at most `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<difference_type>::max()`. At runtime, the size of the container may be limited to a value smaller than `max_size()` by the amount of RAM available. ### Example ``` #include <iostream> #include <locale> #include <unordered_set> int main() { std::unordered_set<char> q; std::cout.imbue(std::locale("en_US.UTF-8")); std::cout << "Maximum size of a std::unordered_set is " << q.max_size() << '\n'; } ``` Possible output: ``` Maximum size of a std::unordered_set is 768,614,336,404,564,650 ``` ### See also | | | | --- | --- | | [size](size "cpp/container/unordered set/size") (C++11) | returns the number of elements (public member function) | cpp std::unordered_set<Key,Hash,KeyEqual,Allocator>::count std::unordered\_set<Key,Hash,KeyEqual,Allocator>::count ======================================================= | | | | | --- | --- | --- | | ``` size_type count( const Key& key ) const; ``` | (1) | (since C++11) | | ``` template< class K > size_type count( const K& x ) const; ``` | (2) | (since C++20) | 1) Returns the number of elements with key that compares equal to the specified argument `key`, which is either 1 or 0 since this container does not allow duplicates. 2) Returns the number of elements with key that compares equivalent to the specified argument `x`. This overload participates in overload resolution only if `Hash::is_transparent` and `KeyEqual::is_transparent` are valid and each denotes a type. This assumes that such `Hash` is callable with both `K` and `Key` type, and that the `KeyEqual` is transparent, which, together, allows calling this function without constructing an instance of `Key`. ### Parameters | | | | | --- | --- | --- | | key | - | key value of the elements to count | | x | - | a value of any type that can be transparently compared with a key | ### Return value 1) Number of elements with key `key`, that is either 1 or 0. 2) Number of elements with key that compares equivalent to `x`. ### Complexity Constant on average, worst case linear in the size of the container. ### Notes | [Feature-test](../../utility/feature_test "cpp/utility/feature test") macro | Comment | | --- | --- | | [`__cpp_lib_generic_unordered_lookup`](../../feature_test#Library_features "cpp/feature test") | for overload (2) | ### Example ``` #include <algorithm> #include <iostream> #include <unordered_set> int main() { std::unordered_set set{2, 7, 1, 8, 2, 8, 1, 8, 2, 8}; std::cout << "The set is: "; for (int e: set) { std::cout << e << ' '; } const auto [min, max] = std::ranges::minmax(set); std::cout << "\nNumbers from " << min << " to " << max << " that are in the set: "; for (int i{min}; i <= max; ++i) { if (set.count(i) == 1) { std::cout << i << ' '; } } } ``` Possible output: ``` The set is: 8 1 7 2 Numbers from 1 to 8 that are in the set: 1 2 7 8 ``` ### See also | | | | --- | --- | | [find](find "cpp/container/unordered set/find") (C++11) | finds element with specific key (public member function) | | [contains](contains "cpp/container/unordered set/contains") (C++20) | checks if the container contains element with specific key (public member function) | | [equal\_range](equal_range "cpp/container/unordered set/equal range") (C++11) | returns range of elements matching a specific key (public member function) | cpp std::unordered_set<Key,Hash,KeyEqual,Allocator>::bucket_size std::unordered\_set<Key,Hash,KeyEqual,Allocator>::bucket\_size ============================================================== | | | | | --- | --- | --- | | ``` size_type bucket_size( size_type n ) const; ``` | | (since C++11) | Returns the number of elements in the bucket with index `n`. ### Parameters | | | | | --- | --- | --- | | n | - | the index of the bucket to examine | ### Return value The number of elements in the bucket `n`. ### Complexity Linear in the size of the bucket `n`. ### See also | | | | --- | --- | | [bucket\_count](bucket_count "cpp/container/unordered set/bucket count") (C++11) | returns the number of buckets (public member function) | cpp std::unordered_set<Key,Hash,KeyEqual,Allocator>::max_bucket_count std::unordered\_set<Key,Hash,KeyEqual,Allocator>::max\_bucket\_count ==================================================================== | | | | | --- | --- | --- | | ``` size_type max_bucket_count() const; ``` | | (since C++11) | Returns the maximum number of buckets the container is able to hold due to system or library implementation limitations. ### Parameters (none). ### Return value Maximum number of buckets. ### Complexity Constant. ### Example ``` #include <iostream> #include <unordered_set> int main() { struct Ha { std::size_t operator()(long x) const { return std::hash<long>{}(x); }; }; auto c1 = std::unordered_set<char>{}; auto c2 = std::unordered_set<long>{}; auto c3 = std::unordered_set<long, std::hash<int>>{}; auto c4 = std::unordered_set<long, Ha>{}; std::cout << "Max bucket count of\n" << std::hex << std::showbase << "c1: " << c1.max_bucket_count() << '\n' << "c2: " << c2.max_bucket_count() << '\n' << "c3: " << c3.max_bucket_count() << '\n' << "c4: " << c4.max_bucket_count() << '\n' ; } ``` Possible output: ``` Max bucket count of c1: 0xfffffffffffffff c2: 0xfffffffffffffff c3: 0xfffffffffffffff c4: 0xaaaaaaaaaaaaaaa ``` ### See also | | | | --- | --- | | [bucket\_count](bucket_count "cpp/container/unordered set/bucket count") (C++11) | returns the number of buckets (public member function) |
programming_docs
cpp std::unordered_set<Key,Hash,KeyEqual,Allocator>::unordered_set std::unordered\_set<Key,Hash,KeyEqual,Allocator>::unordered\_set ================================================================ | | | | | --- | --- | --- | | ``` unordered_set() : unordered_set( size_type(/*implementation-defined*/) ) {} explicit unordered_set( size_type bucket_count, const Hash& hash = Hash(), const key_equal& equal = key_equal(), const Allocator& alloc = Allocator() ); ``` | (1) | (since C++11) | | ``` unordered_set( size_type bucket_count, const Allocator& alloc ) : unordered_set(bucket_count, Hash(), key_equal(), alloc) {} unordered_set( size_type bucket_count, const Hash& hash, const Allocator& alloc ) : unordered_set(bucket_count, hash, key_equal(), alloc) {} ``` | (1) | (since C++14) | | ``` explicit unordered_set( const Allocator& alloc ); ``` | (1) | (since C++11) | | ``` template< class InputIt > unordered_set( InputIt first, InputIt last, size_type bucket_count = /*implementation-defined*/, const Hash& hash = Hash(), const key_equal& equal = key_equal(), const Allocator& alloc = Allocator() ); ``` | (2) | (since C++11) | | ``` template< class InputIt > unordered_set( InputIt first, InputIt last, size_type bucket_count, const Allocator& alloc ) : unordered_set(first, last, bucket_count, Hash(), key_equal(), alloc) {} ``` | (2) | (since C++14) | | ``` template< class InputIt > unordered_set( InputIt first, InputIt last, size_type bucket_count, const Hash& hash, const Allocator& alloc ) : unordered_set(first, last, bucket_count, hash, key_equal(), alloc) {} ``` | (2) | (since C++14) | | ``` unordered_set( const unordered_set& other ); ``` | (3) | (since C++11) | | ``` unordered_set( const unordered_set& other, const Allocator& alloc ); ``` | (3) | (since C++11) | | ``` unordered_set( unordered_set&& other ); ``` | (4) | (since C++11) | | ``` unordered_set( unordered_set&& other, const Allocator& alloc ); ``` | (4) | (since C++11) | | ``` unordered_set( std::initializer_list<value_type> init, size_type bucket_count = /*implementation-defined*/, const Hash& hash = Hash(), const key_equal& equal = key_equal(), const Allocator& alloc = Allocator() ); ``` | (5) | (since C++11) | | ``` unordered_set( std::initializer_list<value_type> init, size_type bucket_count, const Allocator& alloc ) : unordered_set(init, bucket_count, Hash(), key_equal(), alloc) {} ``` | (5) | (since C++14) | | ``` unordered_set( std::initializer_list<value_type> init, size_type bucket_count, const Hash& hash, const Allocator& alloc ) : unordered_set(init, bucket_count, hash, key_equal(), alloc) {} ``` | (5) | (since C++14) | Constructs new container from a variety of data sources. Optionally uses user supplied `bucket_count` as a minimal number of buckets to create, `hash` as the hash function, `equal` as the function to compare keys and `alloc` as the allocator. 1) Constructs empty container. Sets `[max\_load\_factor()](max_load_factor "cpp/container/unordered set/max load factor")` to 1.0. For the default constructor, the number of buckets is implementation-defined. 2) constructs the container with the contents of the range `[first, last)`. Sets `[max\_load\_factor()](max_load_factor "cpp/container/unordered set/max load factor")` to 1.0. If multiple elements in the range have keys that compare equivalent, it is unspecified which element is inserted (pending [LWG2844](https://cplusplus.github.io/LWG/issue2844)). 3) copy constructor. Constructs the container with the copy of the contents of `other`, copies the load factor, the predicate, and the hash function as well. If `alloc` is not provided, allocator is obtained by calling `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<allocator_type>::select\_on\_container\_copy\_construction(other.get\_allocator())`. | | | | --- | --- | | The template parameter `Allocator` is only deduced from the first argument while used in [class template argument deduction](../../language/class_template_argument_deduction "cpp/language/class template argument deduction"). | (since C++23) | 4) move constructor. Constructs the container with the contents of `other` using move semantics. If `alloc` is not provided, allocator is obtained by move-construction from the allocator belonging to `other`. | | | | --- | --- | | The template parameter `Allocator` is only deduced from the first argument while used in [class template argument deduction](../../language/class_template_argument_deduction "cpp/language/class template argument deduction"). | (since C++23) | 5) constructs the container with the contents of the initializer list `init`, same as `unordered_set(init.begin(), init.end())`. ### Parameters | | | | | --- | --- | --- | | alloc | - | allocator to use for all memory allocations of this container | | bucket\_count | - | minimal number of buckets to use on initialization. If it is not specified, implementation-defined default value is used | | hash | - | hash function to use | | equal | - | comparison function to use for all key comparisons of this container | | first, last | - | the range to copy the elements from | | other | - | another container to be used as source to initialize the elements of the container with | | init | - | initializer list to initialize the elements of the container with | | Type requirements | | -`InputIt` must meet the requirements of [LegacyInputIterator](../../named_req/inputiterator "cpp/named req/InputIterator"). | ### Complexity 1) constant 2) average case linear worst case quadratic in distance between `first` and `last` 3) linear in size of `other` 4) constant. If `alloc` is given and `alloc != other.get_allocator()`, then linear. 5) average case linear worst case quadratic in size of `init` ### Exceptions Calls to `Allocator::allocate` may throw. ### Notes After container move construction (overload (4)), references, pointers, and iterators (other than the end iterator) to `other` remain valid, but refer to elements that are now in `*this`. The current standard makes this guarantee via the blanket statement in [[container.requirements.general]/12](https://eel.is/c++draft/container.requirements.general#12), and a more direct guarantee is under consideration via [LWG 2321](https://cplusplus.github.io/LWG/issue2321). Although not formally required until C++23, some implementations has already put the template parameter `Allocator` into [non-deduced contexts](../../language/template_argument_deduction#Non-deduced_contexts "cpp/language/template argument deduction") in earlier modes. ### Example ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 2193](https://cplusplus.github.io/LWG/issue2193) | C++11 | the default constructor is explicit | made non-explicit | ### See also | | | | --- | --- | | [operator=](operator= "cpp/container/unordered set/operator=") (C++11) | assigns values to the container (public member function) | cpp std::unordered_set<Key,Hash,KeyEqual,Allocator>::find std::unordered\_set<Key,Hash,KeyEqual,Allocator>::find ====================================================== | | | | | --- | --- | --- | | ``` iterator find( const Key& key ); ``` | (1) | | | ``` const_iterator find( const Key& key ) const; ``` | (2) | | | ``` template< class K > iterator find( const K& x ); ``` | (3) | (since C++20) | | ``` template< class K > const_iterator find( const K& x ) const; ``` | (4) | (since C++20) | 1,2) Finds an element with key equivalent to `key`. 3,4) Finds an element with key that compares *equivalent* to the value `x`. This overload participates in overload resolution only if `Hash::is_transparent` and `KeyEqual::is_transparent` are valid and each denotes a type. This assumes that such `Hash` is callable with both `K` and `Key` type, and that the `KeyEqual` is transparent, which, together, allows calling this function without constructing an instance of `Key`. ### Parameters | | | | | --- | --- | --- | | key | - | key value of the element to search for | | x | - | a value of any type that can be transparently compared with a key | ### Return value Iterator to an element with key equivalent to `key`. If no such element is found, past-the-end (see `[end()](end "cpp/container/unordered set/end")`) iterator is returned. ### Complexity Constant on average, worst case linear in the size of the container. ### Notes | [Feature-test](../../utility/feature_test "cpp/utility/feature test") macro | Comment | | --- | --- | | [`__cpp_lib_generic_unordered_lookup`](../../feature_test#Library_features "cpp/feature test") | for overloads (3,4) | ### Example ``` #include <iostream> #include <unordered_set> int main() { // simple comparison demo std::unordered_set<int> example = {1, 2, 3, 4}; auto search = example.find(2); if (search != example.end()) { std::cout << "Found " << (*search) << '\n'; } else { std::cout << "Not found\n"; } } ``` Output: ``` Found 2 ``` ### See also | | | | --- | --- | | [count](count "cpp/container/unordered set/count") (C++11) | returns the number of elements matching specific key (public member function) | | [equal\_range](equal_range "cpp/container/unordered set/equal range") (C++11) | returns range of elements matching a specific key (public member function) | cpp std::unordered_set<Key,Hash,KeyEqual,Allocator>::equal_range std::unordered\_set<Key,Hash,KeyEqual,Allocator>::equal\_range ============================================================== | | | | | --- | --- | --- | | ``` std::pair<iterator,iterator> equal_range( const Key& key ); ``` | (1) | (since C++11) | | ``` std::pair<const_iterator,const_iterator> equal_range( const Key& key ) const; ``` | (2) | (since C++11) | | ``` template< class K > std::pair<iterator,iterator> equal_range( const K& x ); ``` | (3) | (since C++20) | | ``` template< class K > std::pair<const_iterator,const_iterator> equal_range( const K& x ) const; ``` | (4) | (since C++20) | 1,2) Returns a range containing all elements with key `key` in the container. The range is defined by two iterators, the first pointing to the first element of the wanted range and the second pointing past the last element of the range. 3,4) Returns a range containing all elements in the container with key equivalent to `x`. This overload participates in overload resolution only if `Hash::is_transparent` and `KeyEqual::is_transparent` are valid and each denotes a type. This assumes that such `Hash` is callable with both `K` and `Key` type, and that the `KeyEqual` is transparent, which, together, allows calling this function without constructing an instance of `Key`. ### Parameters | | | | | --- | --- | --- | | key | - | key value to compare the elements to | | x | - | a value of any type that can be transparently compared with a key | ### Return value `[std::pair](../../utility/pair "cpp/utility/pair")` containing a pair of iterators defining the wanted range. If there are no such elements, past-the-end (see `[end()](end "cpp/container/unordered set/end")`) iterators are returned as both elements of the pair. ### Complexity Average case linear in the number of elements with the key `key`, worst case linear in the size of the container. ### Notes | [Feature-test](../../utility/feature_test "cpp/utility/feature test") macro | Comment | | --- | --- | | [`__cpp_lib_generic_unordered_lookup`](../../feature_test#Library_features "cpp/feature test") | for overloads (3,4) | ### Example ### See also | | | | --- | --- | | [find](find "cpp/container/unordered set/find") (C++11) | finds element with specific key (public member function) | | [contains](contains "cpp/container/unordered set/contains") (C++20) | checks if the container contains element with specific key (public member function) | | [count](count "cpp/container/unordered set/count") (C++11) | returns the number of elements matching specific key (public member function) | | [equal\_range](../../algorithm/equal_range "cpp/algorithm/equal range") | returns range of elements matching a specific key (function template) | cpp std::unordered_set<Key,Hash,KeyEqual,Allocator>::erase std::unordered\_set<Key,Hash,KeyEqual,Allocator>::erase ======================================================= | | | | | --- | --- | --- | | | (1) | | | ``` iterator erase( iterator pos ); ``` | (since C++11) | | ``` iterator erase( const_iterator pos ); ``` | (since C++11) | | | (2) | | | ``` iterator erase( const_iterator first, const_iterator last ); ``` | (since C++11) | | ``` size_type erase( const Key& key ); ``` | (3) | (since C++11) | | ``` template< class K > size_type erase( K&& x ); ``` | (4) | (since C++23) | Removes specified elements from the container. 1) Removes the element at `pos`. Only one overload is provided if `iterator` and `const_iterator` are the same type. 2) Removes the elements in the range `[first; last)`, which must be a valid range in `*this`. 3) Removes the element (if one exists) with the key equivalent to `key`. 4) Removes the element (if one exists) with key that compares *equivalent* to the value `x`. This overload participates in overload resolution only if `Hash::is_transparent` and `KeyEqual::is_transparent` are valid and each denotes a type, and neither `iterator` nor `const_iterator` is implicitly convertible from `K`. This assumes that such `Hash` is callable with both `K` and `Key` type, and that the `KeyEqual` is transparent, which, together, allows calling this function without constructing an instance of `Key`. References and iterators to the erased elements are invalidated. Other iterators and references are not invalidated. The iterator `pos` must be valid and dereferenceable. Thus the `[end()](end "cpp/container/unordered set/end")` iterator (which is valid, but is not dereferenceable) cannot be used as a value for `pos`. The order of the elements that are not erased is preserved. (This makes it possible to erase individual elements while iterating through the container.). ### Parameters | | | | | --- | --- | --- | | pos | - | iterator to the element to remove | | first, last | - | range of elements to remove | | key | - | key value of the elements to remove | | x | - | a value of any type that can be transparently compared with a key denoting the elements to remove | ### Return value 1-2) Iterator following the last removed element. 3,4) Number of elements removed (`0` or `1`). ### Exceptions 1,2) Throws nothing. 3,4) Any exceptions thrown by the `Hash` and `KeyEqual` object. ### Complexity Given an instance `c` of `unordered_set`: 1) Average case: constant, worst case: `c.size()` 2) Average case: `[std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(first, last)`, worst case: `c.size()` 3) Average case: `c.count(key)`, worst case: `c.size()` 4) Average case: `c.count(x)`, worst case: `c.size()` ### Notes | [Feature-test](../../utility/feature_test "cpp/utility/feature test") macro | Comment | | --- | --- | | [`__cpp_lib_associative_heterogeneous_erasure`](../../feature_test#Library_features "cpp/feature test") | for overload (4) | ### Example ``` #include <unordered_set> #include <iostream> int main() { std::unordered_set<int> c = { 1, 2, 3, 4, 1, 2, 3, 4 }; auto print = [&c] { std::cout << "c = { "; for(int n : c) std::cout << n << ' '; std::cout << "}\n"; }; print(); std::cout << "Erase all odd numbers:\n"; for(auto it = c.begin(); it != c.end(); ) { if(*it % 2 != 0) it = c.erase(it); else ++it; } print(); std::cout << "Erase 1, erased count: " << c.erase(1) << '\n'; std::cout << "Erase 2, erased count: " << c.erase(2) << '\n'; std::cout << "Erase 2, erased count: " << c.erase(2) << '\n'; print(); } ``` Possible output: ``` c = { 1 2 3 4 } Erase all odd numbers: c = { 2 4 } Erase 1, erased count: 0 Erase 2, erased count: 1 Erase 2, erased count: 0 c = { 4 } ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 2059](https://cplusplus.github.io/LWG/issue2059) | C++11 | overload for one `const_iterator` introduced new ambiguity | overload for `iterator` added | | [LWG 2356](https://cplusplus.github.io/LWG/issue2356) | C++11 | the order of element that are not erased was unspecified | required to be preserved | ### See also | | | | --- | --- | | [clear](clear "cpp/container/unordered set/clear") (C++11) | clears the contents (public member function) | cpp std::unordered_set<Key,Hash,KeyEqual,Allocator>::load_factor std::unordered\_set<Key,Hash,KeyEqual,Allocator>::load\_factor ============================================================== | | | | | --- | --- | --- | | ``` float load_factor() const; ``` | | (since C++11) | Returns the average number of elements per bucket, that is, `[size()](size "cpp/container/unordered set/size")` divided by `[bucket\_count()](bucket_count "cpp/container/unordered set/bucket count")`. ### Parameters (none). ### Return value Average number of elements per bucket. ### Complexity Constant. ### See also | | | | --- | --- | | [max\_load\_factor](max_load_factor "cpp/container/unordered set/max load factor") (C++11) | manages maximum average number of elements per bucket (public member function) | cpp std::swap(std::unordered_set) std::swap(std::unordered\_set) ============================== | Defined in header `[<unordered\_set>](../../header/unordered_set "cpp/header/unordered set")` | | | | --- | --- | --- | | ``` template< class Key, class Hash, class KeyEqual, class Alloc > void swap( std::unordered_set<Key,Hash,KeyEqual,Alloc>& lhs, std::unordered_set<Key,Hash,KeyEqual,Alloc>& rhs ); ``` | | (since C++11) (until C++17) | | ``` template< class Key, class Hash, class KeyEqual, class Alloc > void swap( std::unordered_set<Key,Hash,KeyEqual,Alloc>& lhs, std::unordered_set<Key,Hash,KeyEqual,Alloc>& rhs ) noexcept(/* see below */); ``` | | (since C++17) | Specializes the `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` algorithm for `[std::unordered\_set](http://en.cppreference.com/w/cpp/container/unordered_set)`. Swaps the contents of `lhs` and `rhs`. Calls `lhs.swap(rhs)`. ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | containers whose contents to swap | ### Return value (none). ### Complexity Constant. ### Exceptions | | | | --- | --- | | [`noexcept`](../../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept(noexcept(lhs.swap(rhs)))` | (since C++17) | ### Notes Although the overloads of `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` for container adaptors are introduced in C++11, container adaptors can already be swapped by `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` in C++98. Such calls to `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` usually have linear time complexity, but better complexity may be provided. ### Example ``` #include <algorithm> #include <iostream> #include <unordered_set> int main() { std::unordered_set<int> alice{1, 2, 3}; std::unordered_set<int> bob{7, 8, 9, 10}; auto print = [](const int& n) { std::cout << ' ' << n; }; // Print state before swap std::cout << "alice:"; std::for_each(alice.begin(), alice.end(), print); std::cout << "\n" "bob :"; std::for_each(bob.begin(), bob.end(), print); std::cout << '\n'; std::cout << "-- SWAP\n"; std::swap(alice, bob); // Print state after swap std::cout << "alice:"; std::for_each(alice.begin(), alice.end(), print); std::cout << "\n" "bob :"; std::for_each(bob.begin(), bob.end(), print); std::cout << '\n'; } ``` Possible output: ``` alice: 1 2 3 bob : 7 8 9 10 -- SWAP alice: 7 8 9 10 bob : 1 2 3 ``` ### See also | | | | --- | --- | | [swap](swap "cpp/container/unordered set/swap") (C++11) | swaps the contents (public member function) |
programming_docs
cpp std::unordered_set<Key,Hash,KeyEqual,Allocator>::operator= std::unordered\_set<Key,Hash,KeyEqual,Allocator>::operator= =========================================================== | | | | | --- | --- | --- | | ``` unordered_set& operator=( const unordered_set& other ); ``` | (1) | (since C++11) | | | (2) | | | ``` unordered_set& operator=( unordered_set&& other ); ``` | (since C++11) (until C++17) | | ``` unordered_set& operator=( unordered_set&& other ) noexcept(/* see below */); ``` | (since C++17) | | ``` unordered_set& operator=( std::initializer_list<value_type> ilist ); ``` | (3) | (since C++11) | Replaces the contents of the container. 1) Copy assignment operator. Replaces the contents with a copy of the contents of `other`. If `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<allocator_type>::propagate\_on\_container\_copy\_assignment::value` is `true`, the allocator of `*this` is replaced by a copy of that of `other`. If the allocator of `*this` after assignment would compare unequal to its old value, the old allocator is used to deallocate the memory, then the new allocator is used to allocate it before copying the elements. Otherwise, the memory owned by `*this` may be reused when possible. In any case, the elements originally belonging to `*this` may be either destroyed or replaced by element-wise copy-assignment. 2) Move assignment operator. Replaces the contents with those of `other` using move semantics (i.e. the data in `other` is moved from `other` into this container). `other` is in a valid but unspecified state afterwards. If `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<allocator_type>::propagate\_on\_container\_move\_assignment::value` is `true`, the allocator of `*this` is replaced by a copy of that of `other`. If it is `false` and the allocators of `*this` and `other` do not compare equal, `*this` cannot take ownership of the memory owned by `other` and must move-assign each element individually, allocating additional memory using its own allocator as needed. In any case, all elements originally belonging to `*this` are either destroyed or replaced by element-wise move-assignment. 3) Replaces the contents with those identified by initializer list `ilist`. ### Parameters | | | | | --- | --- | --- | | other | - | another container to use as data source | | ilist | - | initializer list to use as data source | ### Return value `*this`. ### Complexity 1) Linear in the size of `*this` and `other`. 2) Linear in the size of `*this` unless the allocators do not compare equal and do not propagate, in which case linear in the size of `*this` and `other`. 3) Linear in the size of `*this` and `ilist`. ### Exceptions | | | | --- | --- | | May throw implementation-defined exceptions. | (until C++17) | | 1,3) May throw implementation-defined exceptions. 2) [`noexcept`](../../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept([std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<Allocator>::is\_always\_equal::value && [std::is\_nothrow\_move\_assignable](http://en.cppreference.com/w/cpp/types/is_move_assignable)<Hash>::value. && [std::is\_nothrow\_move\_assignable](http://en.cppreference.com/w/cpp/types/is_move_assignable)<Pred>::value)` | (since C++17) | ### Notes After container move assignment (overload (2)), unless element-wise move assignment is forced by incompatible allocators, references, pointers, and iterators (other than the end iterator) to `other` remain valid, but refer to elements that are now in `*this`. The current standard makes this guarantee via the blanket statement in [[container.requirements.general]/12](https://eel.is/c++draft/container.requirements.general#12), and a more direct guarantee is under consideration via [LWG 2321](https://cplusplus.github.io/LWG/issue2321). ### Example The following code uses `operator=` to assign one `[std::unordered\_set](../unordered_set "cpp/container/unordered set")` to another: ``` #include <unordered_set> #include <iterator> #include <iostream> void print(auto const comment, auto const& container) { auto size = std::size(container); std::cout << comment << "{ "; for (auto const& element: container) std::cout << element << (--size ? ", " : " "); std::cout << "}\n"; } int main() { std::unordered_set<int> x { 1, 2, 3 }, y, z; const auto w = { 4, 5, 6, 7 }; std::cout << "Initially:\n"; print("x = ", x); print("y = ", y); print("z = ", z); std::cout << "Copy assignment copies data from x to y:\n"; y = x; print("x = ", x); print("y = ", y); std::cout << "Move assignment moves data from x to z, modifying both x and z:\n"; z = std::move(x); print("x = ", x); print("z = ", z); std::cout << "Assignment of initializer_list w to z:\n"; z = w; print("w = ", w); print("z = ", z); } ``` Possible output: ``` Initially: x = { 3, 2, 1 } y = { } z = { } Copy assignment copies data from x to y: x = { 3, 2, 1 } y = { 3, 2, 1 } Move assignment moves data from x to z, modifying both x and z: x = { } z = { 3, 2, 1 } Assignment of initializer_list w to z: w = { 4, 5, 6, 7 } z = { 7, 6, 5, 4 } ``` ### See also | | | | --- | --- | | [(constructor)](unordered_set "cpp/container/unordered set/unordered set") (C++11) | constructs the `unordered_set` (public member function) | cpp std::unordered_set<Key,Hash,KeyEqual,Allocator>::clear std::unordered\_set<Key,Hash,KeyEqual,Allocator>::clear ======================================================= | | | | | --- | --- | --- | | ``` void clear() noexcept; ``` | | (since C++11) | Erases all elements from the container. After this call, `[size()](size "cpp/container/unordered set/size")` returns zero. Invalidates any references, pointers, or iterators referring to contained elements. May also invalidate past-the-end iterators. ### Parameters (none). ### Return value (none). ### Complexity Linear in the size of the container, i.e., the number of elements. ### Example ``` #include <algorithm> #include <iostream> #include <unordered_set> int main() { std::unordered_set<int> container{1, 2, 3}; auto print = [](const int& n) { std::cout << " " << n; }; std::cout << "Before clear:"; std::for_each(container.begin(), container.end(), print); std::cout << "\nSize=" << container.size() << '\n'; std::cout << "Clear\n"; container.clear(); std::cout << "After clear:"; std::for_each(container.begin(), container.end(), print); std::cout << "\nSize=" << container.size() << '\n'; } ``` Possible output: ``` Before clear: 1 2 3 Size=3 Clear After clear: Size=0 ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 2550](https://cplusplus.github.io/LWG/issue2550) | C++11 | for unordered associative containers, unclear if complexity is linear in the number of elements or buckets | clarified that it's linear in the number of elements | ### See also | | | | --- | --- | | [erase](erase "cpp/container/unordered set/erase") (C++11) | erases elements (public member function) | cpp std::unordered_set<Key,Hash,KeyEqual,Allocator>::~unordered_set std::unordered\_set<Key,Hash,KeyEqual,Allocator>::~unordered\_set ================================================================= | | | | | --- | --- | --- | | ``` ~unordered_set(); ``` | | (since C++11) | Destructs the `unordered_set`. The destructors of the elements are called and the used storage is deallocated. Note, that if the elements are pointers, the pointed-to objects are not destroyed. ### Complexity Linear in the size of the `unordered_set`. cpp std::unordered_set<Key,Hash,KeyEqual,Allocator>::rehash std::unordered\_set<Key,Hash,KeyEqual,Allocator>::rehash ======================================================== | | | | | --- | --- | --- | | ``` void rehash( size_type count ); ``` | | (since C++11) | Sets the number of buckets to `count` and rehashes the container, i.e. puts the elements into appropriate buckets considering that total number of buckets has changed. If the new number of buckets makes load factor more than maximum load factor (`count < size() / max_load_factor()`), then the new number of buckets is at least `size() / max_load_factor()`. ### Parameters | | | | | --- | --- | --- | | count | - | new number of buckets | ### Return value (none). ### Complexity Average case linear in the size of the container, worst case quadratic. ### Notes `rehash(0)` may be used to force an unconditional rehash, such as after suspension of automatic rehashing by temporarily increasing `max_load_factor()`. ### See also | | | | --- | --- | | [reserve](reserve "cpp/container/unordered set/reserve") (C++11) | reserves space for at least the specified number of elements and regenerates the hash table (public member function) | cpp std::unordered_set<Key,Hash,KeyEqual,Allocator>::key_eq std::unordered\_set<Key,Hash,KeyEqual,Allocator>::key\_eq ========================================================= | | | | | --- | --- | --- | | ``` key_equal key_eq() const; ``` | | (since C++11) | Returns the function that compares keys for equality. ### Parameters (none). ### Return value The key comparison function. ### Complexity Constant. ### See also | | | | --- | --- | | [hash\_function](hash_function "cpp/container/unordered set/hash function") (C++11) | returns function used to hash the keys (public member function) | cpp std::unordered_set<Key,Hash,KeyEqual,Allocator>::end(size_type), std::unordered_set<Key,Hash,KeyEqual,Allocator>::cend(size_type) std::unordered\_set<Key,Hash,KeyEqual,Allocator>::end(size\_type), std::unordered\_set<Key,Hash,KeyEqual,Allocator>::cend(size\_type) ===================================================================================================================================== | | | | | --- | --- | --- | | ``` local_iterator end( size_type n ); ``` | | (since C++11) | | ``` const_local_iterator end( size_type n ) const; ``` | | (since C++11) | | ``` const_local_iterator cend( size_type n ) const; ``` | | (since C++11) | Returns an iterator to the element following the last element of the bucket with index `n`. . This element acts as a placeholder, attempting to access it results in undefined behavior. ### Parameters | | | | | --- | --- | --- | | n | - | the index of the bucket to access | ### Return value iterator to the element following the last element. ### Complexity Constant. ### See also | | | | --- | --- | | [begin(size\_type) cbegin(size\_type)](begin2 "cpp/container/unordered set/begin2") (C++11) | returns an iterator to the beginning of the specified bucket (public member function) | cpp operator==,!=(std::unordered_set) operator==,!=(std::unordered\_set) ================================== | | | | | --- | --- | --- | | ``` template< class Key, class Hash, class KeyEqual, class Alloc > bool operator==( const std::unordered_set<Key,Hash,KeyEqual,Alloc>& lhs, const std::unordered_set<Key,Hash,KeyEqual,Alloc>& rhs ); ``` | (1) | | | ``` template< class Key, class Hash, class KeyEqual, class Alloc > bool operator!=( const std::unordered_set<Key,Hash,KeyEqual,Alloc>& lhs, const std::unordered_set<Key,Hash,KeyEqual,Alloc>& rhs ); ``` | (2) | (until C++20) | Compares the contents of two unordered containers. The contents of two unordered containers `lhs` and `rhs` are equal if the following conditions hold: * `lhs.size() == rhs.size()` * each group of equivalent elements `[lhs_eq1, lhs_eq2)` obtained from `lhs.equal_range(lhs_eq1)` has a corresponding group of equivalent elements in the other container `[rhs_eq1, rhs_eq2)` obtained from `rhs.equal_range(rhs_eq1)`, that has the following properties: + `[std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(lhs_eq1, lhs_eq2) == [std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(rhs_eq1, rhs_eq2)`. + `[std::is\_permutation](http://en.cppreference.com/w/cpp/algorithm/is_permutation)(lhs_eq1, lhs_eq2, rhs_eq1) == true`. The behavior is undefined if `Key` is not [EqualityComparable](../../named_req/equalitycomparable "cpp/named req/EqualityComparable"). The behavior is also undefined if `hash_function()` and `key_eq()` do (until C++20)`key_eq()` does (since C++20) not have the same behavior on `lhs` and `rhs` or if `operator==` for `Key` is not a refinement of the partition into equivalent-key groups introduced by `key_eq()` (that is, if two elements that compare equal using `operator==` fall into different partitions). | | | | --- | --- | | The `!=` operator is [synthesized](../../language/operators#Relational_operators "cpp/language/operators") from `operator==`. | (since C++20) | ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | unordered containers to compare | ### Return value 1) `true` if the contents of the containers are equal, `false` otherwise 2) `true` if the contents of the containers are not equal, `false` otherwise ### Complexity Proportional to *N* calls to `operator==` on `value_type`, calls to the predicate returned by [`key_eq`](key_eq "cpp/container/unordered set/key eq"), and calls to the hasher returned by [`hash_function`](hash_function "cpp/container/unordered set/hash function"), in the average case, proportional to *N2* in the worst case where *N* is the size of the container. cpp std::unordered_set<Key,Hash,KeyEqual,Allocator>::reserve std::unordered\_set<Key,Hash,KeyEqual,Allocator>::reserve ========================================================= | | | | | --- | --- | --- | | ``` void reserve( size_type count ); ``` | | (since C++11) | Sets the number of buckets to the number needed to accomodate at least `count` elements without exceeding maximum load factor and rehashes the container, i.e. puts the elements into appropriate buckets considering that total number of buckets has changed. Effectively calls `rehash([std::ceil](http://en.cppreference.com/w/cpp/numeric/math/ceil)(count / max_load_factor()))`. ### Parameters | | | | | --- | --- | --- | | count | - | new capacity of the container | ### Return value (none). ### Complexity Average case linear in the size of the container, worst case quadratic. ### See also | | | | --- | --- | | [rehash](rehash "cpp/container/unordered set/rehash") (C++11) | reserves at least the specified number of buckets and regenerates the hash table (public member function) | cpp std::unordered_set<Key,Hash,KeyEqual,Allocator>::empty std::unordered\_set<Key,Hash,KeyEqual,Allocator>::empty ======================================================= | | | | | --- | --- | --- | | ``` bool empty() const noexcept; ``` | | (since C++11) (until C++20) | | ``` [[nodiscard]] bool empty() const noexcept; ``` | | (since C++20) | Checks if the container has no elements, i.e. whether `begin() == end()`. ### Parameters (none). ### Return value `true` if the container is empty, `false` otherwise. ### Complexity Constant. ### Example The following code uses `empty` to check if a `[std::unordered\_set](http://en.cppreference.com/w/cpp/container/unordered_set)<int>` contains any elements: ``` #include <unordered_set> #include <iostream> int main() { std::unordered_set<int> numbers; std::cout << std::boolalpha; std::cout << "Initially, numbers.empty(): " << numbers.empty() << '\n'; numbers.insert(42); numbers.insert(13317); std::cout << "After adding elements, numbers.empty(): " << numbers.empty() << '\n'; } ``` Output: ``` Initially, numbers.empty(): true After adding elements, numbers.empty(): false ``` ### See also | | | | --- | --- | | [size](size "cpp/container/unordered set/size") (C++11) | returns the number of elements (public member function) | | [empty](../../iterator/empty "cpp/iterator/empty") (C++17) | checks whether the container is empty (function template) | cpp std::unordered_set<Key,Hash,KeyEqual,Allocator>::begin, std::unordered_set<Key,Hash,KeyEqual,Allocator>::cbegin std::unordered\_set<Key,Hash,KeyEqual,Allocator>::begin, std::unordered\_set<Key,Hash,KeyEqual,Allocator>::cbegin ================================================================================================================= | | | | | --- | --- | --- | | ``` iterator begin() noexcept; ``` | | (since C++11) | | ``` const_iterator begin() const noexcept; ``` | | (since C++11) | | ``` const_iterator cbegin() const noexcept; ``` | | (since C++11) | Returns an iterator to the first element of the `unordered_set`. If the `unordered_set` is empty, the returned iterator will be equal to `[end()](end "cpp/container/unordered set/end")`. ![range-begin-end.svg]() ### Parameters (none). ### Return value Iterator to the first element. ### Complexity Constant. ### Notes Because both `iterator` and `const_iterator` are constant iterators (and may in fact be the same type), it is not possible to mutate the elements of the container through an iterator returned by any of these member functions. ### Example ``` #include <iostream> #include <unordered_set> struct Point { double x, y; }; int main() { Point pts[3] = { {1, 0}, {2, 0}, {3, 0} }; //points is a set containing the addresses of points std::unordered_set<Point *> points = { pts, pts + 1, pts + 2 }; //Change each y-coordinate of (i, 0) from 0 into i^2 and print the point for(auto iter = points.begin(); iter != points.end(); ++iter){ (*iter)->y = ((*iter)->x) * ((*iter)->x); //iter is a pointer-to-Point* std::cout << "(" << (*iter)->x << ", " << (*iter)->y << ") "; } std::cout << '\n'; //Now using the range-based for loop, we increase each y-coordinate by 10 for(Point * i : points) { i->y += 10; std::cout << "(" << i->x << ", " << i->y << ") "; } } ``` Possible output: ``` (3, 9) (1, 1) (2, 4) (3, 19) (1, 11) (2, 14) ``` ### See also | | | | --- | --- | | [end cend](end "cpp/container/unordered set/end") (C++11) | returns an iterator to the end (public member function) | | [begincbegin](../../iterator/begin "cpp/iterator/begin") (C++11)(C++14) | returns an iterator to the beginning of a container or array (function template) | cpp std::unordered_set<Key,Hash,KeyEqual,Allocator>::begin(size_type), std::unordered_set<Key,Hash,KeyEqual,Allocator>::cbegin(size_type) std::unordered\_set<Key,Hash,KeyEqual,Allocator>::begin(size\_type), std::unordered\_set<Key,Hash,KeyEqual,Allocator>::cbegin(size\_type) ========================================================================================================================================= | | | | | --- | --- | --- | | ``` local_iterator begin( size_type n ); ``` | | (since C++11) | | ``` const_local_iterator begin( size_type n ) const; ``` | | (since C++11) | | ``` const_local_iterator cbegin( size_type n ) const; ``` | | (since C++11) | Returns an iterator to the first element of the bucket with index `n`. ### Parameters | | | | | --- | --- | --- | | n | - | the index of the bucket to access | ### Return value Iterator to the first element. ### Complexity Constant. ### See also | | | | --- | --- | | [end(size\_type) cend(size\_type)](end2 "cpp/container/unordered set/end2") (C++11) | returns an iterator to the end of the specified bucket (public member function) |
programming_docs
cpp std::unordered_set<Key,Hash,KeyEqual,Allocator>::end, std::unordered_set<Key,Hash,KeyEqual,Allocator>::cend std::unordered\_set<Key,Hash,KeyEqual,Allocator>::end, std::unordered\_set<Key,Hash,KeyEqual,Allocator>::cend ============================================================================================================= | | | | | --- | --- | --- | | ``` iterator end() noexcept; ``` | | (since C++11) | | ``` const_iterator end() const noexcept; ``` | | (since C++11) | | ``` const_iterator cend() const noexcept; ``` | | (since C++11) | Returns an iterator to the element following the last element of the `unordered_set`. This element acts as a placeholder; attempting to access it results in undefined behavior. ![range-begin-end.svg]() ### Parameters (none). ### Return value Iterator to the element following the last element. ### Complexity Constant. ### Notes Because both `iterator` and `const_iterator` are constant iterators (and may in fact be the same type), it is not possible to mutate the elements of the container through an iterator returned by any of these member functions. ### Example ``` #include <iostream> #include <unordered_set> struct Point { double x, y; }; int main() { Point pts[3] = { {1, 0}, {2, 0}, {3, 0} }; //points is a set containing the addresses of points std::unordered_set<Point *> points = { pts, pts + 1, pts + 2 }; //Change each y-coordinate of (i, 0) from 0 into i^2 and print the point for(auto iter = points.begin(); iter != points.end(); ++iter){ (*iter)->y = ((*iter)->x) * ((*iter)->x); //iter is a pointer-to-Point* std::cout << "(" << (*iter)->x << ", " << (*iter)->y << ") "; } std::cout << '\n'; //Now using the range-based for loop, we increase each y-coordinate by 10 for(Point * i : points) { i->y += 10; std::cout << "(" << i->x << ", " << i->y << ") "; } } ``` Possible output: ``` (3, 9) (1, 1) (2, 4) (3, 19) (1, 11) (2, 14) ``` ### See also | | | | --- | --- | | [begin cbegin](begin "cpp/container/unordered set/begin") (C++11) | returns an iterator to the beginning (public member function) | | [endcend](../../iterator/end "cpp/iterator/end") (C++11)(C++14) | returns an iterator to the end of a container or array (function template) | cpp std::unordered_set<Key,Hash,KeyEqual,Allocator>::bucket std::unordered\_set<Key,Hash,KeyEqual,Allocator>::bucket ======================================================== | | | | | --- | --- | --- | | ``` size_type bucket( const Key& key ) const; ``` | | (since C++11) | Returns the index of the bucket for key `key`. Elements (if any) with keys equivalent to `key` are always found in this bucket. The returned value is valid only for instances of the container for which `[bucket\_count()](bucket_count "cpp/container/unordered set/bucket count")` returns the same value. The behavior is undefined if `[bucket\_count()](bucket_count "cpp/container/unordered set/bucket count")` is zero. ### Parameters | | | | | --- | --- | --- | | key | - | the value of the key to examine | ### Return value Bucket index for the key `key`. ### Complexity Constant. ### See also | | | | --- | --- | | [bucket\_size](bucket_size "cpp/container/unordered set/bucket size") (C++11) | returns the number of elements in specific bucket (public member function) | cpp std::unordered_multiset<Key,Hash,KeyEqual,Allocator>::contains std::unordered\_multiset<Key,Hash,KeyEqual,Allocator>::contains =============================================================== | | | | | --- | --- | --- | | ``` bool contains( const Key& key ) const; ``` | (1) | (since C++20) | | ``` template< class K > bool contains( const K& x ) const; ``` | (2) | (since C++20) | 1) Checks if there is an element with key equivalent to `key` in the container. 2) Checks if there is an element with key that compares *equivalent* to the value `x`. This overload participates in overload resolution only if `Hash::is_transparent` and `KeyEqual::is_transparent` are valid and each denotes a type. This assumes that such `Hash` is callable with both `K` and `Key` type, and that the `KeyEqual` is transparent, which, together, allows calling this function without constructing an instance of `Key`. ### Parameters | | | | | --- | --- | --- | | key | - | key value of the element to search for | | x | - | a value of any type that can be transparently compared with a key | ### Return value `true` if there is such an element, otherwise `false`. ### Complexity Constant on average, worst case linear in the size of the container. ### Example ``` #include <iostream> #include <unordered_set> int main() { std::unordered_multiset<int> example = {1, 2, 3, 4}; for(int x: {2, 5}) { if(example.contains(x)) { std::cout << x << ": Found\n"; } else { std::cout << x << ": Not found\n"; } } } ``` Output: ``` 2: Found 5: Not found ``` ### See also | | | | --- | --- | | [find](find "cpp/container/unordered multiset/find") (C++11) | finds element with specific key (public member function) | | [count](count "cpp/container/unordered multiset/count") (C++11) | returns the number of elements matching specific key (public member function) | | [equal\_range](equal_range "cpp/container/unordered multiset/equal range") (C++11) | returns range of elements matching a specific key (public member function) | cpp std::unordered_multiset<Key,Hash,KeyEqual,Allocator>::size std::unordered\_multiset<Key,Hash,KeyEqual,Allocator>::size =========================================================== | | | | | --- | --- | --- | | ``` size_type size() const noexcept; ``` | | (since C++11) | Returns the number of elements in the container, i.e. `[std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(begin(), end())`. ### Parameters (none). ### Return value The number of elements in the container. ### Complexity Constant. ### Example The following code uses `size` to display the number of elements in a `[std::unordered\_multiset](http://en.cppreference.com/w/cpp/container/unordered_multiset)<int>`: ``` #include <unordered_set> #include <iostream> int main() { std::unordered_multiset<int> nums {1, 3, 5, 7}; std::cout << "nums contains " << nums.size() << " elements.\n"; } ``` Output: ``` nums contains 4 elements. ``` ### See also | | | | --- | --- | | [empty](empty "cpp/container/unordered multiset/empty") (C++11) | checks whether the container is empty (public member function) | | [max\_size](max_size "cpp/container/unordered multiset/max size") (C++11) | returns the maximum possible number of elements (public member function) | | [sizessize](../../iterator/size "cpp/iterator/size") (C++17)(C++20) | returns the size of a container or array (function template) | cpp std::unordered_multiset<Key,Hash,KeyEqual,Allocator>::bucket_count std::unordered\_multiset<Key,Hash,KeyEqual,Allocator>::bucket\_count ==================================================================== | | | | | --- | --- | --- | | ``` size_type bucket_count() const; ``` | | (since C++11) | Returns the number of buckets in the container. ### Parameters (none). ### Return value The number of buckets in the container. ### Complexity Constant. ### See also | | | | --- | --- | | [bucket\_size](bucket_size "cpp/container/unordered multiset/bucket size") (C++11) | returns the number of elements in specific bucket (public member function) | | [max\_bucket\_count](max_bucket_count "cpp/container/unordered multiset/max bucket count") (C++11) | returns the maximum number of buckets (public member function) | cpp deduction guides for std::unordered_multiset deduction guides for `std::unordered_multiset` ============================================== | Defined in header `[<unordered\_set>](../../header/unordered_set "cpp/header/unordered set")` | | | | --- | --- | --- | | ``` template<class InputIt, class Hash = std::hash<typename std::iterator_traits<InputIt>::value_type>, class Pred = std::equal_to<typename std::iterator_traits<InputIt>::value_type>, class Alloc = std::allocator<typename std::iterator_traits<InputIt>::value_type>> unordered_multiset(InputIt, InputIt, typename /*see below*/::size_type = /*see below*/, Hash = Hash(), Pred = Pred(), Alloc = Alloc()) -> unordered_multiset<typename std::iterator_traits<InputIt>::value_type, Hash, Pred, Alloc>; ``` | (1) | (since C++17) | | ``` template<class T, class Hash = std::hash<T>, class Pred = std::equal_to<T>, class Alloc = std::allocator<T>> unordered_multiset(std::initializer_list<T>, typename /*see below*/::size_type = /*see below*/, Hash = Hash(), Pred = Pred(), Alloc = Alloc()) -> unordered_multiset<T, Hash, Pred, Alloc>; ``` | (2) | (since C++17) | | ``` template<class InputIt, class Alloc> unordered_multiset(InputIt, InputIt, typename /*see below*/::size_type, Alloc) -> unordered_multiset<typename std::iterator_traits<InputIt>::value_type, std::hash<typename std::iterator_traits<InputIt>::value_type>, std::equal_to<typename std::iterator_traits<InputIt>::value_type>, Alloc>; ``` | (3) | (since C++17) | | ``` template<class InputIt, class Hash, class Alloc> unordered_multiset(InputIt, InputIt, typename /*see below*/::size_type, Hash, Alloc) -> unordered_multiset<typename std::iterator_traits<InputIt>::value_type, Hash, std::equal_to<typename std::iterator_traits<InputIt>::value_type>, Allocator>; ``` | (4) | (since C++17) | | ``` template<class T, class Allocator> unordered_multiset(std::initializer_list<T>, typename /*see below*/::size_type, Allocator) -> unordered_multiset<T, std::hash<T>, std::equal_to<T>, Alloc>; ``` | (5) | (since C++17) | | ``` template<class T, class Hash, class Alloc> unordered_multiset(std::initializer_list<T>, typename /*see below*/::size_type, Hash, Alloc) -> unordered_multiset<T, Hash, std::equal_to<T>, Alloc>; ``` | (6) | (since C++17) | These [deduction guides](../../language/class_template_argument_deduction "cpp/language/class template argument deduction") are provided for unordered\_multiset to allow deduction from an iterator range (overloads (1,3,4)) and `[std::initializer\_list](../../utility/initializer_list "cpp/utility/initializer list")` (overloads (2,5.6)). This overload participates in overload resolution only if `InputIt` satisfies [LegacyInputIterator](../../named_req/inputiterator "cpp/named req/InputIterator"), `Alloc` satisfies [Allocator](../../named_req/allocator "cpp/named req/Allocator"), neither `Hash` nor `Pred` satisfy [Allocator](../../named_req/allocator "cpp/named req/Allocator"), `Hash` is not an integral type. Note: the extent to which the library determines that a type does not satisfy [LegacyInputIterator](../../named_req/inputiterator "cpp/named req/InputIterator") is unspecified, except that as a minimum integral types do not qualify as input iterators. Likewise, the extent to which it determines that a type does not satisfy [Allocator](../../named_req/allocator "cpp/named req/Allocator") is unspecified, except that as a minimum the member type `Alloc::value_type` must exist and the expression `[std::declval](http://en.cppreference.com/w/cpp/utility/declval)<Alloc&>().allocate([std::size\_t](http://en.cppreference.com/w/cpp/types/size_t){})` must be well-formed when treated as an unevaluated operand. The `size_type` parameter type in these guides refers to the `size_type` member type of the type deduced by the deduction guide. ### Example ``` #include <unordered_set> int main() { std::unordered_multiset s = {1,2,3,4}; // guide #2 deduces std::unordered_multiset<int> std::unordered_multiset s2(s.begin(), s.end()); // guide #1 deduces std::unordered_multiset<int> } ``` cpp std::unordered_multiset<Key,Hash,KeyEqual,Allocator>::emplace std::unordered\_multiset<Key,Hash,KeyEqual,Allocator>::emplace ============================================================== | | | | | --- | --- | --- | | ``` template< class... Args > iterator emplace( Args&&... args ); ``` | | (since C++11) | Inserts a new element into the container constructed in-place with the given `args` . Careful use of `emplace` allows the new element to be constructed while avoiding unnecessary copy or move operations. The constructor of the new element is called with exactly the same arguments as supplied to `emplace`, forwarded via `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Args>(args)...`. If rehashing occurs due to the insertion, all iterators are invalidated. Otherwise iterators are not affected. References are not invalidated. Rehashing occurs only if the new number of elements is greater than `max_load_factor()*bucket_count()`. ### Parameters | | | | | --- | --- | --- | | args | - | arguments to forward to the constructor of the element | ### Return value Returns an iterator to the inserted element. ### Exceptions If an exception is thrown by any operation, this function has no effect (strong exception guarantee). ### Complexity Amortized constant on average, worst case linear in the size of the container. ### Example ### See also | | | | --- | --- | | [emplace\_hint](emplace_hint "cpp/container/unordered multiset/emplace hint") (C++11) | constructs elements in-place using a hint (public member function) | | [insert](insert "cpp/container/unordered multiset/insert") (C++11) | inserts elements or nodes (since C++17) (public member function) | cpp std::unordered_multiset<Key,Hash,KeyEqual,Allocator>::insert std::unordered\_multiset<Key,Hash,KeyEqual,Allocator>::insert ============================================================= | | | | | --- | --- | --- | | ``` iterator insert( const value_type& value ); ``` | (1) | (since C++11) | | ``` iterator insert( value_type&& value ); ``` | (2) | (since C++11) | | ``` iterator insert( const_iterator hint, const value_type& value ); ``` | (3) | (since C++11) | | ``` iterator insert( const_iterator hint, value_type&& value ); ``` | (4) | (since C++11) | | ``` template< class InputIt > void insert( InputIt first, InputIt last ); ``` | (5) | (since C++11) | | ``` void insert( std::initializer_list<value_type> ilist ); ``` | (6) | (since C++11) | | ``` iterator insert( node_type&& nh ); ``` | (7) | (since C++17) | | ``` iterator insert( const_iterator hint, node_type&& nh ); ``` | (8) | (since C++17) | Inserts element(s) into the container. 1-2) Inserts `value`. 3-4) Inserts `value`, using `hint` as a non-binding suggestion to where the search should start. 5) Inserts elements from range `[first, last)`. 6) Inserts elements from initializer list `ilist`. 7) If `nh` is an empty [node handle](../node_handle "cpp/container/node handle"), does nothing. Otherwise, inserts the element owned by `nh` into the container and returns an iterator pointing at the inserted element.. The behavior is undefined if `nh` is not empty and `get_allocator() != nh.get_allocator()`. 8) If `nh` is an empty [node handle](../node_handle "cpp/container/node handle"), does nothing and returns the end iterator. Otherwise, inserts the element owned by `nh` into the container, and returns the iterator pointing to the element with key equivalent to `nh.key()` The element is inserted as close as possible to `hint`. The behavior is undefined if `nh` is not empty and `get_allocator() != nh.get_allocator()`. If rehashing occurs due to the insertion, all iterators are invalidated. Otherwise iterators are not affected. References are not invalidated. Rehashing occurs only if the new number of elements is greater than `max_load_factor()*bucket_count()`. If the insertion is successful, pointers and references to the element obtained while it is held in the node handle are invalidated, and pointers and references obtained to that element before it was extracted become valid. (since C++17). ### Parameters | | | | | --- | --- | --- | | hint | - | iterator, used as a suggestion as to where to insert the content | | value | - | element value to insert | | first, last | - | range of elements to insert | | ilist | - | initializer list to insert the values from | | nh | - | a compatible [node handle](../node_handle "cpp/container/node handle") | | Type requirements | | -`InputIt` must meet the requirements of [LegacyInputIterator](../../named_req/inputiterator "cpp/named req/InputIterator"). | ### Return value 1-4) Returns an iterator to the inserted element. 5-6) (none) 7,8) End iterator if `nh` was empty, iterator pointing to the inserted element otherwise. ### Exceptions 1-4) If an exception is thrown by any operation, the insertion has no effect. ### Complexity 1-4) Average case: `O(1)`, worst case `O(size())` 5-6) Average case: `O(N)`, where N is the number of elements to insert. Worse case: `O(N*size()+N)` 7-8) Average case: `O(1)`, worst case `O(size())` ### Example ### See also | | | | --- | --- | | [emplace](emplace "cpp/container/unordered multiset/emplace") (C++11) | constructs element in-place (public member function) | | [emplace\_hint](emplace_hint "cpp/container/unordered multiset/emplace hint") (C++11) | constructs elements in-place using a hint (public member function) | | [inserter](../../iterator/inserter "cpp/iterator/inserter") | creates a `[std::insert\_iterator](../../iterator/insert_iterator "cpp/iterator/insert iterator")` of type inferred from the argument (function template) | cpp std::unordered_multiset<Key,Hash,KeyEqual,Allocator>::get_allocator std::unordered\_multiset<Key,Hash,KeyEqual,Allocator>::get\_allocator ===================================================================== | | | | | --- | --- | --- | | ``` allocator_type get_allocator() const noexcept; ``` | | (since C++11) | Returns the allocator associated with the container. ### Parameters (none). ### Return value The associated allocator. ### Complexity Constant. cpp std::unordered_multiset<Key,Hash,KeyEqual,Allocator>::merge std::unordered\_multiset<Key,Hash,KeyEqual,Allocator>::merge ============================================================ | | | | | --- | --- | --- | | ``` template<class H2, class P2> void merge( std::unordered_set<Key, H2, P2, Allocator>& source ); ``` | (1) | (since C++17) | | ``` template<class H2, class P2> void merge( std::unordered_set<Key, H2, P2, Allocator>&& source ); ``` | (2) | (since C++17) | | ``` template<class H2, class P2> void merge( std::unordered_multiset<Key, H2, P2, Allocator>& source ); ``` | (3) | (since C++17) | | ``` template<class H2, class P2> void merge( std::unordered_multiset<Key, H2, P2, Allocator>&& source ); ``` | (4) | (since C++17) | Attempts to extract ("splice") each element in `source` and insert it into `*this` using the hash function and key equality predicate of `*this`. No elements are copied or moved, only the internal pointers of the container nodes are repointed. All pointers and references to the transferred elements remain valid, but now refer into `*this`, not into `source`. Iterators referring to the transferred elements and all iterators referring to `*this` are invalidated. The behavior is undefined if `get_allocator() != source.get_allocator()`. ### Parameters | | | | | --- | --- | --- | | source | - | compatible container to transfer the nodes from | ### Return value (none). ### Complexity Average case O(N), worst case O(N\*size()+N), where N is `source.size()`. ### Example ``` #include <iostream> #include <unordered_set> // print out a container template <class Os, class K> Os& operator<<(Os& os, const std::unordered_multiset<K>& v) { os << '[' << v.size() << "] {"; bool o{}; for (const auto& e : v) os << (o ? ", " : (o = 1, " ")) << e; return os << " }\n"; } int main() { std::unordered_multiset<char> p{ 'C', 'B', 'B', 'A' }, q{ 'E', 'D', 'E', 'C' }; std::cout << "p: " << p << "q: " << q; p.merge(q); std::cout << "p.merge(q);\n" << "p: " << p << "q: " << q; } ``` Possible output: ``` p: [4] { A, B, B, C } q: [4] { C, D, E, E } p.merge(q); p: [8] { E, E, D, A, B, B, C, C } q: [0] { } ``` ### See also | | | | --- | --- | | [extract](extract "cpp/container/unordered multiset/extract") (C++17) | extracts nodes from the container (public member function) | | [insert](insert "cpp/container/unordered multiset/insert") (C++11) | inserts elements or nodes (since C++17) (public member function) |
programming_docs
cpp std::unordered_multiset<Key,Hash,KeyEqual,Allocator>::extract std::unordered\_multiset<Key,Hash,KeyEqual,Allocator>::extract ============================================================== | | | | | --- | --- | --- | | ``` node_type extract( const_iterator position ); ``` | (1) | (since C++17) | | ``` node_type extract( const Key& k ); ``` | (2) | (since C++17) | | ``` template< class K > node_type extract( K&& x ); ``` | (3) | (since C++23) | 1) Unlinks the node that contains the element pointed to by `position` and returns a [node handle](../node_handle "cpp/container/node handle") that owns it. 2) If the container has an element with key equivalent to `k`, unlinks the node that contains the first such element from the container and returns a [node handle](../node_handle "cpp/container/node handle") that owns it. Otherwise, returns an empty node handle. 3) Same as (2). This overload participates in overload resolution only if `Hash::is_transparent` and `KeyEqual::is_transparent` are valid and each denotes a type, and neither `iterator` nor `const_iterator` is implicitly convertible from `K`. This assumes that such `Hash` is callable with both `K` and `Key` type, and that the `KeyEqual` is transparent, which, together, allows calling this function without constructing an instance of `Key`. In either case, no elements are copied or moved, only the internal pointers of the container nodes are repointed . Extracting a node invalidates only the iterators to the extracted element, and preserves the relative order of the elements that are not erased. Pointers and references to the extracted element remain valid, but cannot be used while element is owned by a node handle: they become usable if the element is inserted into a container. ### Parameters | | | | | --- | --- | --- | | position | - | a valid iterator into this container | | k | - | a key to identify the node to be extracted | | x | - | a value of any type that can be transparently compared with a key identifying the node to be extracted | ### Return value A [node handle](../node_handle "cpp/container/node handle") that owns the extracted element, or empty node handle in case the element is not found in (2,3). ### Exceptions 1) Throws nothing. 2,3) Any exceptions thrown by the `Hash` and `KeyEqual` object. ### Complexity 1,2,3) Average case O(1), worst case O(`a.size()`). ### Notes extract is the only way to take a move-only object out of a set. ``` std::set<move_only_type> s; s.emplace(...); move_only_type mot = std::move(s.extract(s.begin()).value()); ``` | [Feature-test](../../utility/feature_test "cpp/utility/feature test") macro | Comment | | --- | --- | | [`__cpp_lib_associative_heterogeneous_erasure`](../../feature_test#Library_features "cpp/feature test") | for overload (3) | ### Example ``` #include <algorithm> #include <iostream> #include <string_view> #include <unordered_set> void print(std::string_view comment, const auto& data) { std::cout << comment; for (auto datum : data) std::cout << ' ' << datum; std::cout << '\n'; } int main() { std::unordered_multiset<int> cont{1, 2, 3}; print("Start:", cont); // Extract node handle and change key auto nh = cont.extract(1); nh.value() = 4; print("After extract and before insert:", cont); // Insert node handle back cont.insert(std::move(nh)); print("End:", cont); } ``` Possible output: ``` Start: 1 2 3 After extract and before insert: 2 3 End: 2 3 4 ``` ### See also | | | | --- | --- | | [merge](merge "cpp/container/unordered multiset/merge") (C++17) | splices nodes from another container (public member function) | | [insert](insert "cpp/container/unordered multiset/insert") (C++11) | inserts elements or nodes (since C++17) (public member function) | | [erase](erase "cpp/container/unordered multiset/erase") (C++11) | erases elements (public member function) | cpp std::unordered_multiset<Key,Hash,KeyEqual,Allocator>::max_load_factor std::unordered\_multiset<Key,Hash,KeyEqual,Allocator>::max\_load\_factor ======================================================================== | | | | | --- | --- | --- | | ``` float max_load_factor() const; ``` | (1) | (since C++11) | | ``` void max_load_factor( float ml ); ``` | (2) | (since C++11) | Manages the maximum load factor (number of elements per bucket). The container automatically increases the number of buckets if the load factor exceeds this threshold. 1) Returns current maximum load factor. 2) Sets the maximum load factor to `ml`. ### Parameters | | | | | --- | --- | --- | | ml | - | new maximum load factor setting | ### Return value 1) current maximum load factor. 2) none. ### Complexity Constant. ### See also | | | | --- | --- | | [load\_factor](load_factor "cpp/container/unordered multiset/load factor") (C++11) | returns average number of elements per bucket (public member function) | cpp std::unordered_multiset<Key,Hash,KeyEqual,Allocator>::emplace_hint std::unordered\_multiset<Key,Hash,KeyEqual,Allocator>::emplace\_hint ==================================================================== | | | | | --- | --- | --- | | ``` template <class... Args> iterator emplace_hint( const_iterator hint, Args&&... args ); ``` | | (since C++11) | Inserts a new element to the container, using `hint` as a suggestion where the element should go. The element is constructed in-place, i.e. no copy or move operations are performed. The constructor of the element is called with exactly the same arguments as supplied to the function, forwarded with `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Args>(args)...`. If rehashing occurs due to the insertion, all iterators are invalidated. Otherwise iterators are not affected. References are not invalidated. Rehashing occurs only if the new number of elements is greater than `max_load_factor()*bucket_count()`. ### Parameters | | | | | --- | --- | --- | | hint | - | iterator, used as a suggestion as to where to insert the new element | | args | - | arguments to forward to the constructor of the element | ### Return value Returns an iterator to the newly inserted element. ### Exceptions If an exception is thrown by any operation, this function has no effect (strong exception guarantee). ### Complexity Amortized constant on average, worst case linear in the size of the container. ### See also | | | | --- | --- | | [emplace](emplace "cpp/container/unordered multiset/emplace") (C++11) | constructs element in-place (public member function) | | [insert](insert "cpp/container/unordered multiset/insert") (C++11) | inserts elements or nodes (since C++17) (public member function) | cpp std::unordered_multiset<Key,Hash,KeyEqual,Allocator>::hash_function std::unordered\_multiset<Key,Hash,KeyEqual,Allocator>::hash\_function ===================================================================== | | | | | --- | --- | --- | | ``` hasher hash_function() const; ``` | | (since C++11) | Returns the function that hashes the keys. ### Parameters (none). ### Return value The hash function. ### Complexity Constant. ### See also | | | | --- | --- | | [key\_eq](key_eq "cpp/container/unordered multiset/key eq") (C++11) | returns the function used to compare keys for equality (public member function) | cpp std::unordered_multiset<Key,Hash,KeyEqual,Allocator>::swap std::unordered\_multiset<Key,Hash,KeyEqual,Allocator>::swap =========================================================== | | | | | --- | --- | --- | | ``` void swap( unordered_multiset& other ); ``` | | (since C++11) (until C++17) | | ``` void swap( unordered_multiset& other ) noexcept(/* see below */); ``` | | (since C++17) | Exchanges the contents of the container with those of `other`. Does not invoke any move, copy, or swap operations on individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated. The `Hash` and `KeyEqual` objects must be [Swappable](../../named_req/swappable "cpp/named req/Swappable"), and they are exchanged using unqualified calls to non-member `swap`. | | | | --- | --- | | If `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<allocator_type>::propagate\_on\_container\_swap::value` is true, then the allocators are exchanged using an unqualified call to non-member `swap`. Otherwise, they are not swapped (and if `get_allocator() != other.get_allocator()`, the behavior is undefined). | (since C++11) | ### Parameters | | | | | --- | --- | --- | | other | - | container to exchange the contents with | ### Return value (none). ### Exceptions | | | | --- | --- | | Any exception thrown by the swap of the `Hash` or `KeyEqual` objects. | (until C++17) | | [`noexcept`](../../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept([std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<Allocator>::is\_always\_equal::value && [std::is\_nothrow\_swappable](http://en.cppreference.com/w/cpp/types/is_swappable)<Hash>::value. && [std::is\_nothrow\_swappable](http://en.cppreference.com/w/cpp/types/is_swappable)<key_equal>::value)` | (since C++17) | ### Complexity Constant. ### Example ``` #include <iostream> #include <unordered_set> template<class Os, class Co> Os& operator<<(Os& os, const Co& co) { os << "{"; for (auto const& i : co) { os << ' ' << i; } return os << " } "; } int main() { std::unordered_multiset<int> a1{3, 1, 3, 2}, a2{5, 4, 5}; auto it1 = std::next(a1.begin()); auto it2 = std::next(a2.begin()); const int& ref1 = *(a1.begin()); const int& ref2 = *(a2.begin()); std::cout << a1 << a2 << *it1 << ' ' << *it2 << ' ' << ref1 << ' ' << ref2 << '\n'; a1.swap(a2); std::cout << a1 << a2 << *it1 << ' ' << *it2 << ' ' << ref1 << ' ' << ref2 << '\n'; // Note that every iterator referring to an element in one container before the swap // refers to the same element in the other container after the swap. Same is true // for references. } ``` Possible output: ``` { 2 3 3 1 } { 4 5 5 } 3 5 2 4 { 4 5 5 } { 2 3 3 1 } 3 5 2 4 ``` ### See also | | | | --- | --- | | [std::swap(std::unordered\_multiset)](swap2 "cpp/container/unordered multiset/swap2") (C++11) | specializes the `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | cpp std::unordered_multiset<Key,Hash,KeyEqual,Allocator>::max_size std::unordered\_multiset<Key,Hash,KeyEqual,Allocator>::max\_size ================================================================ | | | | | --- | --- | --- | | ``` size_type max_size() const noexcept; ``` | | (since C++11) | Returns the maximum number of elements the container is able to hold due to system or library implementation limitations, i.e. `[std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(begin(), end())` for the largest container. ### Parameters (none). ### Return value Maximum number of elements. ### Complexity Constant. ### Notes This value typically reflects the theoretical limit on the size of the container, at most `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<difference_type>::max()`. At runtime, the size of the container may be limited to a value smaller than `max_size()` by the amount of RAM available. ### Example ``` #include <iostream> #include <locale> #include <unordered_set> int main() { std::unordered_multiset<char> q; std::cout.imbue(std::locale("en_US.UTF-8")); std::cout << "Maximum size of a std::unordered_multiset is " << q.max_size() << '\n'; } ``` Possible output: ``` Maximum size of a std::unordered_multiset is 768,614,336,404,564,650 ``` ### See also | | | | --- | --- | | [size](size "cpp/container/unordered multiset/size") (C++11) | returns the number of elements (public member function) | cpp std::unordered_multiset<Key,Hash,KeyEqual,Allocator>::count std::unordered\_multiset<Key,Hash,KeyEqual,Allocator>::count ============================================================ | | | | | --- | --- | --- | | ``` size_type count( const Key& key ) const; ``` | (1) | (since C++11) | | ``` template< class K > size_type count( const K& x ) const; ``` | (2) | (since C++20) | 1) Returns the number of elements with key that compares equal to the specified argument `key`. 2) Returns the number of elements with key that compares equivalent to the specified argument `x`. This overload participates in overload resolution only if `Hash::is_transparent` and `KeyEqual::is_transparent` are valid and each denotes a type. This assumes that such `Hash` is callable with both `K` and `Key` type, and that the `KeyEqual` is transparent, which, together, allows calling this function without constructing an instance of `Key`. ### Parameters | | | | | --- | --- | --- | | key | - | key value of the elements to count | | x | - | a value of any type that can be transparently compared with a key | ### Return value 1) Number of elements with key `key`. 2) Number of elements with key that compares equivalent to `x`. ### Complexity linear in the number of elements with key `key` on average, worst case linear in the size of the container. ### Notes | [Feature-test](../../utility/feature_test "cpp/utility/feature test") macro | Comment | | --- | --- | | [`__cpp_lib_generic_unordered_lookup`](../../feature_test#Library_features "cpp/feature test") | for overload (2) | ### Example ``` #include <algorithm> #include <iostream> #include <unordered_set> int main() { std::unordered_multiset set{2, 7, 1, 8, 2, 8, 1, 8, 2, 8}; std::cout << "The set is:\n"; for (int e: set) { std::cout << e << ' '; } const auto [min, max] = std::ranges::minmax(set); std::cout << "\nNumbers [" << min << ".." << max << "] frequency:\n"; for (int i{min}; i <= max; ++i) { std::cout << i << ':' << set.count(i) << "; "; } } ``` Possible output: ``` The set is: 8 8 8 8 1 1 7 2 2 2 Numbers [1..8] frequency: 1:2; 2:3; 3:0; 4:0; 5:0; 6:0; 7:1; 8:4; ``` ### See also | | | | --- | --- | | [find](find "cpp/container/unordered multiset/find") (C++11) | finds element with specific key (public member function) | | [contains](contains "cpp/container/unordered multiset/contains") (C++20) | checks if the container contains element with specific key (public member function) | | [equal\_range](equal_range "cpp/container/unordered multiset/equal range") (C++11) | returns range of elements matching a specific key (public member function) | cpp std::unordered_multiset<Key,Hash,KeyEqual,Allocator>::bucket_size std::unordered\_multiset<Key,Hash,KeyEqual,Allocator>::bucket\_size =================================================================== | | | | | --- | --- | --- | | ``` size_type bucket_size( size_type n ) const; ``` | | (since C++11) | Returns the number of elements in the bucket with index `n`. ### Parameters | | | | | --- | --- | --- | | n | - | the index of the bucket to examine | ### Return value The number of elements in the bucket `n`. ### Complexity Linear in the size of the bucket `n`. ### See also | | | | --- | --- | | [bucket\_count](bucket_count "cpp/container/unordered multiset/bucket count") (C++11) | returns the number of buckets (public member function) | cpp std::unordered_multiset<Key,Hash,KeyEqual,Allocator>::max_bucket_count std::unordered\_multiset<Key,Hash,KeyEqual,Allocator>::max\_bucket\_count ========================================================================= | | | | | --- | --- | --- | | ``` size_type max_bucket_count() const; ``` | | (since C++11) | Returns the maximum number of buckets the container is able to hold due to system or library implementation limitations. ### Parameters (none). ### Return value Maximum number of buckets. ### Complexity Constant. ### Example ``` #include <iostream> #include <unordered_set> int main() { struct Ha { std::size_t operator()(long x) const { return std::hash<long>{}(x); }; }; auto c1 = std::unordered_multiset<char>{}; auto c2 = std::unordered_multiset<long>{}; auto c3 = std::unordered_multiset<long, std::hash<int>>{}; auto c4 = std::unordered_multiset<long, Ha>{}; std::cout << "Max bucket count of\n" << std::hex << std::showbase << "c1: " << c1.max_bucket_count() << '\n' << "c2: " << c2.max_bucket_count() << '\n' << "c3: " << c3.max_bucket_count() << '\n' << "c4: " << c4.max_bucket_count() << '\n' ; } ``` Possible output: ``` Max bucket count of c1: 0xfffffffffffffff c2: 0xfffffffffffffff c3: 0xfffffffffffffff c4: 0xaaaaaaaaaaaaaaa ``` ### See also | | | | --- | --- | | [bucket\_count](bucket_count "cpp/container/unordered multiset/bucket count") (C++11) | returns the number of buckets (public member function) | cpp std::unordered_multiset<Key,Hash,KeyEqual,Allocator>::find std::unordered\_multiset<Key,Hash,KeyEqual,Allocator>::find =========================================================== | | | | | --- | --- | --- | | ``` iterator find( const Key& key ); ``` | (1) | | | ``` const_iterator find( const Key& key ) const; ``` | (2) | | | ``` template< class K > iterator find( const K& x ); ``` | (3) | (since C++20) | | ``` template< class K > const_iterator find( const K& x ) const; ``` | (4) | (since C++20) | 1,2) Finds an element with key equivalent to `key`. 3,4) Finds an element with key that compares *equivalent* to the value `x`. This overload participates in overload resolution only if `Hash::is_transparent` and `KeyEqual::is_transparent` are valid and each denotes a type. This assumes that such `Hash` is callable with both `K` and `Key` type, and that the `KeyEqual` is transparent, which, together, allows calling this function without constructing an instance of `Key`. ### Parameters | | | | | --- | --- | --- | | key | - | key value of the element to search for | | x | - | a value of any type that can be transparently compared with a key | ### Return value Iterator to an element with key equivalent to `key`. If no such element is found, past-the-end (see `[end()](end "cpp/container/unordered multiset/end")`) iterator is returned. ### Complexity Constant on average, worst case linear in the size of the container. ### Notes | [Feature-test](../../utility/feature_test "cpp/utility/feature test") macro | Comment | | --- | --- | | [`__cpp_lib_generic_unordered_lookup`](../../feature_test#Library_features "cpp/feature test") | for overloads (3,4) | ### Example ``` #include <iostream> #include <unordered_set> int main() { // simple comparison demo std::unordered_multiset<int> example = {1, 2, 3, 4}; auto search = example.find(2); if (search != example.end()) { std::cout << "Found " << (*search) << '\n'; } else { std::cout << "Not found\n"; } } ``` Output: ``` Found 2 ``` ### See also | | | | --- | --- | | [count](count "cpp/container/unordered multiset/count") (C++11) | returns the number of elements matching specific key (public member function) | | [equal\_range](equal_range "cpp/container/unordered multiset/equal range") (C++11) | returns range of elements matching a specific key (public member function) | cpp std::unordered_multiset<Key,Hash,KeyEqual,Allocator>::equal_range std::unordered\_multiset<Key,Hash,KeyEqual,Allocator>::equal\_range =================================================================== | | | | | --- | --- | --- | | ``` std::pair<iterator,iterator> equal_range( const Key& key ); ``` | (1) | (since C++11) | | ``` std::pair<const_iterator,const_iterator> equal_range( const Key& key ) const; ``` | (2) | (since C++11) | | ``` template< class K > std::pair<iterator,iterator> equal_range( const K& x ); ``` | (3) | (since C++20) | | ``` template< class K > std::pair<const_iterator,const_iterator> equal_range( const K& x ) const; ``` | (4) | (since C++20) | 1,2) Returns a range containing all elements with key `key` in the container. The range is defined by two iterators, the first pointing to the first element of the wanted range and the second pointing past the last element of the range. 3,4) Returns a range containing all elements in the container with key equivalent to `x`. This overload participates in overload resolution only if `Hash::is_transparent` and `KeyEqual::is_transparent` are valid and each denotes a type. This assumes that such `Hash` is callable with both `K` and `Key` type, and that the `KeyEqual` is transparent, which, together, allows calling this function without constructing an instance of `Key`. ### Parameters | | | | | --- | --- | --- | | key | - | key value to compare the elements to | | x | - | a value of any type that can be transparently compared with a key | ### Return value `[std::pair](../../utility/pair "cpp/utility/pair")` containing a pair of iterators defining the wanted range. If there are no such elements, past-the-end (see `[end()](end "cpp/container/unordered multiset/end")`) iterators are returned as both elements of the pair. ### Complexity Average case linear in the number of elements with the key `key`, worst case linear in the size of the container. ### Notes | [Feature-test](../../utility/feature_test "cpp/utility/feature test") macro | Comment | | --- | --- | | [`__cpp_lib_generic_unordered_lookup`](../../feature_test#Library_features "cpp/feature test") | for overloads (3,4) | ### Example Estimates the characters frequency for given string. ``` #include <iostream> #include <iterator> #include <string> #include <unordered_set> int main() { std::string sentence{"cppreference.com"}; std::cout << "The sentence: " << sentence << '\n'; std::unordered_multiset<char> sequence; for (char x : sentence) { sequence.insert(x); } std::cout << "The sequence: { "; for (char x : sequence) { std::cout << x << ' '; } std::cout << "}\n" "Symbol:Frequency: "; for (auto it = sequence.begin(); it != sequence.end(); ) { if (auto [first, last] = sequence.equal_range(*it); first != last) { std::cout << *first << ":" << std::distance(first, last) << " "; it = last; } else { ++it; } } } ``` Possible output: ``` The sentence: cppreference.com The sequence: { m o c c c p p r r e e e e f n . } Symbol:Frequency: m:1 o:1 c:3 p:2 r:2 e:4 f:1 n:1 .:1 ``` ### See also | | | | --- | --- | | [find](find "cpp/container/unordered multiset/find") (C++11) | finds element with specific key (public member function) | | [contains](contains "cpp/container/unordered multiset/contains") (C++20) | checks if the container contains element with specific key (public member function) | | [count](count "cpp/container/unordered multiset/count") (C++11) | returns the number of elements matching specific key (public member function) | | [equal\_range](../../algorithm/equal_range "cpp/algorithm/equal range") | returns range of elements matching a specific key (function template) |
programming_docs
cpp std::unordered_multiset<Key,Hash,KeyEqual,Allocator>::unordered_multiset std::unordered\_multiset<Key,Hash,KeyEqual,Allocator>::unordered\_multiset ========================================================================== | | | | | --- | --- | --- | | ``` unordered_multiset() : unordered_multiset( size_type(/*implementation-defined*/) ) {} explicit unordered_multiset( size_type bucket_count, const Hash& hash = Hash(), const key_equal& equal = key_equal(), const Allocator& alloc = Allocator() ); ``` | (1) | (since C++11) | | ``` unordered_multiset( size_type bucket_count, const Allocator& alloc ) : unordered_multiset(bucket_count, Hash(), key_equal(), alloc) {} unordered_multiset( size_type bucket_count, const Hash& hash, const Allocator& alloc ) : unordered_multiset(bucket_count, hash, key_equal(), alloc) {} ``` | (1) | (since C++14) | | ``` explicit unordered_multiset( const Allocator& alloc ); ``` | (1) | (since C++11) | | ``` template< class InputIt > unordered_multiset( InputIt first, InputIt last, size_type bucket_count = /*implementation-defined*/, const Hash& hash = Hash(), const key_equal& equal = key_equal(), const Allocator& alloc = Allocator() ); ``` | (2) | (since C++11) | | ``` template< class InputIt > unordered_multiset( InputIt first, InputIt last, size_type bucket_count, const Allocator& alloc ) : unordered_multiset(first, last, bucket_count, Hash(), key_equal(), alloc) {} ``` | (2) | (since C++14) | | ``` template< class InputIt > unordered_multiset( InputIt first, InputIt last, size_type bucket_count, const Hash& hash, const Allocator& alloc ) : unordered_multiset(first, last, bucket_count, hash, key_equal(), alloc) {} ``` | (2) | (since C++14) | | ``` unordered_multiset( const unordered_multiset& other ); ``` | (3) | (since C++11) | | ``` unordered_multiset( const unordered_multiset& other, const Allocator& alloc ); ``` | (3) | (since C++11) | | ``` unordered_multiset( unordered_multiset&& other ); ``` | (4) | (since C++11) | | ``` unordered_multiset( unordered_multiset&& other, const Allocator& alloc ); ``` | (4) | (since C++11) | | ``` unordered_multiset( std::initializer_list<value_type> init, size_type bucket_count = /*implementation-defined*/, const Hash& hash = Hash(), const key_equal& equal = key_equal(), const Allocator& alloc = Allocator() ); ``` | (5) | (since C++11) | | ``` unordered_multiset( std::initializer_list<value_type> init, size_type bucket_count, const Allocator& alloc ) : unordered_multiset(init, bucket_count, Hash(), key_equal(), alloc) {} ``` | (5) | (since C++14) | | ``` unordered_multiset( std::initializer_list<value_type> init, size_type bucket_count, const Hash& hash, const Allocator& alloc ) : unordered_multiset(init, bucket_count, hash, key_equal(), alloc) {} ``` | (5) | (since C++14) | Constructs new container from a variety of data sources. Optionally uses user supplied `bucket_count` as a minimal number of buckets to create, `hash` as the hash function, `equal` as the function to compare keys and `alloc` as the allocator. 1) Constructs empty container. Sets `[max\_load\_factor()](max_load_factor "cpp/container/unordered multiset/max load factor")` to 1.0. For the default constructor, the number of buckets is implementation-defined. 2) constructs the container with the contents of the range `[first, last)`. Sets `[max\_load\_factor()](max_load_factor "cpp/container/unordered multiset/max load factor")` to 1.0. 3) copy constructor. Constructs the container with the copy of the contents of `other`, copies the load factor, the predicate, and the hash function as well. If `alloc` is not provided, allocator is obtained by calling `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<allocator_type>::select\_on\_container\_copy\_construction(other.get\_allocator())`. | | | | --- | --- | | The template parameter `Allocator` is only deduced from the first argument while used in [class template argument deduction](../../language/class_template_argument_deduction "cpp/language/class template argument deduction"). | (since C++23) | 4) move constructor. Constructs the container with the contents of `other` using move semantics. If `alloc` is not provided, allocator is obtained by move-construction from the allocator belonging to `other`. | | | | --- | --- | | The template parameter `Allocator` is only deduced from the first argument while used in [class template argument deduction](../../language/class_template_argument_deduction "cpp/language/class template argument deduction"). | (since C++23) | 5) constructs the container with the contents of the initializer list `init`, same as `unordered_multiset(init.begin(), init.end())`. ### Parameters | | | | | --- | --- | --- | | alloc | - | allocator to use for all memory allocations of this container | | bucket\_count | - | minimal number of buckets to use on initialization. If it is not specified, implementation-defined default value is used | | hash | - | hash function to use | | equal | - | comparison function to use for all key comparisons of this container | | first, last | - | the range to copy the elements from | | other | - | another container to be used as source to initialize the elements of the container with | | init | - | initializer list to initialize the elements of the container with | | Type requirements | | -`InputIt` must meet the requirements of [LegacyInputIterator](../../named_req/inputiterator "cpp/named req/InputIterator"). | ### Complexity 1) constant 2) average case linear worst case quadratic in distance between `first` and `last` 3) linear in size of `other` 4) constant. If `alloc` is given and `alloc != other.get_allocator()`, then linear. 5) average case linear worst case quadratic in size of `init` ### Exceptions Calls to `Allocator::allocate` may throw. ### Notes After container move construction (overload (4)), references, pointers, and iterators (other than the end iterator) to `other` remain valid, but refer to elements that are now in `*this`. The current standard makes this guarantee via the blanket statement in [[container.requirements.general]/12](https://eel.is/c++draft/container.requirements.general#12), and a more direct guarantee is under consideration via [LWG 2321](https://cplusplus.github.io/LWG/issue2321). Although not formally required until C++23, some implementations has already put the template parameter `Allocator` into [non-deduced contexts](../../language/template_argument_deduction#Non-deduced_contexts "cpp/language/template argument deduction") in earlier modes. ### Example ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 2193](https://cplusplus.github.io/LWG/issue2193) | C++11 | the default constructor is explicit | made non-explicit | ### See also | | | | --- | --- | | [operator=](operator= "cpp/container/unordered multiset/operator=") (C++11) | assigns values to the container (public member function) | cpp std::unordered_multiset<Key,Hash,KeyEqual,Allocator>::erase std::unordered\_multiset<Key,Hash,KeyEqual,Allocator>::erase ============================================================ | | | | | --- | --- | --- | | | (1) | | | ``` iterator erase( iterator pos ); ``` | (since C++11) | | ``` iterator erase( const_iterator pos ); ``` | (since C++11) | | | (2) | | | ``` iterator erase( const_iterator first, const_iterator last ); ``` | (since C++11) | | ``` size_type erase( const Key& key ); ``` | (3) | (since C++11) | | ``` template< class K > size_type erase( K&& x ); ``` | (4) | (since C++23) | Removes specified elements from the container. 1) Removes the element at `pos`. Only one overload is provided if `iterator` and `const_iterator` are the same type. 2) Removes the elements in the range `[first; last)`, which must be a valid range in `*this`. 3) Removes all elements with the key equivalent to `key`. 4) Removes all elements with key that compares *equivalent* to the value `x`. This overload participates in overload resolution only if `Hash::is_transparent` and `KeyEqual::is_transparent` are valid and each denotes a type, and neither `iterator` nor `const_iterator` is implicitly convertible from `K`. This assumes that such `Hash` is callable with both `K` and `Key` type, and that the `KeyEqual` is transparent, which, together, allows calling this function without constructing an instance of `Key`. References and iterators to the erased elements are invalidated. Other iterators and references are not invalidated. The iterator `pos` must be valid and dereferenceable. Thus the `[end()](end "cpp/container/unordered multiset/end")` iterator (which is valid, but is not dereferenceable) cannot be used as a value for `pos`. The order of the elements that are not erased is preserved. (This makes it possible to erase individual elements while iterating through the container.). ### Parameters | | | | | --- | --- | --- | | pos | - | iterator to the element to remove | | first, last | - | range of elements to remove | | key | - | key value of the elements to remove | | x | - | a value of any type that can be transparently compared with a key denoting the elements to remove | ### Return value 1-2) Iterator following the last removed element. 3,4) Number of elements removed. ### Exceptions 1,2) Throws nothing. 3,4) Any exceptions thrown by the `Hash` and `KeyEqual` object. ### Complexity Given an instance `c` of `unordered_multiset`: 1) Average case: constant, worst case: `c.size()` 2) Average case: `[std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(first, last)`, worst case: `c.size()` 3) Average case: `c.count(key)`, worst case: `c.size()` 4) Average case: `c.count(x)`, worst case: `c.size()` ### Notes | [Feature-test](../../utility/feature_test "cpp/utility/feature test") macro | Comment | | --- | --- | | [`__cpp_lib_associative_heterogeneous_erasure`](../../feature_test#Library_features "cpp/feature test") | for overload (4) | ### Example ``` #include <unordered_set> #include <iostream> int main() { std::unordered_multiset<int> c = { 1, 2, 3, 4, 1, 2, 3, 4 }; auto print = [&c] { std::cout << "c = { "; for(int n : c) std::cout << n << ' '; std::cout << "}\n"; }; print(); std::cout << "Erase all odd numbers:\n"; for(auto it = c.begin(); it != c.end(); ) { if(*it % 2 != 0) it = c.erase(it); else ++it; } print(); std::cout << "Erase 1, erased count: " << c.erase(1) << '\n'; std::cout << "Erase 2, erased count: " << c.erase(2) << '\n'; std::cout << "Erase 2, erased count: " << c.erase(2) << '\n'; print(); } ``` Possible output: ``` c = { 1 1 2 2 3 3 4 4 } Erase all odd numbers: c = { 2 2 4 4 } Erase 1, erased count: 0 Erase 2, erased count: 2 Erase 2, erased count: 0 c = { 4 4 } ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 2059](https://cplusplus.github.io/LWG/issue2059) | C++11 | overload for one `const_iterator` introduced new ambiguity | overload for `iterator` added | | [LWG 2356](https://cplusplus.github.io/LWG/issue2356) | C++11 | the order of element that are not erased was unspecified | required to be preserved | ### See also | | | | --- | --- | | [clear](clear "cpp/container/unordered multiset/clear") (C++11) | clears the contents (public member function) | cpp std::unordered_multiset<Key,Hash,KeyEqual,Allocator>::load_factor std::unordered\_multiset<Key,Hash,KeyEqual,Allocator>::load\_factor =================================================================== | | | | | --- | --- | --- | | ``` float load_factor() const; ``` | | (since C++11) | Returns the average number of elements per bucket, that is, `[size()](size "cpp/container/unordered multiset/size")` divided by `[bucket\_count()](bucket_count "cpp/container/unordered multiset/bucket count")`. ### Parameters (none). ### Return value Average number of elements per bucket. ### Complexity Constant. ### See also | | | | --- | --- | | [max\_load\_factor](max_load_factor "cpp/container/unordered multiset/max load factor") (C++11) | manages maximum average number of elements per bucket (public member function) | cpp std::swap(std::unordered_multiset) std::swap(std::unordered\_multiset) =================================== | Defined in header `[<unordered\_set>](../../header/unordered_set "cpp/header/unordered set")` | | | | --- | --- | --- | | ``` template< class Key, class Hash, class KeyEqual, class Alloc > void swap( std::unordered_multiset<Key,Hash,KeyEqual,Alloc>& lhs, std::unordered_multiset<Key,Hash,KeyEqual,Alloc>& rhs ); ``` | | (since C++11) (until C++17) | | ``` template< class Key, class Hash, class KeyEqual, class Alloc > void swap( std::unordered_multiset<Key,Hash,KeyEqual,Alloc>& lhs, std::unordered_multiset<Key,Hash,KeyEqual,Alloc>& rhs ) noexcept(/* see below */); ``` | | (since C++17) | Specializes the `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` algorithm for `[std::unordered\_multiset](http://en.cppreference.com/w/cpp/container/unordered_multiset)`. Swaps the contents of `lhs` and `rhs`. Calls `lhs.swap(rhs)`. ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | containers whose contents to swap | ### Return value (none). ### Complexity Constant. ### Exceptions | | | | --- | --- | | [`noexcept`](../../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept(noexcept(lhs.swap(rhs)))` | (since C++17) | ### Notes Although the overloads of `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` for container adaptors are introduced in C++11, container adaptors can already be swapped by `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` in C++98. Such calls to `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` usually have linear time complexity, but better complexity may be provided. ### Example ``` #include <algorithm> #include <iostream> #include <unordered_set> int main() { std::unordered_multiset<int> alice{1, 2, 3}; std::unordered_multiset<int> bob{7, 8, 9, 10}; auto print = [](const int& n) { std::cout << ' ' << n; }; // Print state before swap std::cout << "alice:"; std::for_each(alice.begin(), alice.end(), print); std::cout << "\n" "bob :"; std::for_each(bob.begin(), bob.end(), print); std::cout << '\n'; std::cout << "-- SWAP\n"; std::swap(alice, bob); // Print state after swap std::cout << "alice:"; std::for_each(alice.begin(), alice.end(), print); std::cout << "\n" "bob :"; std::for_each(bob.begin(), bob.end(), print); std::cout << '\n'; } ``` Possible output: ``` alice: 1 2 3 bob : 7 8 9 10 -- SWAP alice: 7 8 9 10 bob : 1 2 3 ``` ### See also | | | | --- | --- | | [swap](swap "cpp/container/unordered multiset/swap") (C++11) | swaps the contents (public member function) | cpp std::unordered_multiset<Key,Hash,KeyEqual,Allocator>::operator= std::unordered\_multiset<Key,Hash,KeyEqual,Allocator>::operator= ================================================================ | | | | | --- | --- | --- | | ``` unordered_multiset& operator=( const unordered_multiset& other ); ``` | (1) | (since C++11) | | | (2) | | | ``` unordered_multiset& operator=( unordered_multiset&& other ); ``` | (since C++11) (until C++17) | | ``` unordered_multiset& operator=( unordered_multiset&& other ) noexcept(/* see below */); ``` | (since C++17) | | ``` unordered_multiset& operator=( std::initializer_list<value_type> ilist ); ``` | (3) | (since C++11) | Replaces the contents of the container. 1) Copy assignment operator. Replaces the contents with a copy of the contents of `other`. If `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<allocator_type>::propagate\_on\_container\_copy\_assignment::value` is `true`, the allocator of `*this` is replaced by a copy of that of `other`. If the allocator of `*this` after assignment would compare unequal to its old value, the old allocator is used to deallocate the memory, then the new allocator is used to allocate it before copying the elements. Otherwise, the memory owned by `*this` may be reused when possible. In any case, the elements originally belonging to `*this` may be either destroyed or replaced by element-wise copy-assignment. 2) Move assignment operator. Replaces the contents with those of `other` using move semantics (i.e. the data in `other` is moved from `other` into this container). `other` is in a valid but unspecified state afterwards. If `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<allocator_type>::propagate\_on\_container\_move\_assignment::value` is `true`, the allocator of `*this` is replaced by a copy of that of `other`. If it is `false` and the allocators of `*this` and `other` do not compare equal, `*this` cannot take ownership of the memory owned by `other` and must move-assign each element individually, allocating additional memory using its own allocator as needed. In any case, all elements originally belonging to `*this` are either destroyed or replaced by element-wise move-assignment. 3) Replaces the contents with those identified by initializer list `ilist`. ### Parameters | | | | | --- | --- | --- | | other | - | another container to use as data source | | ilist | - | initializer list to use as data source | ### Return value `*this`. ### Complexity 1) Linear in the size of `*this` and `other`. 2) Linear in the size of `*this` unless the allocators do not compare equal and do not propagate, in which case linear in the size of `*this` and `other`. 3) Linear in the size of `*this` and `ilist`. ### Exceptions | | | | --- | --- | | May throw implementation-defined exceptions. | (until C++17) | | 1,3) May throw implementation-defined exceptions. 2) [`noexcept`](../../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept([std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<Allocator>::is\_always\_equal::value && [std::is\_nothrow\_move\_assignable](http://en.cppreference.com/w/cpp/types/is_move_assignable)<Hash>::value. && [std::is\_nothrow\_move\_assignable](http://en.cppreference.com/w/cpp/types/is_move_assignable)<Pred>::value)` | (since C++17) | ### Notes After container move assignment (overload (2)), unless element-wise move assignment is forced by incompatible allocators, references, pointers, and iterators (other than the end iterator) to `other` remain valid, but refer to elements that are now in `*this`. The current standard makes this guarantee via the blanket statement in [[container.requirements.general]/12](https://eel.is/c++draft/container.requirements.general#12), and a more direct guarantee is under consideration via [LWG 2321](https://cplusplus.github.io/LWG/issue2321). ### Example The following code uses `operator=` to assign one `[std::unordered\_multiset](../unordered_multiset "cpp/container/unordered multiset")` to another: ``` #include <unordered_set> #include <iterator> #include <iostream> void print(auto const comment, auto const& container) { auto size = std::size(container); std::cout << comment << "{ "; for (auto const& element: container) std::cout << element << (--size ? ", " : " "); std::cout << "}\n"; } int main() { std::unordered_multiset<int> x { 1, 2, 3 }, y, z; const auto w = { 4, 5, 6, 7 }; std::cout << "Initially:\n"; print("x = ", x); print("y = ", y); print("z = ", z); std::cout << "Copy assignment copies data from x to y:\n"; y = x; print("x = ", x); print("y = ", y); std::cout << "Move assignment moves data from x to z, modifying both x and z:\n"; z = std::move(x); print("x = ", x); print("z = ", z); std::cout << "Assignment of initializer_list w to z:\n"; z = w; print("w = ", w); print("z = ", z); } ``` Possible output: ``` Initially: x = { 3, 2, 1 } y = { } z = { } Copy assignment copies data from x to y: x = { 3, 2, 1 } y = { 3, 2, 1 } Move assignment moves data from x to z, modifying both x and z: x = { } z = { 3, 2, 1 } Assignment of initializer_list w to z: w = { 4, 5, 6, 7 } z = { 7, 6, 5, 4 } ``` ### See also | | | | --- | --- | | [(constructor)](unordered_multiset "cpp/container/unordered multiset/unordered multiset") (C++11) | constructs the `unordered_multiset` (public member function) |
programming_docs
cpp std::unordered_multiset<Key,Hash,KeyEqual,Allocator>::clear std::unordered\_multiset<Key,Hash,KeyEqual,Allocator>::clear ============================================================ | | | | | --- | --- | --- | | ``` void clear() noexcept; ``` | | (since C++11) | Erases all elements from the container. After this call, `[size()](size "cpp/container/unordered multiset/size")` returns zero. Invalidates any references, pointers, or iterators referring to contained elements. May also invalidate past-the-end iterators. ### Parameters (none). ### Return value (none). ### Complexity Linear in the size of the container, i.e., the number of elements. ### Example ``` #include <algorithm> #include <iostream> #include <unordered_set> int main() { std::unordered_multiset<int> container{1, 2, 3}; auto print = [](const int& n) { std::cout << " " << n; }; std::cout << "Before clear:"; std::for_each(container.begin(), container.end(), print); std::cout << "\nSize=" << container.size() << '\n'; std::cout << "Clear\n"; container.clear(); std::cout << "After clear:"; std::for_each(container.begin(), container.end(), print); std::cout << "\nSize=" << container.size() << '\n'; } ``` Possible output: ``` Before clear: 1 2 3 Size=3 Clear After clear: Size=0 ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 2550](https://cplusplus.github.io/LWG/issue2550) | C++11 | for unordered associative containers, unclear if complexity is linear in the number of elements or buckets | clarified that it's linear in the number of elements | ### See also | | | | --- | --- | | [erase](erase "cpp/container/unordered multiset/erase") (C++11) | erases elements (public member function) | cpp std::unordered_multiset<Key,Hash,KeyEqual,Allocator>::~unordered_multiset std::unordered\_multiset<Key,Hash,KeyEqual,Allocator>::~unordered\_multiset =========================================================================== | | | | | --- | --- | --- | | ``` ~unordered_multiset(); ``` | | (since C++11) | Destructs the `unordered_multiset`. The destructors of the elements are called and the used storage is deallocated. Note, that if the elements are pointers, the pointed-to objects are not destroyed. ### Complexity Linear in the size of the `unordered_multiset`. cpp std::unordered_multiset<Key,Hash,KeyEqual,Allocator>::rehash std::unordered\_multiset<Key,Hash,KeyEqual,Allocator>::rehash ============================================================= | | | | | --- | --- | --- | | ``` void rehash( size_type count ); ``` | | (since C++11) | Sets the number of buckets to `count` and rehashes the container, i.e. puts the elements into appropriate buckets considering that total number of buckets has changed. If the new number of buckets makes load factor more than maximum load factor (`count < size() / max_load_factor()`), then the new number of buckets is at least `size() / max_load_factor()`. ### Parameters | | | | | --- | --- | --- | | count | - | new number of buckets | ### Return value (none). ### Complexity Average case linear in the size of the container, worst case quadratic. ### Notes `rehash(0)` may be used to force an unconditional rehash, such as after suspension of automatic rehashing by temporarily increasing `max_load_factor()`. ### See also | | | | --- | --- | | [reserve](reserve "cpp/container/unordered multiset/reserve") (C++11) | reserves space for at least the specified number of elements and regenerates the hash table (public member function) | cpp std::unordered_multiset<Key,Hash,KeyEqual,Allocator>::key_eq std::unordered\_multiset<Key,Hash,KeyEqual,Allocator>::key\_eq ============================================================== | | | | | --- | --- | --- | | ``` key_equal key_eq() const; ``` | | (since C++11) | Returns the function that compares keys for equality. ### Parameters (none). ### Return value The key comparison function. ### Complexity Constant. ### See also | | | | --- | --- | | [hash\_function](hash_function "cpp/container/unordered multiset/hash function") (C++11) | returns function used to hash the keys (public member function) | cpp std::unordered_multiset<Key,Hash,KeyEqual,Allocator>::end(size_type), std::unordered_multiset<Key,Hash,KeyEqual,Allocator>::cend(size_type) std::unordered\_multiset<Key,Hash,KeyEqual,Allocator>::end(size\_type), std::unordered\_multiset<Key,Hash,KeyEqual,Allocator>::cend(size\_type) =============================================================================================================================================== | | | | | --- | --- | --- | | ``` local_iterator end( size_type n ); ``` | | (since C++11) | | ``` const_local_iterator end( size_type n ) const; ``` | | (since C++11) | | ``` const_local_iterator cend( size_type n ) const; ``` | | (since C++11) | Returns an iterator to the element following the last element of the bucket with index `n`. . This element acts as a placeholder, attempting to access it results in undefined behavior. ### Parameters | | | | | --- | --- | --- | | n | - | the index of the bucket to access | ### Return value iterator to the element following the last element. ### Complexity Constant. ### See also | | | | --- | --- | | [begin(size\_type) cbegin(size\_type)](begin2 "cpp/container/unordered multiset/begin2") (C++11) | returns an iterator to the beginning of the specified bucket (public member function) | cpp operator==,!=(std::unordered_multiset) operator==,!=(std::unordered\_multiset) ======================================= | | | | | --- | --- | --- | | ``` template< class Key, class Hash, class KeyEqual, class Alloc > bool operator==( const std::unordered_multiset<Key,Hash,KeyEqual,Alloc>& lhs, const std::unordered_multiset<Key,Hash,KeyEqual,Alloc>& rhs ); ``` | (1) | | | ``` template< class Key, class Hash, class KeyEqual, class Alloc > bool operator!=( const std::unordered_multiset<Key,Hash,KeyEqual,Alloc>& lhs, const std::unordered_multiset<Key,Hash,KeyEqual,Alloc>& rhs ); ``` | (2) | (until C++20) | Compares the contents of two unordered containers. The contents of two unordered containers `lhs` and `rhs` are equal if the following conditions hold: * `lhs.size() == rhs.size()` * each group of equivalent elements `[lhs_eq1, lhs_eq2)` obtained from `lhs.equal_range(lhs_eq1)` has a corresponding group of equivalent elements in the other container `[rhs_eq1, rhs_eq2)` obtained from `rhs.equal_range(rhs_eq1)`, that has the following properties: + `[std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(lhs_eq1, lhs_eq2) == [std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(rhs_eq1, rhs_eq2)`. + `[std::is\_permutation](http://en.cppreference.com/w/cpp/algorithm/is_permutation)(lhs_eq1, lhs_eq2, rhs_eq1) == true`. The behavior is undefined if `Key` is not [EqualityComparable](../../named_req/equalitycomparable "cpp/named req/EqualityComparable"). The behavior is also undefined if `hash_function()` and `key_eq()` do (until C++20)`key_eq()` does (since C++20) not have the same behavior on `lhs` and `rhs` or if `operator==` for `Key` is not a refinement of the partition into equivalent-key groups introduced by `key_eq()` (that is, if two elements that compare equal using `operator==` fall into different partitions). | | | | --- | --- | | The `!=` operator is [synthesized](../../language/operators#Relational_operators "cpp/language/operators") from `operator==`. | (since C++20) | ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | unordered containers to compare | ### Return value 1) `true` if the contents of the containers are equal, `false` otherwise 2) `true` if the contents of the containers are not equal, `false` otherwise ### Complexity Proportional to *ΣSi2* calls to `operator==` on `value_type`, calls to the predicate returned by [`key_eq`](key_eq "cpp/container/unordered multiset/key eq"), and calls to the hasher returned by [`hash_function`](hash_function "cpp/container/unordered multiset/hash function") in the average case, where *S* is the size of the *i*th equivalent key group. Proportional to *N2* in the worst case, where *N* is the size of the container. Average case becomes proportional to *N* if the elements within each equivalent key group are arranged in the same order (happens when the containers are copies of each other). cpp std::unordered_multiset<Key,Hash,KeyEqual,Allocator>::reserve std::unordered\_multiset<Key,Hash,KeyEqual,Allocator>::reserve ============================================================== | | | | | --- | --- | --- | | ``` void reserve( size_type count ); ``` | | (since C++11) | Sets the number of buckets to the number needed to accomodate at least `count` elements without exceeding maximum load factor and rehashes the container, i.e. puts the elements into appropriate buckets considering that total number of buckets has changed. Effectively calls `rehash([std::ceil](http://en.cppreference.com/w/cpp/numeric/math/ceil)(count / max_load_factor()))`. ### Parameters | | | | | --- | --- | --- | | count | - | new capacity of the container | ### Return value (none). ### Complexity Average case linear in the size of the container, worst case quadratic. ### See also | | | | --- | --- | | [rehash](rehash "cpp/container/unordered multiset/rehash") (C++11) | reserves at least the specified number of buckets and regenerates the hash table (public member function) | cpp std::unordered_multiset<Key,Hash,KeyEqual,Allocator>::empty std::unordered\_multiset<Key,Hash,KeyEqual,Allocator>::empty ============================================================ | | | | | --- | --- | --- | | ``` bool empty() const noexcept; ``` | | (since C++11) (until C++20) | | ``` [[nodiscard]] bool empty() const noexcept; ``` | | (since C++20) | Checks if the container has no elements, i.e. whether `begin() == end()`. ### Parameters (none). ### Return value `true` if the container is empty, `false` otherwise. ### Complexity Constant. ### Example The following code uses `empty` to check if a `[std::unordered\_multiset](http://en.cppreference.com/w/cpp/container/unordered_multiset)<int>` contains any elements: ``` #include <unordered_set> #include <iostream> int main() { std::unordered_multiset<int> numbers; std::cout << std::boolalpha; std::cout << "Initially, numbers.empty(): " << numbers.empty() << '\n'; numbers.insert(42); numbers.insert(13317); std::cout << "After adding elements, numbers.empty(): " << numbers.empty() << '\n'; } ``` Output: ``` Initially, numbers.empty(): true After adding elements, numbers.empty(): false ``` ### See also | | | | --- | --- | | [size](size "cpp/container/unordered multiset/size") (C++11) | returns the number of elements (public member function) | | [empty](../../iterator/empty "cpp/iterator/empty") (C++17) | checks whether the container is empty (function template) | cpp std::unordered_multiset<Key,Hash,KeyEqual,Allocator>::begin, std::unordered_multiset<Key,Hash,KeyEqual,Allocator>::cbegin std::unordered\_multiset<Key,Hash,KeyEqual,Allocator>::begin, std::unordered\_multiset<Key,Hash,KeyEqual,Allocator>::cbegin =========================================================================================================================== | | | | | --- | --- | --- | | ``` iterator begin() noexcept; ``` | | (since C++11) | | ``` const_iterator begin() const noexcept; ``` | | (since C++11) | | ``` const_iterator cbegin() const noexcept; ``` | | (since C++11) | Returns an iterator to the first element of the `unordered_multiset`. If the `unordered_multiset` is empty, the returned iterator will be equal to `[end()](end "cpp/container/unordered multiset/end")`. ![range-begin-end.svg]() ### Parameters (none). ### Return value Iterator to the first element. ### Complexity Constant. ### Notes Because both `iterator` and `const_iterator` are constant iterators (and may in fact be the same type), it is not possible to mutate the elements of the container through an iterator returned by any of these member functions. ### Example ``` #include <iostream> #include <iterator> #include <string> #include <unordered_set> int main() { const std::unordered_multiset<std::string> words = { "some", "words", "to", "count", "count", "these", "words" }; for (auto it = words.begin(); it != words.end(); ) { auto cnt = words.count(*it); std::cout << *it << ":\t" << cnt << '\n'; std::advance(it, cnt); // all cnt elements have equivalent keys } } ``` Possible output: ``` some: 1 words: 2 to: 1 count: 2 these: 1 ``` ### See also | | | | --- | --- | | [end cend](end "cpp/container/unordered multiset/end") (C++11) | returns an iterator to the end (public member function) | | [begincbegin](../../iterator/begin "cpp/iterator/begin") (C++11)(C++14) | returns an iterator to the beginning of a container or array (function template) | cpp std::unordered_multiset<Key,Hash,KeyEqual,Allocator>::begin(size_type), std::unordered_multiset<Key,Hash,KeyEqual,Allocator>::cbegin(size_type) std::unordered\_multiset<Key,Hash,KeyEqual,Allocator>::begin(size\_type), std::unordered\_multiset<Key,Hash,KeyEqual,Allocator>::cbegin(size\_type) =================================================================================================================================================== | | | | | --- | --- | --- | | ``` local_iterator begin( size_type n ); ``` | | (since C++11) | | ``` const_local_iterator begin( size_type n ) const; ``` | | (since C++11) | | ``` const_local_iterator cbegin( size_type n ) const; ``` | | (since C++11) | Returns an iterator to the first element of the bucket with index `n`. ### Parameters | | | | | --- | --- | --- | | n | - | the index of the bucket to access | ### Return value Iterator to the first element. ### Complexity Constant. ### See also | | | | --- | --- | | [end(size\_type) cend(size\_type)](end2 "cpp/container/unordered multiset/end2") (C++11) | returns an iterator to the end of the specified bucket (public member function) | cpp std::unordered_multiset<Key,Hash,KeyEqual,Allocator>::end, std::unordered_multiset<Key,Hash,KeyEqual,Allocator>::cend std::unordered\_multiset<Key,Hash,KeyEqual,Allocator>::end, std::unordered\_multiset<Key,Hash,KeyEqual,Allocator>::cend ======================================================================================================================= | | | | | --- | --- | --- | | ``` iterator end() noexcept; ``` | | (since C++11) | | ``` const_iterator end() const noexcept; ``` | | (since C++11) | | ``` const_iterator cend() const noexcept; ``` | | (since C++11) | Returns an iterator to the element following the last element of the `unordered_multiset`. This element acts as a placeholder; attempting to access it results in undefined behavior. ![range-begin-end.svg]() ### Parameters (none). ### Return value Iterator to the element following the last element. ### Complexity Constant. ### Notes Because both `iterator` and `const_iterator` are constant iterators (and may in fact be the same type), it is not possible to mutate the elements of the container through an iterator returned by any of these member functions. ### Example ``` #include <iostream> #include <iterator> #include <string> #include <unordered_set> int main() { const std::unordered_multiset<std::string> words = { "some", "words", "to", "count", "count", "these", "words" }; for (auto it = words.begin(); it != words.end(); ) { auto cnt = words.count(*it); std::cout << *it << ":\t" << cnt << '\n'; std::advance(it, cnt); // all cnt elements have equivalent keys } } ``` Possible output: ``` some: 1 words: 2 to: 1 count: 2 these: 1 ``` ### See also | | | | --- | --- | | [begin cbegin](begin "cpp/container/unordered multiset/begin") (C++11) | returns an iterator to the beginning (public member function) | | [endcend](../../iterator/end "cpp/iterator/end") (C++11)(C++14) | returns an iterator to the end of a container or array (function template) | cpp std::unordered_multiset<Key,Hash,KeyEqual,Allocator>::bucket std::unordered\_multiset<Key,Hash,KeyEqual,Allocator>::bucket ============================================================= | | | | | --- | --- | --- | | ``` size_type bucket( const Key& key ) const; ``` | | (since C++11) | Returns the index of the bucket for key `key`. Elements (if any) with keys equivalent to `key` are always found in this bucket. The returned value is valid only for instances of the container for which `[bucket\_count()](bucket_count "cpp/container/unordered multiset/bucket count")` returns the same value. The behavior is undefined if `[bucket\_count()](bucket_count "cpp/container/unordered multiset/bucket count")` is zero. ### Parameters | | | | | --- | --- | --- | | key | - | the value of the key to examine | ### Return value Bucket index for the key `key`. ### Complexity Constant. ### See also | | | | --- | --- | | [bucket\_size](bucket_size "cpp/container/unordered multiset/bucket size") (C++11) | returns the number of elements in specific bucket (public member function) | cpp std::deque<T,Allocator>::size std::deque<T,Allocator>::size ============================= | | | | | --- | --- | --- | | ``` size_type size() const; ``` | | (until C++11) | | ``` size_type size() const noexcept; ``` | | (since C++11) | Returns the number of elements in the container, i.e. `[std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(begin(), end())`. ### Parameters (none). ### Return value The number of elements in the container. ### Complexity Constant. ### Example The following code uses `size` to display the number of elements in a `[std::deque](../deque "cpp/container/deque")`: ``` #include <deque> #include <iostream> int main() { std::deque<int> nums {1, 3, 5, 7}; std::cout << "nums contains " << nums.size() << " elements.\n"; } ``` Output: ``` nums contains 4 elements. ``` ### See also | | | | --- | --- | | [empty](empty "cpp/container/deque/empty") | checks whether the container is empty (public member function) | | [max\_size](max_size "cpp/container/deque/max size") | returns the maximum possible number of elements (public member function) | | [resize](resize "cpp/container/deque/resize") | changes the number of elements stored (public member function) | | [sizessize](../../iterator/size "cpp/iterator/size") (C++17)(C++20) | returns the size of a container or array (function template) | cpp deduction guides for std::deque deduction guides for `std::deque` ================================= | Defined in header `[<deque>](../../header/deque "cpp/header/deque")` | | | | --- | --- | --- | | ``` template< class InputIt, class Alloc = std::allocator<typename std::iterator_traits<InputIt>::value_type>> deque(InputIt, InputIt, Alloc = Alloc()) -> deque<typename std::iterator_traits<InputIt>::value_type, Alloc>; ``` | | (since C++17) | This [deduction guide](../../language/class_template_argument_deduction "cpp/language/class template argument deduction") is provided for deque to allow deduction from an iterator range. This overload participates in overload resolution only if `InputIt` satisfies [LegacyInputIterator](../../named_req/inputiterator "cpp/named req/InputIterator") and `Alloc` satisfies [Allocator](../../named_req/allocator "cpp/named req/Allocator"). Note: the extent to which the library determines that a type does not satisfy [LegacyInputIterator](../../named_req/inputiterator "cpp/named req/InputIterator") is unspecified, except that as a minimum integral types do not qualify as input iterators. Likewise, the extent to which it determines that a type does not satisfy [Allocator](../../named_req/allocator "cpp/named req/Allocator") is unspecified, except that as a minimum the member type `Alloc::value_type` must exist and the expression `[std::declval](http://en.cppreference.com/w/cpp/utility/declval)<Alloc&>().allocate([std::size\_t](http://en.cppreference.com/w/cpp/types/size_t){})` must be well-formed when treated as an unevaluated operand. ### Example ``` #include <deque> #include <vector> int main() { std::vector<int> v = {1, 2, 3, 4}; // uses explicit deduction guide to deduce std::deque<int> std::deque x(v.begin(), v.end()); // deduces std::deque<std::vector<int>::iterator> // first phase of overload resolution for list-initialization selects the candidate // synthesized from the initializer-list constructor; second phase is not performed and // deduction guide has no effect std::deque y{v.begin(), v.end()}; } ```
programming_docs
cpp std::deque<T,Allocator>::emplace std::deque<T,Allocator>::emplace ================================ | | | | | --- | --- | --- | | ``` template< class... Args > iterator emplace( const_iterator pos, Args&&... args ); ``` | | (since C++11) | Inserts a new element into the container directly before `pos`. The element is constructed through `[std::allocator\_traits::construct](../../memory/allocator_traits/construct "cpp/memory/allocator traits/construct")`, which typically uses placement-new to construct the element in-place at a location provided by the container. However, if the required location has been occupied by an existing element, the inserted element is constructed at another location at first, and then move assigned into the required location. The arguments `args...` are forwarded to the constructor as `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Args>(args)...`. `args...` may directly or indirectly refer to a value in the container. All iterators, including the past-the-end iterator, are invalidated. References are invalidated too, unless `pos == begin()` or `pos == end()`, in which case they are not invalidated. ### Parameters | | | | | --- | --- | --- | | pos | - | iterator before which the new element will be constructed | | args | - | arguments to forward to the constructor of the element | | Type requirements | | -`T (the container's element type)` must meet the requirements of [MoveAssignable](../../named_req/moveassignable "cpp/named req/MoveAssignable"), [MoveInsertable](../../named_req/moveinsertable "cpp/named req/MoveInsertable") and [EmplaceConstructible](../../named_req/emplaceconstructible "cpp/named req/EmplaceConstructible"). | ### Return value Iterator pointing to the emplaced element. ### Complexity Linear in the lesser of the distances between `pos` and either of the ends of the container. ### Exceptions If an exception is thrown other than by the copy constructor, move constructor, assignment operator, or move assignment operator of the value type, or if an exception is thrown while `emplace` is used to insert a single element at the either end, there are no effects (strong exception guarantee). Otherwise, the effects are unspecified. ### Example ``` #include <iostream> #include <string> #include <deque> struct A { std::string s; A(std::string str) : s(std::move(str)) { std::cout << " constructed\n"; } A(const A& o) : s(o.s) { std::cout << " copy constructed\n"; } A(A&& o) : s(std::move(o.s)) { std::cout << " move constructed\n"; } A& operator=(const A& other) { s = other.s; std::cout << " copy assigned\n"; return *this; } A& operator=(A&& other) { s = std::move(other.s); std::cout << " move assigned\n"; return *this; } }; int main() { std::deque<A> container; std::cout << "construct 2 times A:\n"; A two { "two" }; A three { "three" }; std::cout << "emplace:\n"; container.emplace(container.end(), "one"); std::cout << "emplace with A&:\n"; container.emplace(container.end(), two); std::cout << "emplace with A&&:\n"; container.emplace(container.end(), std::move(three)); std::cout << "content:\n"; for (const auto& obj : container) std::cout << ' ' << obj.s; std::cout << '\n'; } ``` Output: ``` construct 2 times A: constructed constructed emplace: constructed emplace with A&: copy constructed emplace with A&&: move constructed content: one two three ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 2164](https://cplusplus.github.io/LWG/issue2164) | C++11 | it was not clear whether the arguments can refer to the container | clarified | ### See also | | | | --- | --- | | [insert](insert "cpp/container/deque/insert") | inserts elements (public member function) | | [emplace\_back](emplace_back "cpp/container/deque/emplace back") (C++11) | constructs an element in-place at the end (public member function) | cpp std::deque<T,Allocator>::insert std::deque<T,Allocator>::insert =============================== | | | | | --- | --- | --- | | | (1) | | | ``` iterator insert( iterator pos, const T& value ); ``` | (until C++11) | | ``` iterator insert( const_iterator pos, const T& value ); ``` | (since C++11) | | ``` iterator insert( const_iterator pos, T&& value ); ``` | (2) | (since C++11) | | | (3) | | | ``` void insert( iterator pos, size_type count, const T& value ); ``` | (until C++11) | | ``` iterator insert( const_iterator pos, size_type count, const T& value ); ``` | (since C++11) | | | (4) | | | ``` template< class InputIt > void insert( iterator pos, InputIt first, InputIt last ); ``` | (until C++11) | | ``` template< class InputIt > iterator insert( const_iterator pos, InputIt first, InputIt last ); ``` | (since C++11) | | ``` iterator insert( const_iterator pos, std::initializer_list<T> ilist ); ``` | (5) | (since C++11) | Inserts elements at the specified location in the container. 1-2) inserts `value` before `pos` 3) inserts `count` copies of the `value` before `pos` 4) inserts elements from range `[first, last)` before `pos`. | | | | --- | --- | | This overload has the same effect as overload (3) if `InputIt` is an integral type. | (until C++11) | | This overload participates in overload resolution only if `InputIt` qualifies as [LegacyInputIterator](../../named_req/inputiterator "cpp/named req/InputIterator"), to avoid ambiguity with the overload (3). | (since C++11) | The behavior is undefined if `first` and `last` are iterators into `*this`. 5) inserts elements from initializer list `ilist` before `pos`. All iterators, including the past-the-end iterator, are invalidated. References are invalidated too, unless `pos == begin()` or `pos == end()`, in which case they are not invalidated. ### Parameters | | | | | --- | --- | --- | | pos | - | iterator before which the content will be inserted. `pos` may be the `[end()](end "cpp/container/deque/end")` iterator | | value | - | element value to insert | | count | - | number of elements to insert | | first, last | - | the range of elements to insert, can't be iterators into container for which insert is called | | ilist | - | initializer list to insert the values from | | Type requirements | | -`T` must meet the requirements of [CopyAssignable](../../named_req/copyassignable "cpp/named req/CopyAssignable") and [CopyInsertable](../../named_req/copyinsertable "cpp/named req/CopyInsertable") in order to use overload (1). | | -`T` must meet the requirements of [MoveAssignable](../../named_req/moveassignable "cpp/named req/MoveAssignable") and [MoveInsertable](../../named_req/moveinsertable "cpp/named req/MoveInsertable") in order to use overload (2). | | -`T` must meet the requirements of [CopyAssignable](../../named_req/copyassignable "cpp/named req/CopyAssignable") and [CopyInsertable](../../named_req/copyinsertable "cpp/named req/CopyInsertable") in order to use overload (3). | | -`T` must meet the requirements of [EmplaceConstructible](../../named_req/emplaceconstructible "cpp/named req/EmplaceConstructible") in order to use overload (4,5). | | -`T` must meet the requirements of [Swappable](../../named_req/swappable "cpp/named req/Swappable"), [MoveAssignable](../../named_req/moveassignable "cpp/named req/MoveAssignable"), [MoveConstructible](../../named_req/moveconstructible "cpp/named req/MoveConstructible") and [MoveInsertable](../../named_req/moveinsertable "cpp/named req/MoveInsertable") in order to use overload (4,5). (since C++17) | ### Return value 1-2) Iterator pointing to the inserted `value` 3) Iterator pointing to the first element inserted, or `pos` if `count==0`. 4) Iterator pointing to the first element inserted, or `pos` if `first==last`. 5) Iterator pointing to the first element inserted, or `pos` if `ilist` is empty. ### Complexity 1-2) Constant plus linear in the lesser of the distances between `pos` and either of the ends of the container. 3) Linear in `count` plus linear in the lesser of the distances between `pos` and either of the ends of the container. 4) Linear in `[std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(first, last)` plus linear in the lesser of the distances between `pos` and either of the ends of the container. 5) Linear in `ilist.size()` plus linear in the lesser of the distances between `pos` and either of the ends of the container. ### Exceptions If an exception is thrown when inserting a single element at either end, this function has no effect (strong exception guarantee). ### Example ``` #include <iostream> #include <iterator> #include <deque> void print(int id, const std::deque<int>& container) { std::cout << id << ". "; for (const int x: container) { std::cout << x << ' '; } std::cout << '\n'; } int main () { std::deque<int> c1(3, 100); print(1, c1); auto it = c1.begin(); it = c1.insert(it, 200); print(2, c1); c1.insert(it, 2, 300); print(3, c1); // reset `it` to the begin: it = c1.begin(); std::deque<int> c2(2, 400); c1.insert(std::next(it, 2), c2.begin(), c2.end()); print(4, c1); int arr[] = { 501,502,503 }; c1.insert(c1.begin(), arr, arr + std::size(arr)); print(5, c1); c1.insert(c1.end(), { 601,602,603 } ); print(6, c1); } ``` Output: ``` 1. 100 100 100 2. 200 100 100 100 3. 300 300 200 100 100 100 4. 300 300 400 400 200 100 100 100 5. 501 502 503 300 300 400 400 200 100 100 100 6. 501 502 503 300 300 400 400 200 100 100 100 601 602 603 ``` ### See also | | | | --- | --- | | [emplace](emplace "cpp/container/deque/emplace") (C++11) | constructs element in-place (public member function) | | [push\_front](push_front "cpp/container/deque/push front") | inserts an element to the beginning (public member function) | | [push\_back](push_back "cpp/container/deque/push back") | adds an element to the end (public member function) | | [inserter](../../iterator/inserter "cpp/iterator/inserter") | creates a `[std::insert\_iterator](../../iterator/insert_iterator "cpp/iterator/insert iterator")` of type inferred from the argument (function template) | cpp std::deque<T,Allocator>::get_allocator std::deque<T,Allocator>::get\_allocator ======================================= | | | | | --- | --- | --- | | ``` allocator_type get_allocator() const; ``` | | (until C++11) | | ``` allocator_type get_allocator() const noexcept; ``` | | (since C++11) | Returns the allocator associated with the container. ### Parameters (none). ### Return value The associated allocator. ### Complexity Constant. cpp std::deque<T,Allocator>::shrink_to_fit std::deque<T,Allocator>::shrink\_to\_fit ======================================== | | | | | --- | --- | --- | | ``` void shrink_to_fit(); ``` | | (since C++11) | Requests the removal of unused capacity. It is a non-binding request to reduce the memory usage without changing the size of the sequence. It depends on the implementation whether the request is fulfilled. All iterators and references are invalidated. Past-the-end iterator is also invalidated. ### Parameters (none). | | | --- | | Type requirements | | -`T` must meet the requirements of [MoveInsertable](../../named_req/moveinsertable "cpp/named req/MoveInsertable"). | ### Return value (none). ### Complexity At most linear in the size of the container. ### Notes If an exception is thrown other than by T's move constructor, there are no effects. ### Example ``` #include <iostream> #include <new> #include <deque> // minimal C++11 allocator with debug output template <class Tp> struct NAlloc { typedef Tp value_type; NAlloc() = default; template <class T> NAlloc(const NAlloc<T>&) {} Tp* allocate(std::size_t n) { n *= sizeof(Tp); std::cout << "allocating " << n << " bytes\n"; return static_cast<Tp*>(::operator new(n)); } void deallocate(Tp* p, std::size_t n) { std::cout << "deallocating " << n*sizeof*p << " bytes\n"; ::operator delete(p); } }; template <class T, class U> bool operator==(const NAlloc<T>&, const NAlloc<U>&) { return true; } template <class T, class U> bool operator!=(const NAlloc<T>&, const NAlloc<U>&) { return false; } int main() { /* std::queue has no capacity() function (like std::vector), * because of this we use a custom allocator to show * the working of shrink_to_fit. */ std::cout << "Default-construct deque:\n"; std::deque<int, NAlloc<int>> deq; std::cout << "\nAdd 300 elements:\n"; for (int i = 1000; i < 1300; ++i) deq.push_back(i); std::cout << "\nPop 100 elements:\n"; for (int i = 0; i < 100; ++i) deq.pop_front(); std::cout << "\nRun shrink_to_fit:\n"; deq.shrink_to_fit(); std::cout << "\nDestroy deque as it goes out of scope:\n"; } ``` Possible output: ``` Default-construct deque: allocating 64 bytes allocating 512 bytes Add 300 elements: allocating 512 bytes allocating 512 bytes Pop 100 elements: Run shrink_to_fit: allocating 64 bytes allocating 512 bytes allocating 512 bytes deallocating 512 bytes deallocating 512 bytes deallocating 512 bytes deallocating 64 bytes Destroy deque as it goes out of scope: deallocating 512 bytes deallocating 512 bytes deallocating 64 bytes ``` ### See also | | | | --- | --- | | [size](size "cpp/container/deque/size") | returns the number of elements (public member function) | cpp std::deque<T,Allocator>::~deque std::deque<T,Allocator>::~deque =============================== | | | | | --- | --- | --- | | ``` ~deque(); ``` | | | Destructs the `deque`. The destructors of the elements are called and the used storage is deallocated. Note, that if the elements are pointers, the pointed-to objects are not destroyed. ### Complexity Linear in the size of the `deque`. cpp std::deque<T,Allocator>::rbegin, std::deque<T,Allocator>::crbegin std::deque<T,Allocator>::rbegin, std::deque<T,Allocator>::crbegin ================================================================= | | | | | --- | --- | --- | | ``` reverse_iterator rbegin(); ``` | | (until C++11) | | ``` reverse_iterator rbegin() noexcept; ``` | | (since C++11) | | ``` const_reverse_iterator rbegin() const; ``` | | (until C++11) | | ``` const_reverse_iterator rbegin() const noexcept; ``` | | (since C++11) | | ``` const_reverse_iterator crbegin() const noexcept; ``` | | (since C++11) | Returns a reverse iterator to the first element of the reversed `deque`. It corresponds to the last element of the non-reversed `deque`. If the `deque` is empty, the returned iterator is equal to `[rend()](rend "cpp/container/deque/rend")`. ![range-rbegin-rend.svg]() ### Parameters (none). ### Return value Reverse iterator to the first element. ### Complexity Constant. ### Example ``` #include <algorithm> #include <iostream> #include <numeric> #include <string> #include <deque> int main() { std::deque<int> nums {1, 2, 4, 8, 16}; std::deque<std::string> fruits {"orange", "apple", "raspberry"}; std::deque<char> empty; // Print deque. std::for_each(nums.rbegin(), nums.rend(), [](const int n) { std::cout << n << ' '; }); std::cout << '\n'; // Sums all integers in the deque nums (if any), printing only the result. std::cout << "Sum of nums: " << std::accumulate(nums.rbegin(), nums.rend(), 0) << '\n'; // Prints the first fruit in the deque fruits, checking if there is any. if (!fruits.empty()) std::cout << "First fruit: " << *fruits.rbegin() << '\n'; if (empty.rbegin() == empty.rend()) std::cout << "deque 'empty' is indeed empty.\n"; } ``` Output: ``` 16 8 4 2 1 Sum of nums: 31 First fruit: raspberry deque 'empty' is indeed empty. ``` ### See also | | | | --- | --- | | [rendcrend](rend "cpp/container/deque/rend") (C++11) | returns a reverse iterator to the end (public member function) | | [rbegincrbegin](../../iterator/rbegin "cpp/iterator/rbegin") (C++14) | returns a reverse iterator to the beginning of a container or array (function template) | cpp std::deque<T,Allocator>::at std::deque<T,Allocator>::at =========================== | | | | | --- | --- | --- | | ``` reference at( size_type pos ); ``` | | | | ``` const_reference at( size_type pos ) const; ``` | | | Returns a reference to the element at specified location `pos`, with bounds checking. If `pos` is not within the range of the container, an exception of type `[std::out\_of\_range](../../error/out_of_range "cpp/error/out of range")` is thrown. ### Parameters | | | | | --- | --- | --- | | pos | - | position of the element to return | ### Return value Reference to the requested element. ### Exceptions `[std::out\_of\_range](../../error/out_of_range "cpp/error/out of range")` if `!(pos < size())`. ### Complexity Constant. ### Example ``` #include <iostream> #include <deque> int main() { std::deque<int> data = { 1, 2, 4, 5, 5, 6 }; // Set element 1 data.at(1) = 88; // Read element 2 std::cout << "Element at index 2 has value " << data.at(2) << '\n'; std::cout << "data size = " << data.size() << '\n'; try { // Set element 6 data.at(6) = 666; } catch (std::out_of_range const& exc) { std::cout << exc.what() << '\n'; } // Print final values std::cout << "data:"; for (int elem : data) std::cout << " " << elem; std::cout << '\n'; } ``` Possible output: ``` Element at index 2 has value 4 data size = 6 deque::_M_range_check: __n (which is 6)>= this->size() (which is 6) data: 1 88 4 5 5 6 ``` ### See also | | | | --- | --- | | [operator[]](operator_at "cpp/container/deque/operator at") | access specified element (public member function) | cpp std::deque<T,Allocator>::push_front std::deque<T,Allocator>::push\_front ==================================== | | | | | --- | --- | --- | | ``` void push_front( const T& value ); ``` | | | | ``` void push_front( T&& value ); ``` | | (since C++11) | Prepends the given element `value` to the beginning of the container. All iterators, including the past-the-end iterator, are invalidated. No references are invalidated. ### Parameters | | | | | --- | --- | --- | | value | - | the value of the element to prepend | ### Return value (none). ### Complexity Constant. ### Exceptions If an exception is thrown, this function has no effect (strong exception guarantee). ### Example ``` #include <deque> #include <iostream> #include <iomanip> #include <string> int main() { std::deque<std::string> letters; letters.push_front("abc"); std::string s{"def"}; letters.push_front(std::move(s)); std::cout << "std::deque `letters` holds: "; for (auto&& e : letters) std::cout << std::quoted(e) << ' '; std::cout << "\nMoved-from string `s` holds: " << std::quoted(s) << '\n'; } ``` Possible output: ``` std::deque `letters` holds: "def" "abc" Moved-from string `s` holds: "" ``` ### See also | | | | --- | --- | | [emplace\_front](emplace_front "cpp/container/deque/emplace front") (C++11) | constructs an element in-place at the beginning (public member function) | | [push\_back](push_back "cpp/container/deque/push back") | adds an element to the end (public member function) | | [pop\_front](pop_front "cpp/container/deque/pop front") | removes the first element (public member function) | | [front\_inserter](../../iterator/front_inserter "cpp/iterator/front inserter") | creates a `[std::front\_insert\_iterator](../../iterator/front_insert_iterator "cpp/iterator/front insert iterator")` of type inferred from the argument (function template) |
programming_docs
cpp std::deque<T,Allocator>::operator[] std::deque<T,Allocator>::operator[] =================================== | | | | | --- | --- | --- | | ``` reference operator[]( size_type pos ); ``` | | | | ``` const_reference operator[]( size_type pos ) const; ``` | | | Returns a reference to the element at specified location `pos`. No bounds checking is performed. ### Parameters | | | | | --- | --- | --- | | pos | - | position of the element to return | ### Return value Reference to the requested element. ### Complexity Constant. ### Notes Unlike `[std::map::operator[]](../map/operator_at "cpp/container/map/operator at")`, this operator never inserts a new element into the container. Accessing a nonexistent element through this operator is undefined behavior. ### Example The following code uses `operator[]` to read from and write to a `[std::deque](http://en.cppreference.com/w/cpp/container/deque)<int>`: ``` #include <deque> #include <iostream> int main() { std::deque<int> numbers {2, 4, 6, 8}; std::cout << "Second element: " << numbers[1] << '\n'; numbers[0] = 5; std::cout << "All numbers:"; for (auto i : numbers) { std::cout << ' ' << i; } std::cout << '\n'; } ``` Output: ``` Second element: 4 All numbers: 5 4 6 8 ``` ### See also | | | | --- | --- | | [at](at "cpp/container/deque/at") | access specified element with bounds checking (public member function) | cpp std::deque<T,Allocator>::swap std::deque<T,Allocator>::swap ============================= | | | | | --- | --- | --- | | ``` void swap( deque& other ); ``` | | (until C++17) | | ``` void swap( deque& other ) noexcept(/* see below */); ``` | | (since C++17) | Exchanges the contents of the container with those of `other`. Does not invoke any move, copy, or swap operations on individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated. | | | | --- | --- | | If `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<allocator_type>::propagate\_on\_container\_swap::value` is true, then the allocators are exchanged using an unqualified call to non-member `swap`. Otherwise, they are not swapped (and if `get_allocator() != other.get_allocator()`, the behavior is undefined). | (since C++11) | ### Parameters | | | | | --- | --- | --- | | other | - | container to exchange the contents with | ### Return value (none). ### Exceptions | | | | --- | --- | | (none). | (until C++17) | | [`noexcept`](../../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept([std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<Allocator>::is\_always\_equal::value)` | (since C++17) | ### Complexity Constant. ### Example ``` #include <iostream> #include <deque> template<class Os, class Co> Os& operator<<(Os& os, const Co& co) { os << "{"; for (auto const& i : co) { os << ' ' << i; } return os << " } "; } int main() { std::deque<int> a1{1, 2, 3}, a2{4, 5}; auto it1 = std::next(a1.begin()); auto it2 = std::next(a2.begin()); int& ref1 = a1.front(); int& ref2 = a2.front(); std::cout << a1 << a2 << *it1 << ' ' << *it2 << ' ' << ref1 << ' ' << ref2 << '\n'; a1.swap(a2); std::cout << a1 << a2 << *it1 << ' ' << *it2 << ' ' << ref1 << ' ' << ref2 << '\n'; // Note that after swap the iterators and references stay associated with their // original elements, e.g. it1 that pointed to an element in 'a1' with value 2 // still points to the same element, though this element was moved into 'a2'. } ``` Output: ``` { 1 2 3 } { 4 5 } 2 5 1 4 { 4 5 } { 1 2 3 } 2 5 1 4 ``` ### See also | | | | --- | --- | | [std::swap(std::deque)](swap2 "cpp/container/deque/swap2") | specializes the `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | cpp std::deque<T,Allocator>::max_size std::deque<T,Allocator>::max\_size ================================== | | | | | --- | --- | --- | | ``` size_type max_size() const; ``` | | (until C++11) | | ``` size_type max_size() const noexcept; ``` | | (since C++11) | Returns the maximum number of elements the container is able to hold due to system or library implementation limitations, i.e. `[std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(begin(), end())` for the largest container. ### Parameters (none). ### Return value Maximum number of elements. ### Complexity Constant. ### Notes This value typically reflects the theoretical limit on the size of the container, at most `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<difference_type>::max()`. At runtime, the size of the container may be limited to a value smaller than `max_size()` by the amount of RAM available. ### Example ``` #include <iostream> #include <locale> #include <deque> int main() { std::deque<char> q; std::cout.imbue(std::locale("en_US.UTF-8")); std::cout << "Maximum size of a std::deque is " << q.max_size() << '\n'; } ``` Possible output: ``` Maximum size of a std::deque is 9,223,372,036,854,775,807 ``` ### See also | | | | --- | --- | | [size](size "cpp/container/deque/size") | returns the number of elements (public member function) | cpp std::deque<T,Allocator>::back std::deque<T,Allocator>::back ============================= | | | | | --- | --- | --- | | ``` reference back(); ``` | | | | ``` const_reference back() const; ``` | | | Returns a reference to the last element in the container. Calling `back` on an empty container causes [undefined behavior](../../language/ub "cpp/language/ub"). ### Parameters (none). ### Return value Reference to the last element. ### Complexity Constant. ### Notes For a non-empty container `c`, the expression `c.back()` is equivalent to `\*[std::prev](http://en.cppreference.com/w/cpp/iterator/prev)(c.end())`. ### Example The following code uses `back` to display the last element of a `[std::deque](http://en.cppreference.com/w/cpp/container/deque)<char>`: ``` #include <deque> #include <iostream> int main() { std::deque<char> letters {'a', 'b', 'c', 'd', 'e', 'f'}; if (!letters.empty()) { std::cout << "The last character is '" << letters.back() << "'.\n"; } } ``` Output: ``` The last character is 'f'. ``` ### See also | | | | --- | --- | | [front](front "cpp/container/deque/front") | access the first element (public member function) | cpp std::deque<T,Allocator>::assign std::deque<T,Allocator>::assign =============================== | | | | | --- | --- | --- | | ``` void assign( size_type count, const T& value ); ``` | (1) | | | ``` template< class InputIt > void assign( InputIt first, InputIt last ); ``` | (2) | | | ``` void assign( std::initializer_list<T> ilist ); ``` | (3) | (since C++11) | Replaces the contents of the container. 1) Replaces the contents with `count` copies of value `value` 2) Replaces the contents with copies of those in the range `[first, last)`. The behavior is undefined if either argument is an iterator into `*this`. | | | | --- | --- | | This overload has the same effect as overload (1) if `InputIt` is an integral type. | (until C++11) | | This overload participates in overload resolution only if `InputIt` satisfies [LegacyInputIterator](../../named_req/inputiterator "cpp/named req/InputIterator"). | (since C++11) | 3) Replaces the contents with the elements from the initializer list `ilist`. All iterators, pointers and references to the elements of the container are invalidated. The past-the-end iterator is also invalidated. ### Parameters | | | | | --- | --- | --- | | count | - | the new size of the container | | value | - | the value to initialize elements of the container with | | first, last | - | the range to copy the elements from | | ilist | - | initializer list to copy the values from | ### Complexity 1) Linear in `count` 2) Linear in distance between `first` and `last` 3) Linear in `ilist.size()` ### Example The following code uses `assign` to add several characters to a `[std::deque](http://en.cppreference.com/w/cpp/container/deque)<char>`: ``` #include <deque> #include <iostream> #include <string> int main() { std::deque<char> characters; auto print_deque = [&](){ for (char c : characters) std::cout << c << ' '; std::cout << '\n'; }; characters.assign(5, 'a'); print_deque(); const std::string extra(6, 'b'); characters.assign(extra.begin(), extra.end()); print_deque(); characters.assign({'C', '+', '+', '1', '1'}); print_deque(); } ``` Output: ``` a a a a a b b b b b b C + + 1 1 ``` ### See also | | | | --- | --- | | [(constructor)](deque "cpp/container/deque/deque") | constructs the `deque` (public member function) | cpp std::deque<T,Allocator>::pop_front std::deque<T,Allocator>::pop\_front =================================== | | | | | --- | --- | --- | | ``` void pop_front(); ``` | | | Removes the first element of the container. If there are no elements in the container, the behavior is undefined. | | | | --- | --- | | Iterators and references to the erased element are invalidated. It is unspecified whether the past-the-end iterator is invalidated if the element is the last element in the container. Other references and iterators are not affected. | (until C++11) | | Iterators and references to the erased element are invalidated. If the element is the last element in the container, the past-the-end iterator is also invalidated. Other references and iterators are not affected. | (since C++11) | ### Parameters (none). ### Return value (none). ### Complexity Constant. ### Exceptions Does not throw. ### Example ``` #include <deque> #include <iostream> int main() { std::deque<char> chars{'A', 'B', 'C', 'D'}; for (; !chars.empty(); chars.pop_front()) { std::cout << "chars.front(): '" << chars.front() << "'\n"; } } ``` Output: ``` chars.front(): 'A' chars.front(): 'B' chars.front(): 'C' chars.front(): 'D' ``` ### See also | | | | --- | --- | | [pop\_back](pop_back "cpp/container/deque/pop back") | removes the last element (public member function) | | [push\_front](push_front "cpp/container/deque/push front") | inserts an element to the beginning (public member function) | | [front](front "cpp/container/deque/front") | access the first element (public member function) | cpp std::deque<T,Allocator>::resize std::deque<T,Allocator>::resize =============================== | | | | | --- | --- | --- | | ``` void resize( size_type count ); ``` | (1) | (since C++11) | | | (2) | | | ``` void resize( size_type count, T value = T() ); ``` | (until C++11) | | ``` void resize( size_type count, const value_type& value ); ``` | (since C++11) | Resizes the container to contain `count` elements. If the current size is greater than `count`, the container is reduced to its first `count` elements. If the current size is less than `count`, 1) additional [default-inserted](../../named_req/defaultinsertable "cpp/named req/DefaultInsertable") elements are appended 2) additional copies of `value` are appended. ### Parameters | | | | | --- | --- | --- | | count | - | new size of the container | | value | - | the value to initialize the new elements with | | Type requirements | | -`T` must meet the requirements of [MoveInsertable](../../named_req/moveinsertable "cpp/named req/MoveInsertable") and [DefaultInsertable](../../named_req/defaultinsertable "cpp/named req/DefaultInsertable") in order to use overload (1). | | -`T` must meet the requirements of [CopyInsertable](../../named_req/copyinsertable "cpp/named req/CopyInsertable") in order to use overload (2). | ### Return value (none). ### Complexity Linear in the difference between the current size and `count`. ### Notes If value-initialization in overload (1) is undesirable, for example, if the elements are of non-class type and zeroing out is not needed, it can be avoided by providing a [custom `Allocator::construct`](http://stackoverflow.com/a/21028912/273767). ### Example ``` #include <iostream> #include <deque> int main() { std::deque<int> c = {1, 2, 3}; std::cout << "The deque holds: "; for(const auto& el: c) std::cout << el << ' '; std::cout << '\n'; c.resize(5); std::cout << "After resize up to 5: "; for(const auto& el: c) std::cout << el << ' '; std::cout << '\n'; c.resize(2); std::cout << "After resize down to 2: "; for(const auto& el: c) std::cout << el << ' '; std::cout << '\n'; c.resize(6, 4); std::cout << "After resize up to 6 (initializer = 4): "; for(const auto& el: c) std::cout << el << ' '; std::cout << '\n'; } ``` Output: ``` The deque holds: 1 2 3 After resize up to 5: 1 2 3 0 0 After resize down to 2: 1 2 After resize up to 6 (initializer = 4): 1 2 4 4 4 4 ``` ### See also | | | | --- | --- | | [size](size "cpp/container/deque/size") | returns the number of elements (public member function) | | [insert](insert "cpp/container/deque/insert") | inserts elements (public member function) | | [erase](erase "cpp/container/deque/erase") | erases elements (public member function) | cpp std::deque<T,Allocator>::erase std::deque<T,Allocator>::erase ============================== | | | | | --- | --- | --- | | | (1) | | | ``` iterator erase( iterator pos ); ``` | (until C++11) | | ``` iterator erase( const_iterator pos ); ``` | (since C++11) | | | (2) | | | ``` iterator erase( iterator first, iterator last ); ``` | (until C++11) | | ``` iterator erase( const_iterator first, const_iterator last ); ``` | (since C++11) | Erases the specified elements from the container. 1) Removes the element at `pos`. 2) Removes the elements in the range `[first, last)`. All iterators and references are invalidated, unless the erased elements are at the end or the beginning of the container, in which case only the iterators and references to the erased elements are invalidated. | | | | --- | --- | | It is unspecified when the past-the-end iterator is invalidated. | (until C++11) | | The past-the-end iterator is also invalidated unless the erased elements are at the beginning of the container and the last element is not erased. | (since C++11) | The iterator `pos` must be valid and dereferenceable. Thus the `[end()](end "cpp/container/deque/end")` iterator (which is valid, but is not dereferenceable) cannot be used as a value for `pos`. The iterator `first` does not need to be dereferenceable if `first==last`: erasing an empty range is a no-op. ### Parameters | | | | | --- | --- | --- | | pos | - | iterator to the element to remove | | first, last | - | range of elements to remove | | Type requirements | | -`T` must meet the requirements of [MoveAssignable](../../named_req/moveassignable "cpp/named req/MoveAssignable"). | ### Return value Iterator following the last removed element. If `pos` refers to the last element, then the `[end()](end "cpp/container/deque/end")` iterator is returned. If `last==end()` prior to removal, then the updated `[end()](end "cpp/container/deque/end")` iterator is returned. If `[first, last)` is an empty range, then `last` is returned. ### Exceptions Does not throw unless an exception is thrown by the assignment operator of `T`. ### Complexity Linear: the number of calls to the destructor of T is the same as the number of elements erased, the number of calls to the assignment operator of T is no more than the lesser of the number of elements before the erased elements and the number of elements after the erased elements. ### Example ``` #include <deque> #include <iostream> void print_container(const std::deque<int>& c) { for (int i : c) { std::cout << i << " "; } std::cout << '\n'; } int main( ) { std::deque<int> c{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; print_container(c); c.erase(c.begin()); print_container(c); c.erase(c.begin()+2, c.begin()+5); print_container(c); // Erase all even numbers for (std::deque<int>::iterator it = c.begin(); it != c.end(); ) { if (*it % 2 == 0) { it = c.erase(it); } else { ++it; } } print_container(c); } ``` Output: ``` 0 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 1 2 6 7 8 9 1 7 9 ``` ### See also | | | | --- | --- | | [clear](clear "cpp/container/deque/clear") | clears the contents (public member function) | cpp std::swap(std::deque) std::swap(std::deque) ===================== | Defined in header `[<deque>](../../header/deque "cpp/header/deque")` | | | | --- | --- | --- | | ``` template< class T, class Alloc > void swap( std::deque<T,Alloc>& lhs, std::deque<T,Alloc>& rhs ); ``` | | (until C++17) | | ``` template< class T, class Alloc > void swap( std::deque<T,Alloc>& lhs, std::deque<T,Alloc>& rhs ) noexcept(/* see below */); ``` | | (since C++17) | Specializes the `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` algorithm for `[std::deque](http://en.cppreference.com/w/cpp/container/deque)`. Swaps the contents of `lhs` and `rhs`. Calls `lhs.swap(rhs)`. ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | containers whose contents to swap | ### Return value (none). ### Complexity Constant. ### Exceptions | | | | --- | --- | | [`noexcept`](../../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept(noexcept(lhs.swap(rhs)))` | (since C++17) | ### Notes Although the overloads of `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` for container adaptors are introduced in C++11, container adaptors can already be swapped by `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` in C++98. Such calls to `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` usually have linear time complexity, but better complexity may be provided. ### Example ``` #include <algorithm> #include <iostream> #include <deque> int main() { std::deque<int> alice{1, 2, 3}; std::deque<int> bob{7, 8, 9, 10}; auto print = [](const int& n) { std::cout << ' ' << n; }; // Print state before swap std::cout << "alice:"; std::for_each(alice.begin(), alice.end(), print); std::cout << "\n" "bob :"; std::for_each(bob.begin(), bob.end(), print); std::cout << '\n'; std::cout << "-- SWAP\n"; std::swap(alice, bob); // Print state after swap std::cout << "alice:"; std::for_each(alice.begin(), alice.end(), print); std::cout << "\n" "bob :"; std::for_each(bob.begin(), bob.end(), print); std::cout << '\n'; } ``` Output: ``` alice: 1 2 3 bob : 7 8 9 10 -- SWAP alice: 7 8 9 10 bob : 1 2 3 ``` ### See also | | | | --- | --- | | [swap](swap "cpp/container/deque/swap") | swaps the contents (public member function) | cpp std::deque<T,Allocator>::front std::deque<T,Allocator>::front ============================== | | | | | --- | --- | --- | | ``` reference front(); ``` | | | | ``` const_reference front() const; ``` | | | Returns a reference to the first element in the container. Calling `front` on an empty container is undefined. ### Parameters (none). ### Return value reference to the first element. ### Complexity Constant. ### Notes For a container `c`, the expression `c.front()` is equivalent to `*c.begin()`. ### Example The following code uses `front` to display the first element of a `[std::deque](http://en.cppreference.com/w/cpp/container/deque)<char>`: ``` #include <deque> #include <iostream> int main() { std::deque<char> letters {'o', 'm', 'g', 'w', 't', 'f'}; if (!letters.empty()) { std::cout << "The first character is '" << letters.front() << "'.\n"; } } ``` Output: ``` The first character is 'o'. ``` ### See also | | | | --- | --- | | [back](back "cpp/container/deque/back") | access the last element (public member function) |
programming_docs
cpp std::deque<T,Allocator>::operator= std::deque<T,Allocator>::operator= ================================== | | | | | --- | --- | --- | | ``` deque& operator=( const deque& other ); ``` | (1) | | | | (2) | | | ``` deque& operator=( deque&& other ); ``` | (since C++11) (until C++17) | | ``` deque& operator=( deque&& other ) noexcept(/* see below */); ``` | (since C++17) | | ``` deque& operator=( std::initializer_list<T> ilist ); ``` | (3) | (since C++11) | Replaces the contents of the container. 1) Copy assignment operator. Replaces the contents with a copy of the contents of `other`. | | | | --- | --- | | If `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<allocator_type>::propagate\_on\_container\_copy\_assignment::value` is `true`, the allocator of `*this` is replaced by a copy of that of `other`. If the allocator of `*this` after assignment would compare unequal to its old value, the old allocator is used to deallocate the memory, then the new allocator is used to allocate it before copying the elements. Otherwise, the memory owned by `*this` may be reused when possible. In any case, the elements originally belonging to `*this` may be either destroyed or replaced by element-wise copy-assignment. | (since C++11) | 2) Move assignment operator. Replaces the contents with those of `other` using move semantics (i.e. the data in `other` is moved from `other` into this container). `other` is in a valid but unspecified state afterwards. If `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<allocator_type>::propagate\_on\_container\_move\_assignment::value` is `true`, the allocator of `*this` is replaced by a copy of that of `other`. If it is `false` and the allocators of `*this` and `other` do not compare equal, `*this` cannot take ownership of the memory owned by `other` and must move-assign each element individually, allocating additional memory using its own allocator as needed. In any case, all elements originally belonging to `*this` are either destroyed or replaced by element-wise move-assignment. 3) Replaces the contents with those identified by initializer list `ilist`. ### Parameters | | | | | --- | --- | --- | | other | - | another container to use as data source | | ilist | - | initializer list to use as data source | ### Return value `*this`. ### Complexity 1) Linear in the size of `*this` and `other`. 2) Linear in the size of `*this` unless the allocators do not compare equal and do not propagate, in which case linear in the size of `*this` and `other`. 3) Linear in the size of `*this` and `ilist`. ### Exceptions | | | | --- | --- | | May throw implementation-defined exceptions. | (until C++17) | | 1,3) May throw implementation-defined exceptions. 2) [`noexcept`](../../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept([std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<Allocator>::is\_always\_equal::value)` | (since C++17) | ### Notes After container move assignment (overload (2)), unless element-wise move assignment is forced by incompatible allocators, references, pointers, and iterators (other than the end iterator) to `other` remain valid, but refer to elements that are now in `*this`. The current standard makes this guarantee via the blanket statement in [[container.requirements.general]/12](https://eel.is/c++draft/container.requirements.general#12), and a more direct guarantee is under consideration via [LWG 2321](https://cplusplus.github.io/LWG/issue2321). ### Example The following code uses `operator=` to assign one `[std::deque](../deque "cpp/container/deque")` to another: ``` #include <deque> #include <iterator> #include <iostream> void print(auto const comment, auto const& container) { auto size = std::size(container); std::cout << comment << "{ "; for (auto const& element: container) std::cout << element << (--size ? ", " : " "); std::cout << "}\n"; } int main() { std::deque<int> x { 1, 2, 3 }, y, z; const auto w = { 4, 5, 6, 7 }; std::cout << "Initially:\n"; print("x = ", x); print("y = ", y); print("z = ", z); std::cout << "Copy assignment copies data from x to y:\n"; y = x; print("x = ", x); print("y = ", y); std::cout << "Move assignment moves data from x to z, modifying both x and z:\n"; z = std::move(x); print("x = ", x); print("z = ", z); std::cout << "Assignment of initializer_list w to z:\n"; z = w; print("w = ", w); print("z = ", z); } ``` Output: ``` Initially: x = { 1, 2, 3 } y = { } z = { } Copy assignment copies data from x to y: x = { 1, 2, 3 } y = { 1, 2, 3 } Move assignment moves data from x to z, modifying both x and z: x = { } z = { 1, 2, 3 } Assignment of initializer_list w to z: w = { 4, 5, 6, 7 } z = { 4, 5, 6, 7 } ``` ### See also | | | | --- | --- | | [(constructor)](deque "cpp/container/deque/deque") | constructs the `deque` (public member function) | | [assign](assign "cpp/container/deque/assign") | assigns values to the container (public member function) | cpp std::deque<T,Allocator>::rend, std::deque<T,Allocator>::crend std::deque<T,Allocator>::rend, std::deque<T,Allocator>::crend ============================================================= | | | | | --- | --- | --- | | ``` reverse_iterator rend(); ``` | | (until C++11) | | ``` reverse_iterator rend() noexcept; ``` | | (since C++11) | | ``` const_reverse_iterator rend() const; ``` | | (until C++11) | | ``` const_reverse_iterator rend() const noexcept; ``` | | (since C++11) | | ``` const_reverse_iterator crend() const noexcept; ``` | | (since C++11) | Returns a reverse iterator to the element following the last element of the reversed `deque`. It corresponds to the element preceding the first element of the non-reversed `deque`. This element acts as a placeholder, attempting to access it results in undefined behavior. ![range-rbegin-rend.svg]() ### Parameters (none). ### Return value Reverse iterator to the element following the last element. ### Complexity Constant. ### Example ``` #include <algorithm> #include <iostream> #include <numeric> #include <string> #include <deque> int main() { std::deque<int> nums {1, 2, 4, 8, 16}; std::deque<std::string> fruits {"orange", "apple", "raspberry"}; std::deque<char> empty; // Print deque. std::for_each(nums.rbegin(), nums.rend(), [](const int n) { std::cout << n << ' '; }); std::cout << '\n'; // Sums all integers in the deque nums (if any), printing only the result. std::cout << "Sum of nums: " << std::accumulate(nums.rbegin(), nums.rend(), 0) << '\n'; // Prints the first fruit in the deque fruits, checking if there is any. if (!fruits.empty()) std::cout << "First fruit: " << *fruits.rbegin() << '\n'; if (empty.rbegin() == empty.rend()) std::cout << "deque 'empty' is indeed empty.\n"; } ``` Output: ``` 16 8 4 2 1 Sum of nums: 31 First fruit: raspberry deque 'empty' is indeed empty. ``` ### See also | | | | --- | --- | | [rbegincrbegin](rbegin "cpp/container/deque/rbegin") (C++11) | returns a reverse iterator to the beginning (public member function) | | [rendcrend](../../iterator/rend "cpp/iterator/rend") (C++14) | returns a reverse end iterator for a container or array (function template) | cpp std::deque<T,Allocator>::clear std::deque<T,Allocator>::clear ============================== | | | | | --- | --- | --- | | ``` void clear(); ``` | | (until C++11) | | ``` void clear() noexcept; ``` | | (since C++11) | Erases all elements from the container. After this call, `[size()](size "cpp/container/deque/size")` returns zero. Invalidates any references, pointers, or iterators referring to contained elements. Any past-the-end iterators are also invalidated. ### Parameters (none). ### Return value (none). ### Complexity Linear in the size of the container, i.e., the number of elements. ### Example ``` #include <algorithm> #include <iostream> #include <deque> int main() { std::deque<int> container{1, 2, 3}; auto print = [](const int& n) { std::cout << " " << n; }; std::cout << "Before clear:"; std::for_each(container.begin(), container.end(), print); std::cout << "\nSize=" << container.size() << '\n'; std::cout << "Clear\n"; container.clear(); std::cout << "After clear:"; std::for_each(container.begin(), container.end(), print); std::cout << "\nSize=" << container.size() << '\n'; } ``` Output: ``` Before clear: 1 2 3 Size=3 Clear After clear: Size=0 ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 2231](https://cplusplus.github.io/LWG/issue2231) | C++11 | complexity guarantee was mistakenly omitted in C++11 | complexity reaffirmed as linear | ### See also | | | | --- | --- | | [erase](erase "cpp/container/deque/erase") | erases elements (public member function) | cpp std::deque<T,Allocator>::deque std::deque<T,Allocator>::deque ============================== | | | | | --- | --- | --- | | ``` deque(); ``` | (1) | | | ``` explicit deque( const Allocator& alloc ); ``` | (2) | | | | (3) | | | ``` explicit deque( size_type count, const T& value = T(), const Allocator& alloc = Allocator()); ``` | (until C++11) | | ``` deque( size_type count, const T& value, const Allocator& alloc = Allocator()); ``` | (since C++11) | | | (4) | | | ``` explicit deque( size_type count ); ``` | (since C++11) (until C++14) | | ``` explicit deque( size_type count, const Allocator& alloc = Allocator() ); ``` | (since C++14) | | ``` template< class InputIt > deque( InputIt first, InputIt last, const Allocator& alloc = Allocator() ); ``` | (5) | | | ``` deque( const deque& other ); ``` | (6) | | | ``` deque( const deque& other, const Allocator& alloc ); ``` | (7) | (since C++11) | | ``` deque( deque&& other ); ``` | (8) | (since C++11) | | ``` deque( deque&& other, const Allocator& alloc ); ``` | (9) | (since C++11) | | ``` deque( std::initializer_list<T> init, const Allocator& alloc = Allocator() ); ``` | (10) | (since C++11) | Constructs a new container from a variety of data sources, optionally using a user supplied allocator `alloc`. 1) Default constructor. Constructs an empty container with a default-constructed allocator. 2) Constructs an empty container with the given allocator `alloc`. 3) Constructs the container with `count` copies of elements with value `value`. 4) Constructs the container with `count` [default-inserted](../../named_req/defaultinsertable "cpp/named req/DefaultInsertable") instances of `T`. No copies are made. 5) Constructs the container with the contents of the range `[first, last)`. | | | | --- | --- | | This constructor has the same effect as `deque(static_cast<size_type>(first), static_cast<value_type>(last), a)` if `InputIt` is an integral type. | (until C++11) | | This overload participates in overload resolution only if `InputIt` satisfies [LegacyInputIterator](../../named_req/inputiterator "cpp/named req/InputIterator"), to avoid ambiguity with the overload (3). | (since C++11) | 6) Copy constructor. Constructs the container with the copy of the contents of `other`. | | | | --- | --- | | The allocator is obtained as if by calling `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<allocator_type>::select\_on\_container\_copy\_construction( other.get\_allocator())`. | (since C++11) | 7) Constructs the container with the copy of the contents of `other`, using `alloc` as the allocator. | | | | --- | --- | | The template parameter `Allocator` is only deduced from the first argument while used in [class template argument deduction](../../language/class_template_argument_deduction "cpp/language/class template argument deduction"). | (since C++23) | 8) Move constructor. Constructs the container with the contents of `other` using move semantics. Allocator is obtained by move-construction from the allocator belonging to `other`. 9) Allocator-extended move constructor. Using `alloc` as the allocator for the new container, moving the contents from `other`; if `alloc != other.get_allocator()`, this results in an element-wise move. | | | | --- | --- | | The template parameter `Allocator` is only deduced from the first argument while used in [class template argument deduction](../../language/class_template_argument_deduction "cpp/language/class template argument deduction"). | (since C++23) | 10) Constructs the container with the contents of the initializer list `init`. ### Parameters | | | | | --- | --- | --- | | alloc | - | allocator to use for all memory allocations of this container | | count | - | the size of the container | | value | - | the value to initialize elements of the container with | | first, last | - | the range to copy the elements from | | other | - | another container to be used as source to initialize the elements of the container with | | init | - | initializer list to initialize the elements of the container with | ### Complexity 1-2) Constant 3-4) Linear in `count` 5) Linear in distance between `first` and `last` 6-7) Linear in size of `other` 8) Constant. 9) Linear if `alloc != other.get_allocator()`, otherwise constant. 10) Linear in size of `init`. ### Exceptions Calls to `Allocator::allocate` may throw. ### Notes After container move construction (overload (8)), references, pointers, and iterators (other than the end iterator) to `other` remain valid, but refer to elements that are now in `*this`. The current standard makes this guarantee via the blanket statement in [[container.requirements.general]/12](https://eel.is/c++draft/container.requirements.general#12), and a more direct guarantee is under consideration via [LWG 2321](https://cplusplus.github.io/LWG/issue2321). ### Example ``` #include <deque> #include <string> #include <iostream> template<typename T> std::ostream& operator<<(std::ostream& s, const std::deque<T>& v) { s.put('['); char comma[3] = {'\0', ' ', '\0'}; for (const auto& e : v) { s << comma << e; comma[0] = ','; } return s << ']'; } int main() { // c++11 initializer list syntax: std::deque<std::string> words1 {"the", "frogurt", "is", "also", "cursed"}; std::cout << "words1: " << words1 << '\n'; // words2 == words1 std::deque<std::string> words2(words1.begin(), words1.end()); std::cout << "words2: " << words2 << '\n'; // words3 == words1 std::deque<std::string> words3(words1); std::cout << "words3: " << words3 << '\n'; // words4 is {"Mo", "Mo", "Mo", "Mo", "Mo"} std::deque<std::string> words4(5, "Mo"); std::cout << "words4: " << words4 << '\n'; } ``` Output: ``` words1: [the, frogurt, is, also, cursed] words2: [the, frogurt, is, also, cursed] words3: [the, frogurt, is, also, cursed] words4: [Mo, Mo, Mo, Mo, Mo] ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 2193](https://cplusplus.github.io/LWG/issue2193) | C++11 | the default constructor is explicit | made non-explicit | ### See also | | | | --- | --- | | [assign](assign "cpp/container/deque/assign") | assigns values to the container (public member function) | | [operator=](operator= "cpp/container/deque/operator=") | assigns values to the container (public member function) | cpp std::deque<T,Allocator>::emplace_front std::deque<T,Allocator>::emplace\_front ======================================= | | | | | --- | --- | --- | | ``` template< class... Args > void emplace_front( Args&&... args ); ``` | | (since C++11) (until C++17) | | ``` template< class... Args > reference emplace_front( Args&&... args ); ``` | | (since C++17) | Inserts a new element to the beginning of the container. The element is constructed through `[std::allocator\_traits::construct](../../memory/allocator_traits/construct "cpp/memory/allocator traits/construct")`, which typically uses placement-new to construct the element in-place at the location provided by the container. The arguments `args...` are forwarded to the constructor as `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Args>(args)...`. All iterators, including the past-the-end iterator, are invalidated. No references are invalidated. ### Parameters | | | | | --- | --- | --- | | args | - | arguments to forward to the constructor of the element | | Type requirements | | -`T (the container's element type)` must meet the requirements of [EmplaceConstructible](../../named_req/emplaceconstructible "cpp/named req/EmplaceConstructible"). | ### Return value | | | | --- | --- | | (none) | (until C++17) | | A reference to the inserted element. | (since C++17) | ### Complexity Constant. ### Exceptions If an exception is thrown, this function has no effect (strong exception guarantee). ### See also | | | | --- | --- | | [push\_front](push_front "cpp/container/deque/push front") | inserts an element to the beginning (public member function) | cpp std::deque<T,Allocator>::push_back std::deque<T,Allocator>::push\_back =================================== | | | | | --- | --- | --- | | ``` void push_back( const T& value ); ``` | (1) | | | ``` void push_back( T&& value ); ``` | (2) | (since C++11) | Appends the given element `value` to the end of the container. 1) The new element is initialized as a copy of `value`. 2) `value` is moved into the new element. All iterators, including the past-the-end iterator, are invalidated. No references are invalidated. ### Parameters | | | | | --- | --- | --- | | value | - | the value of the element to append | | Type requirements | | -`T` must meet the requirements of [CopyInsertable](../../named_req/copyinsertable "cpp/named req/CopyInsertable") in order to use overload (1). | | -`T` must meet the requirements of [MoveInsertable](../../named_req/moveinsertable "cpp/named req/MoveInsertable") in order to use overload (2). | ### Return value (none). ### Complexity Constant. ### Exceptions If an exception is thrown (which can be due to `Allocator::allocate()` or element copy/move constructor/assignment), this function has no effect ([strong exception guarantee](../../language/exceptions#Exception_safety "cpp/language/exceptions")). ### Example ``` #include <deque> #include <iostream> #include <iomanip> #include <string> int main() { std::deque<std::string> letters; letters.push_back("abc"); std::string s{"def"}; letters.push_back(std::move(s)); std::cout << "std::deque `letters` holds: "; for (auto&& e : letters) std::cout << std::quoted(e) << ' '; std::cout << "\nMoved-from string `s` holds: " << std::quoted(s) << '\n'; } ``` Possible output: ``` std::deque `letters` holds: "abc" "def" Moved-from string `s` holds: "" ``` ### See also | | | | --- | --- | | [emplace\_back](emplace_back "cpp/container/deque/emplace back") (C++11) | constructs an element in-place at the end (public member function) | | [push\_front](push_front "cpp/container/deque/push front") | inserts an element to the beginning (public member function) | | [pop\_back](pop_back "cpp/container/deque/pop back") | removes the last element (public member function) | | [back\_inserter](../../iterator/back_inserter "cpp/iterator/back inserter") | creates a `[std::back\_insert\_iterator](../../iterator/back_insert_iterator "cpp/iterator/back insert iterator")` of type inferred from the argument (function template) |
programming_docs
cpp std::deque<T,Allocator>::empty std::deque<T,Allocator>::empty ============================== | | | | | --- | --- | --- | | ``` bool empty() const; ``` | | (until C++11) | | ``` bool empty() const noexcept; ``` | | (since C++11) (until C++20) | | ``` [[nodiscard]] bool empty() const noexcept; ``` | | (since C++20) | Checks if the container has no elements, i.e. whether `begin() == end()`. ### Parameters (none). ### Return value `true` if the container is empty, `false` otherwise. ### Complexity Constant. ### Example The following code uses `empty` to check if a `[std::deque](http://en.cppreference.com/w/cpp/container/deque)<int>` contains any elements: ``` #include <deque> #include <iostream> int main() { std::deque<int> numbers; std::cout << std::boolalpha; std::cout << "Initially, numbers.empty(): " << numbers.empty() << '\n'; numbers.push_back(42); numbers.push_back(13317); std::cout << "After adding elements, numbers.empty(): " << numbers.empty() << '\n'; } ``` Output: ``` Initially, numbers.empty(): true After adding elements, numbers.empty(): false ``` ### See also | | | | --- | --- | | [size](size "cpp/container/deque/size") | returns the number of elements (public member function) | | [empty](../../iterator/empty "cpp/iterator/empty") (C++17) | checks whether the container is empty (function template) | cpp std::deque<T,Allocator>::begin, std::deque<T,Allocator>::cbegin std::deque<T,Allocator>::begin, std::deque<T,Allocator>::cbegin =============================================================== | | | | | --- | --- | --- | | ``` iterator begin(); ``` | | (until C++11) | | ``` iterator begin() noexcept; ``` | | (since C++11) | | ``` const_iterator begin() const; ``` | | (until C++11) | | ``` const_iterator begin() const noexcept; ``` | | (since C++11) | | ``` const_iterator cbegin() const noexcept; ``` | | (since C++11) | Returns an iterator to the first element of the `deque`. If the `deque` is empty, the returned iterator will be equal to `[end()](end "cpp/container/deque/end")`. ![range-begin-end.svg]() ### Parameters (none). ### Return value Iterator to the first element. ### Complexity Constant. ### Example ``` #include <algorithm> #include <iostream> #include <numeric> #include <string> #include <deque> int main() { std::deque<int> nums {1, 2, 4, 8, 16}; std::deque<std::string> fruits {"orange", "apple", "raspberry"}; std::deque<char> empty; // Print deque. std::for_each(nums.begin(), nums.end(), [](const int n) { std::cout << n << ' '; }); std::cout << '\n'; // Sums all integers in the deque nums (if any), printing only the result. std::cout << "Sum of nums: " << std::accumulate(nums.begin(), nums.end(), 0) << '\n'; // Prints the first fruit in the deque fruits, checking if there is any. if (!fruits.empty()) std::cout << "First fruit: " << *fruits.begin() << '\n'; if (empty.begin() == empty.end()) std::cout << "deque 'empty' is indeed empty.\n"; } ``` Output: ``` 1 2 4 8 16 Sum of nums: 31 First fruit: orange deque 'empty' is indeed empty. ``` ### See also | | | | --- | --- | | [end cend](end "cpp/container/deque/end") (C++11) | returns an iterator to the end (public member function) | | [begincbegin](../../iterator/begin "cpp/iterator/begin") (C++11)(C++14) | returns an iterator to the beginning of a container or array (function template) | cpp std::deque<T,Allocator>::emplace_back std::deque<T,Allocator>::emplace\_back ====================================== | | | | | --- | --- | --- | | ``` template< class... Args > void emplace_back( Args&&... args ); ``` | | (since C++11) (until C++17) | | ``` template< class... Args > reference emplace_back( Args&&... args ); ``` | | (since C++17) | Appends a new element to the end of the container. The element is constructed through `[std::allocator\_traits::construct](../../memory/allocator_traits/construct "cpp/memory/allocator traits/construct")`, which typically uses placement-new to construct the element in-place at the location provided by the container. The arguments `args...` are forwarded to the constructor as `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Args>(args)...`. All iterators, including the past-the-end iterator, are invalidated. No references are invalidated. ### Parameters | | | | | --- | --- | --- | | args | - | arguments to forward to the constructor of the element | | Type requirements | | -`T (the container's element type)` must meet the requirements of [EmplaceConstructible](../../named_req/emplaceconstructible "cpp/named req/EmplaceConstructible"). | ### Return value | | | | --- | --- | | (none). | (until C++17) | | A reference to the inserted element. | (since C++17) | ### Complexity Constant. ### Exceptions If an exception is thrown, this function has no effect (strong exception guarantee). ### Example The following code uses `emplace_back` to append an object of type `President` to a `[std::deque](http://en.cppreference.com/w/cpp/container/deque)`. It demonstrates how `emplace_back` forwards parameters to the `President` constructor and shows how using `emplace_back` avoids the extra copy or move operation required when using `push_back`. ``` #include <deque> #include <string> #include <cassert> #include <iostream> struct President { std::string name; std::string country; int year; President(std::string p_name, std::string p_country, int p_year) : name(std::move(p_name)), country(std::move(p_country)), year(p_year) { std::cout << "I am being constructed.\n"; } President(President&& other) : name(std::move(other.name)), country(std::move(other.country)), year(other.year) { std::cout << "I am being moved.\n"; } President& operator=(const President& other) = default; }; int main() { std::deque<President> elections; std::cout << "emplace_back:\n"; auto& ref = elections.emplace_back("Nelson Mandela", "South Africa", 1994); assert(ref.year == 1994 && "uses a reference to the created object (C++17)"); std::deque<President> reElections; std::cout << "\npush_back:\n"; reElections.push_back(President("Franklin Delano Roosevelt", "the USA", 1936)); std::cout << "\nContents:\n"; for (President const& president: elections) { std::cout << president.name << " was elected president of " << president.country << " in " << president.year << ".\n"; } for (President const& president: reElections) { std::cout << president.name << " was re-elected president of " << president.country << " in " << president.year << ".\n"; } } ``` Output: ``` emplace_back: I am being constructed. push_back: I am being constructed. I am being moved. Contents: Nelson Mandela was elected president of South Africa in 1994. Franklin Delano Roosevelt was re-elected president of the USA in 1936. ``` ### See also | | | | --- | --- | | [push\_back](push_back "cpp/container/deque/push back") | adds an element to the end (public member function) | | [emplace](emplace "cpp/container/deque/emplace") (C++11) | constructs element in-place (public member function) | cpp std::deque<T,Allocator>::end, std::deque<T,Allocator>::cend std::deque<T,Allocator>::end, std::deque<T,Allocator>::cend =========================================================== | | | | | --- | --- | --- | | ``` iterator end(); ``` | | (until C++11) | | ``` iterator end() noexcept; ``` | | (since C++11) | | ``` const_iterator end() const; ``` | | (until C++11) | | ``` const_iterator end() const noexcept; ``` | | (since C++11) | | ``` const_iterator cend() const noexcept; ``` | | (since C++11) | Returns an iterator to the element following the last element of the `deque`. This element acts as a placeholder; attempting to access it results in undefined behavior. ![range-begin-end.svg]() ### Parameters (none). ### Return value Iterator to the element following the last element. ### Complexity Constant. ### Example ``` #include <algorithm> #include <iostream> #include <numeric> #include <string> #include <deque> int main() { std::deque<int> nums {1, 2, 4, 8, 16}; std::deque<std::string> fruits {"orange", "apple", "raspberry"}; std::deque<char> empty; // Print deque. std::for_each(nums.begin(), nums.end(), [](const int n) { std::cout << n << ' '; }); std::cout << '\n'; // Sums all integers in the deque nums (if any), printing only the result. std::cout << "Sum of nums: " << std::accumulate(nums.begin(), nums.end(), 0) << '\n'; // Prints the first fruit in the deque fruits, checking if there is any. if (!fruits.empty()) std::cout << "First fruit: " << *fruits.begin() << '\n'; if (empty.begin() == empty.end()) std::cout << "deque 'empty' is indeed empty.\n"; } ``` Output: ``` 1 2 4 8 16 Sum of nums: 31 First fruit: orange deque 'empty' is indeed empty. ``` ### See also | | | | --- | --- | | [begin cbegin](begin "cpp/container/deque/begin") (C++11) | returns an iterator to the beginning (public member function) | | [endcend](../../iterator/end "cpp/iterator/end") (C++11)(C++14) | returns an iterator to the end of a container or array (function template) | cpp std::deque<T,Allocator>::pop_back std::deque<T,Allocator>::pop\_back ================================== | | | | | --- | --- | --- | | ``` void pop_back(); ``` | | | Removes the last element of the container. Calling `pop_back` on an empty container results in undefined behavior. | | | | --- | --- | | Iterators and references to the erased element are invalidated. It is unspecified whether the past-the-end iterator is invalidated. Other references and iterators are not affected. | (until C++11) | | Iterators and references to the erased element are invalidated. The past-the-end iterator is also invalidated. Other references and iterators are not affected. | (since C++11) | ### Parameters (none). ### Return value (none). ### Complexity Constant. ### Exceptions Throws nothing. ### Example ``` #include <deque> #include <iostream> template<typename T> void print(T const & xs) { std::cout << "[ "; for(auto const & x : xs) { std::cout << x << ' '; } std::cout << "]\n"; } int main() { std::deque<int> numbers; print(numbers); numbers.push_back(5); numbers.push_back(3); numbers.push_back(4); print(numbers); numbers.pop_back(); print(numbers); } ``` Output: ``` [ ] [ 5 3 4 ] [ 5 3 ] ``` ### See also | | | | --- | --- | | [pop\_front](pop_front "cpp/container/deque/pop front") | removes the first element (public member function) | | [push\_back](push_back "cpp/container/deque/push back") | adds an element to the end (public member function) | cpp std::map<Key,T,Compare,Allocator>::contains std::map<Key,T,Compare,Allocator>::contains =========================================== | | | | | --- | --- | --- | | ``` bool contains( const Key& key ) const; ``` | (1) | (since C++20) | | ``` template< class K > bool contains( const K& x ) const; ``` | (2) | (since C++20) | 1) Checks if there is an element with key equivalent to `key` in the container. 2) Checks if there is an element with key that compares *equivalent* to the value `x`. This overload participates in overload resolution only if the qualified-id `Compare::is_transparent` is valid and denotes a type. It allows calling this function without constructing an instance of `Key`. ### Parameters | | | | | --- | --- | --- | | key | - | key value of the element to search for | | x | - | a value of any type that can be transparently compared with a key | ### Return value `true` if there is such an element, otherwise `false`. ### Complexity Logarithmic in the size of the container. ### Example ``` #include <iostream> #include <map> int main() { std::map<int,char> example = {{1,'a'},{2,'b'}}; for(int x: {2, 5}) { if(example.contains(x)) { std::cout << x << ": Found\n"; } else { std::cout << x << ": Not found\n"; } } } ``` Output: ``` 2: Found 5: Not found ``` ### See also | | | | --- | --- | | [find](find "cpp/container/map/find") | finds element with specific key (public member function) | | [count](count "cpp/container/map/count") | returns the number of elements matching specific key (public member function) | | [equal\_range](equal_range "cpp/container/map/equal range") | returns range of elements matching a specific key (public member function) | cpp std::map<Key,T,Compare,Allocator>::size std::map<Key,T,Compare,Allocator>::size ======================================= | | | | | --- | --- | --- | | ``` size_type size() const; ``` | | (until C++11) | | ``` size_type size() const noexcept; ``` | | (since C++11) | Returns the number of elements in the container, i.e. `[std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(begin(), end())`. ### Parameters (none). ### Return value The number of elements in the container. ### Complexity Constant. ### Example The following code uses `size` to display the number of elements in a `[std::map](../map "cpp/container/map")`: ``` #include <map> #include <iostream> int main() { std::map<int,char> nums {{1, 'a'}, {3, 'b'}, {5, 'c'}, {7, 'd'}}; std::cout << "nums contains " << nums.size() << " elements.\n"; } ``` Output: ``` nums contains 4 elements. ``` ### See also | | | | --- | --- | | [empty](empty "cpp/container/map/empty") | checks whether the container is empty (public member function) | | [max\_size](max_size "cpp/container/map/max size") | returns the maximum possible number of elements (public member function) | | [sizessize](../../iterator/size "cpp/iterator/size") (C++17)(C++20) | returns the size of a container or array (function template) | cpp std::map<Key,T,Compare,Allocator>::map std::map<Key,T,Compare,Allocator>::map ====================================== | | | | | --- | --- | --- | | ``` map(); ``` | (1) | | | ``` explicit map( const Compare& comp, const Allocator& alloc = Allocator() ); ``` | (2) | | | ``` explicit map( const Allocator& alloc ); ``` | (3) | (since C++11) | | ``` template< class InputIt > map( InputIt first, InputIt last, const Compare& comp = Compare(), const Allocator& alloc = Allocator() ); ``` | (4) | | | ``` template< class InputIt > map( InputIt first, InputIt last, const Allocator& alloc ); ``` | (5) | (since C++14) | | ``` map( const map& other ); ``` | (6) | | | ``` map( const map& other, const Allocator& alloc ); ``` | (7) | (since C++11) | | ``` map( map&& other ); ``` | (8) | (since C++11) | | ``` map( map&& other, const Allocator& alloc ); ``` | (9) | (since C++11) | | ``` map( std::initializer_list<value_type> init, const Compare& comp = Compare(), const Allocator& alloc = Allocator() ); ``` | (10) | (since C++11) | | ``` map( std::initializer_list<value_type> init, const Allocator& ); ``` | (11) | (since C++14) | Constructs new container from a variety of data sources and optionally using user supplied allocator `alloc` or comparison function object `comp`. 1-3) Constructs an empty container. 4-5) Constructs the container with the contents of the range `[first, last)`. If multiple elements in the range have keys that compare equivalent, it is unspecified which element is inserted (pending [LWG2844](https://cplusplus.github.io/LWG/issue2844)). 6-7) Copy constructor. Constructs the container with the copy of the contents of `other`. | | | | --- | --- | | If `alloc` is not provided, allocator is obtained by calling `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<allocator_type>::select\_on\_container\_copy\_construction( other.get\_allocator())`. | (since C++11) | | The template parameter `Allocator` is only deduced from the first argument while used in [class template argument deduction](../../language/class_template_argument_deduction "cpp/language/class template argument deduction"). | (since C++23) | 8-9) Move constructor. Constructs the container with the contents of `other` using move semantics. If `alloc` is not provided, allocator is obtained by move-construction from the allocator belonging to `other`. | | | | --- | --- | | The template parameter `Allocator` is only deduced from the first argument while used in [class template argument deduction](../../language/class_template_argument_deduction "cpp/language/class template argument deduction"). | (since C++23) | 10-11) Constructs the container with the contents of the initializer list `init`. If multiple elements in the range have keys that compare equivalent, it is unspecified which element is inserted (pending [LWG2844](https://cplusplus.github.io/LWG/issue2844)). ### Parameters | | | | | --- | --- | --- | | alloc | - | allocator to use for all memory allocations of this container | | comp | - | comparison function object to use for all comparisons of keys | | first, last | - | the range to copy the elements from | | other | - | another container to be used as source to initialize the elements of the container with | | init | - | initializer list to initialize the elements of the container with | | Type requirements | | -`InputIt` must meet the requirements of [LegacyInputIterator](../../named_req/inputiterator "cpp/named req/InputIterator"). | | -`Compare` must meet the requirements of [Compare](../../named_req/compare "cpp/named req/Compare"). | | -`Allocator` must meet the requirements of [Allocator](../../named_req/allocator "cpp/named req/Allocator"). | ### Complexity 1-3) Constant 4-5) N log(N) where `N = [std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(first, last)` in general, linear in `N` if the range is already sorted by `value_comp()`. 6-7) Linear in size of `other` 8-9) Constant. If `alloc` is given and `alloc != other.get_allocator()`, then linear. 10-11) N log(N) where `N = init.size()` in general, linear in `N` if `init` is already sorted by `value_comp()`. ### Exceptions Calls to `Allocator::allocate` may throw. ### Notes After container move construction (overload (8-9)), references, pointers, and iterators (other than the end iterator) to `other` remain valid, but refer to elements that are now in `*this`. The current standard makes this guarantee via the blanket statement in [[container.requirements.general]/12](https://eel.is/c++draft/container.requirements.general#12), and a more direct guarantee is under consideration via [LWG 2321](https://cplusplus.github.io/LWG/issue2321). Although not formally required until C++23, some implementations has already put the template parameter `Allocator` into [non-deduced contexts](../../language/template_argument_deduction#Non-deduced_contexts "cpp/language/template argument deduction") in earlier modes. ### Example ``` #include <iomanip> #include <iostream> #include <string> #include <map> template<typename Key, typename Value> std::ostream& operator<<(std::ostream& os, std::map<Key, Value> const& m) { os << "{ "; for(auto const& p: m) os << '(' << p.first << ':' << p.second << ") "; return os << "}\n"; } struct Point { double x, y; }; struct PointCmp { bool operator()(const Point& lhs, const Point& rhs) const { return lhs.x < rhs.x; // NB. intentionally ignores y } }; int main() { // (1) Default constructor std::map<std::string, int> map1; map1["something"] = 69; map1["anything"] = 199; map1["that thing"] = 50; std::cout << "map1 = " << map1; // (4) Range constructor std::map<std::string, int> iter(map1.find("anything"), map1.end()); std::cout << "\niter = " << iter; std::cout << "map1 = " << map1; // (6) Copy constructor std::map<std::string, int> copied(map1); std::cout << "\ncopied = " << copied; std::cout << "map1 = " << map1; // (8) Move constructor std::map<std::string, int> moved{std::move(map1)}; std::cout << "\nmoved = " << moved; std::cout << "map1 = " << map1; // (10) Initializer list constructor const std::map<std::string, int> init { {"this", 100}, {"can", 100}, {"be", 100}, {"const", 100}, }; std::cout << "\ninit = " << init; std::cout << "\nCustom Key class option 1:\n"; // Use a comparison struct std::map<Point, double, PointCmp> mag = { { {5, -12}, 13 }, { {3, 4}, 5 }, { {-8, -15}, 17 } }; for(auto p : mag) std::cout << "The magnitude of (" << p.first.x << ", " << p.first.y << ") is " << p.second << '\n'; std::cout << "\nCustom Key class option 2:\n"; // Use a comparison lambda // This lambda sorts points according to their magnitudes, where note that // these magnitudes are taken from the local variable mag auto cmpLambda = [&mag](const Point &lhs, const Point &rhs) { return mag[lhs] < mag[rhs]; }; // You could also use a lambda that is not dependent on local variables, like this: // auto cmpLambda = [](const Point &lhs, const Point &rhs) { return lhs.y < rhs.y; }; std::map<Point, double, decltype(cmpLambda)> magy(cmpLambda); // Various ways of inserting elements: magy.insert(std::pair<Point, double>({5, -12}, 13)); magy.insert({ {3, 4}, 5}); magy.insert({Point{-8.0, -15.0}, 17}); for(auto p : magy) std::cout << "The magnitude of (" << p.first.x << ", " << p.first.y << ") is " << p.second << '\n'; } ``` Output: ``` map1 = { (anything:199) (something:69) (that thing:50) } iter = { (anything:199) (something:69) (that thing:50) } map1 = { (anything:199) (something:69) (that thing:50) } copied = { (anything:199) (something:69) (that thing:50) } map1 = { (anything:199) (something:69) (that thing:50) } moved = { (anything:199) (something:69) (that thing:50) } map1 = { } init = { (be:100) (can:100) (const:100) (this:100) } Custom Key class option 1: The magnitude of (-8, -15) is 17 The magnitude of (3, 4) is 5 The magnitude of (5, -12) is 13 Custom Key class option 2: The magnitude of (3, 4) is 5 The magnitude of (5, -12) is 13 The magnitude of (-8, -15) is 17 ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 2193](https://cplusplus.github.io/LWG/issue2193) | C++11 | the default constructor is explicit | made non-explicit | ### See also | | | | --- | --- | | [operator=](operator= "cpp/container/map/operator=") | assigns values to the container (public member function) |
programming_docs
cpp deduction guides for std::map deduction guides for `std::map` =============================== | Defined in header `[<map>](../../header/map "cpp/header/map")` | | | | --- | --- | --- | | ``` template< class InputIt, class Comp = std::less<iter_key_t<InputIt>>, class Alloc = std::allocator<iter_to_alloc_t<InputIt>> > map( InputIt, InputIt, Comp = Comp(), Alloc = Alloc() ) -> map<iter_key_t<InputIt>, iter_val_t<InputIt>, Comp, Alloc>; ``` | (1) | (since C++17) | | ``` template< class Key, class T, class Comp = std::less<Key>, class Alloc = std::allocator<std::pair<const Key, T>> > map( std::initializer_list<std::pair<Key, T>>, Comp = Comp(), Alloc = Alloc() ) -> map<Key, T, Comp, Alloc>; ``` | (2) | (since C++17) | | ``` template< class InputIt, class Alloc > map( InputIt, InputIt, Alloc ) -> map<iter_key_t<InputIt>, iter_val_t<InputIt>, std::less<iter_key_t<InputIt>>, Alloc>; ``` | (3) | (since C++17) | | ``` template< class Key, class T, class Allocator > map( std::initializer_list<std::pair<Key, T>>, Allocator ) -> map<Key, T, std::less<Key>, Allocator>; ``` | (4) | (since C++17) | where the type aliases `iter_key_t`, `iter_val_t`, `iter_to_alloc_t` are defined as if as follows. | | | | | --- | --- | --- | | ``` template< class InputIt > using iter_key_t = std::remove_const_t< typename std::iterator_traits<InputIt>::value_type::first_type>; ``` | | (exposition only) | | ``` template< class InputIt > using iter_val_t = typename std::iterator_traits<InputIt>::value_type::second_type; ``` | | (exposition only) | | ``` template< class InputIt > using iter_to_alloc_t = std::pair< std::add_const_t<typename std::iterator_traits<InputIt>::value_type::first_type>, typename std::iterator_traits<InputIt>::value_type::second_type > ``` | | (exposition only) | This [deduction guide](../../language/class_template_argument_deduction "cpp/language/class template argument deduction") is provided for map to allow deduction from an iterator range (overloads (1,3)) and `[std::initializer\_list](../../utility/initializer_list "cpp/utility/initializer list")` (overloads (2,4)). These overloads participate in overload resolution only if `InputIt` satisfies [LegacyInputIterator](../../named_req/inputiterator "cpp/named req/InputIterator"), `Alloc` satisfies [Allocator](../../named_req/allocator "cpp/named req/Allocator"), and `Comp` does not satisfy [Allocator](../../named_req/allocator "cpp/named req/Allocator"). Note: the extent to which the library determines that a type does not satisfy [LegacyInputIterator](../../named_req/inputiterator "cpp/named req/InputIterator") is unspecified, except that as a minimum integral types do not qualify as input iterators. Likewise, the extent to which it determines that a type does not satisfy [Allocator](../../named_req/allocator "cpp/named req/Allocator") is unspecified, except that as a minimum the member type `Alloc::value_type` must exist and the expression `[std::declval](http://en.cppreference.com/w/cpp/utility/declval)<Alloc&>().allocate([std::size\_t](http://en.cppreference.com/w/cpp/types/size_t){})` must be well-formed when treated as an unevaluated operand. ### Example ``` #include <map> int main() { // std::map m1 = {{"foo", 1}, {"bar", 2}}; // Error: braced-init-list has no type; // cannot deduce pair<Key, T> from // {"foo", 1} or {"bar", 2} std::map m1 = {std::pair{"foo", 2}, {"bar", 3}}; // guide #2 std::map m2(m1.begin(), m1.end()); // guide #1 } ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 3025](https://cplusplus.github.io/LWG/issue3025) | C++17 | initializer-list guides take `[std::pair](http://en.cppreference.com/w/cpp/utility/pair)<const Key, T>` | use `[std::pair](http://en.cppreference.com/w/cpp/utility/pair)<Key, T>` | cpp std::map<Key,T,Compare,Allocator>::insert_or_assign std::map<Key,T,Compare,Allocator>::insert\_or\_assign ===================================================== | | | | | --- | --- | --- | | ``` template <class M> std::pair<iterator, bool> insert_or_assign( const Key& k, M&& obj ); ``` | (1) | (since C++17) | | ``` template <class M> std::pair<iterator, bool> insert_or_assign( Key&& k, M&& obj ); ``` | (2) | (since C++17) | | ``` template <class M> iterator insert_or_assign( const_iterator hint, const Key& k, M&& obj ); ``` | (3) | (since C++17) | | ``` template <class M> iterator insert_or_assign( const_iterator hint, Key&& k, M&& obj ); ``` | (4) | (since C++17) | 1,3) If a key equivalent to `k` already exists in the container, assigns `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<M>(obj)` to the `mapped_type` corresponding to the key `k`. If the key does not exist, inserts the new value as if by [`insert`](insert "cpp/container/map/insert"), constructing it from `value_type(k, [std::forward](http://en.cppreference.com/w/cpp/utility/forward)<M>(obj))` 2,4) Same as (1,3), except the mapped value is constructed from `value_type(std::move(k), [std::forward](http://en.cppreference.com/w/cpp/utility/forward)<M>(obj))` The behavior is undefined (until C++20)The program is ill-formed (since C++20) if `[std::is\_assignable\_v](http://en.cppreference.com/w/cpp/types/is_assignable)<mapped_type&, M&&>` is `false`. No iterators or references are invalidated. ### Parameters | | | | | --- | --- | --- | | k | - | the key used both to look up and to insert if not found | | hint | - | iterator to the position before which the new element will be inserted | | obj | - | the value to insert or assign | ### Return value 1,2) The bool component is `true` if the insertion took place and `false` if the assignment took place. The iterator component is pointing at the element that was inserted or updated 3,4) Iterator pointing at the element that was inserted or updated ### Complexity 1,2) Same as for [`emplace`](emplace "cpp/container/map/emplace") 3,4) Same as for [`emplace_hint`](emplace_hint "cpp/container/map/emplace hint") ### Notes `insert_or_assign` returns more information than `operator[]` and does not require default-constructibility of the mapped type. | [Feature-test](../../utility/feature_test "cpp/utility/feature test") macro | | --- | | [`__cpp_lib_map_try_emplace`](../../feature_test#Library_features "cpp/feature test") | ### Example ``` #include <iostream> #include <map> #include <string> auto print_node = [](const auto &node) { std::cout << "[" << node.first << "] = " << node.second << '\n'; }; auto print_result = [](auto const &pair) { std::cout << (pair.second ? "inserted: " : "assigned: "); print_node(*pair.first); }; int main() { std::map<std::string, std::string> myMap; print_result( myMap.insert_or_assign("a", "apple" ) ); print_result( myMap.insert_or_assign("b", "banana" ) ); print_result( myMap.insert_or_assign("c", "cherry" ) ); print_result( myMap.insert_or_assign("c", "clementine") ); for (const auto &node : myMap) { print_node(node); } } ``` Output: ``` inserted: [a] = apple inserted: [b] = banana inserted: [c] = cherry assigned: [c] = clementine [a] = apple [b] = banana [c] = clementine ``` ### See also | | | | --- | --- | | [operator[]](operator_at "cpp/container/map/operator at") | access or insert specified element (public member function) | | [at](at "cpp/container/map/at") | access specified element with bounds checking (public member function) | | [insert](insert "cpp/container/map/insert") | inserts elements or nodes (since C++17) (public member function) | | [emplace](emplace "cpp/container/map/emplace") (C++11) | constructs element in-place (public member function) | cpp std::map<Key,T,Compare,Allocator>::emplace std::map<Key,T,Compare,Allocator>::emplace ========================================== | | | | | --- | --- | --- | | ``` template< class... Args > std::pair<iterator,bool> emplace( Args&&... args ); ``` | | (since C++11) | Inserts a new element into the container constructed in-place with the given `args` if there is no element with the key in the container. Careful use of `emplace` allows the new element to be constructed while avoiding unnecessary copy or move operations. The constructor of the new element (i.e. `[std::pair](http://en.cppreference.com/w/cpp/utility/pair)<const Key, T>`) is called with exactly the same arguments as supplied to `emplace`, forwarded via `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Args>(args)...`. The element may be constructed even if there already is an element with the key in the container, in which case the newly constructed element will be destroyed immediately. No iterators or references are invalidated. ### Parameters | | | | | --- | --- | --- | | args | - | arguments to forward to the constructor of the element | ### Return value Returns a pair consisting of an iterator to the inserted element, or the already-existing element if no insertion happened, and a `bool` denoting whether the insertion took place (`true` if insertion happened, `false` if it did not). ### Exceptions If an exception is thrown by any operation, this function has no effect (strong exception guarantee). ### Complexity Logarithmic in the size of the container. ### Example ``` #include <iostream> #include <utility> #include <string> #include <map> int main() { std::map<std::string, std::string> m; // uses pair's move constructor m.emplace(std::make_pair(std::string("a"), std::string("a"))); // uses pair's converting move constructor m.emplace(std::make_pair("b", "abcd")); // uses pair's template constructor m.emplace("d", "ddd"); // uses pair's piecewise constructor m.emplace(std::piecewise_construct, std::forward_as_tuple("c"), std::forward_as_tuple(10, 'c')); // as of C++17, m.try_emplace("c", 10, 'c'); can be used for (const auto &p : m) { std::cout << p.first << " => " << p.second << '\n'; } } ``` Output: ``` a => a b => abcd c => cccccccccc d => ddd ``` ### See also | | | | --- | --- | | [emplace\_hint](emplace_hint "cpp/container/map/emplace hint") (C++11) | constructs elements in-place using a hint (public member function) | | [try\_emplace](try_emplace "cpp/container/map/try emplace") (C++17) | inserts in-place if the key does not exist, does nothing if the key exists (public member function) | | [insert](insert "cpp/container/map/insert") | inserts elements or nodes (since C++17) (public member function) | cpp std::map<Key,T,Compare,Allocator>::insert std::map<Key,T,Compare,Allocator>::insert ========================================= | | | | | --- | --- | --- | | ``` std::pair<iterator, bool> insert( const value_type& value ); ``` | (1) | | | ``` template< class P > std::pair<iterator, bool> insert( P&& value ); ``` | (2) | (since C++11) | | ``` std::pair<iterator, bool> insert( value_type&& value ); ``` | (3) | (since C++17) | | | (4) | | | ``` iterator insert( iterator hint, const value_type& value ); ``` | (until C++11) | | ``` iterator insert( const_iterator hint, const value_type& value ); ``` | (since C++11) | | ``` template< class P > iterator insert( const_iterator hint, P&& value ); ``` | (5) | (since C++11) | | ``` iterator insert( const_iterator hint, value_type&& value ); ``` | (6) | (since C++17) | | ``` template< class InputIt > void insert( InputIt first, InputIt last ); ``` | (7) | | | ``` void insert( std::initializer_list<value_type> ilist ); ``` | (8) | (since C++11) | | ``` insert_return_type insert( node_type&& nh ); ``` | (9) | (since C++17) | | ``` iterator insert( const_iterator hint, node_type&& nh ); ``` | (10) | (since C++17) | Inserts element(s) into the container, if the container doesn't already contain an element with an equivalent key. 1-3) Inserts `value`. The overload (2) is equivalent to `emplace([std::forward](http://en.cppreference.com/w/cpp/utility/forward)<P>(value))` and only participates in overload resolution if `[std::is\_constructible](http://en.cppreference.com/w/cpp/types/is_constructible)<value_type, P&&>::value == true`. 4-6) Inserts `value` in the position as close as possible, just prior(since C++11), to `hint`. The overload (5) is equivalent to `emplace_hint(hint, [std::forward](http://en.cppreference.com/w/cpp/utility/forward)<P>(value))` and only participates in overload resolution if `[std::is\_constructible](http://en.cppreference.com/w/cpp/types/is_constructible)<value_type, P&&>::value == true`. 7) Inserts elements from range `[first, last)`. If multiple elements in the range have keys that compare equivalent, it is unspecified which element is inserted (pending [LWG2844](https://cplusplus.github.io/LWG/issue2844)). 8) Inserts elements from initializer list `ilist`. If multiple elements in the range have keys that compare equivalent, it is unspecified which element is inserted (pending [LWG2844](https://cplusplus.github.io/LWG/issue2844)). 9) If `nh` is an empty [node handle](../node_handle "cpp/container/node handle"), does nothing. Otherwise, inserts the element owned by `nh` into the container , if the container doesn't already contain an element with a key equivalent to `nh.key()`. The behavior is undefined if `nh` is not empty and `get_allocator() != nh.get_allocator()`. 10) If `nh` is an empty [node handle](../node_handle "cpp/container/node handle"), does nothing and returns the end iterator. Otherwise, inserts the element owned by `nh` into the container, if the container doesn't already contain an element with a key equivalent to `nh.key()`, and returns the iterator pointing to the element with key equivalent to `nh.key()` (regardless of whether the insert succeeded or failed). If the insertion succeeds, `nh` is moved from, otherwise it retains ownership of the element. The element is inserted as close as possible to the position just prior to `hint`. The behavior is undefined if `nh` is not empty and `get_allocator() != nh.get_allocator()`. No iterators or references are invalidated. If the insertion is successful, pointers and references to the element obtained while it is held in the node handle are invalidated, and pointers and references obtained to that element before it was extracted become valid. (since C++17). ### Parameters | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | | hint | - | | | | | --- | --- | | iterator, used as a suggestion as to where to start the search | (until C++11) | | iterator to the position before which the new element will be inserted | (since C++11) | | | value | - | element value to insert | | first, last | - | range of elements to insert | | ilist | - | initializer list to insert the values from | | nh | - | a compatible [node handle](../node_handle "cpp/container/node handle") | | Type requirements | | -`InputIt` must meet the requirements of [LegacyInputIterator](../../named_req/inputiterator "cpp/named req/InputIterator"). | ### Return value 1-3) Returns a pair consisting of an iterator to the inserted element (or to the element that prevented the insertion) and a `bool` denoting whether the insertion took place. 4-6) Returns an iterator to the inserted element, or to the element that prevented the insertion. 7-8) (none) 9) Returns an [`insert_return_type`](../map#Member_types "cpp/container/map") with the members initialized as follows: * 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()`. 10) End iterator if `nh` was empty, iterator pointing to the inserted element if insertion took place, and iterator pointing to an element with a key equivalent to `nh.key()` if it failed. ### Exceptions 1-6) If an exception is thrown by any operation, the insertion has no effect. ### Complexity 1-3) Logarithmic in the size of the container, `O(log(size()))`. | | | | --- | --- | | 4-6) Amortized constant if the insertion happens in the position just *after* the hint, logarithmic in the size of the container otherwise. | (until C++11) | | 4-6) Amortized constant if the insertion happens in the position just *before* the hint, logarithmic in the size of the container otherwise. | (since C++11) | 7-8) `O(N*log(size() + N))`, where N is the number of elements to insert. 9) Logarithmic in the size of the container, `O(log(size()))`. 10) Amortized constant if the insertion happens in the position just *before* the hint, logarithmic in the size of the container otherwise. ### Notes The hinted insert (4-6) does not return a boolean in order to be signature-compatible with positional insert on sequential containers, such as `[std::vector::insert](../vector/insert "cpp/container/vector/insert")`. This makes it possible to create generic inserters such as `[std::inserter](../../iterator/inserter "cpp/iterator/inserter")`. One way to check success of a hinted insert is to compare [`size()`](size "cpp/container/map/size") before and after. ### Example ``` #include <iomanip> #include <iostream> #include <map> #include <string> using namespace std::literals; template<typename It> void printInsertionStatus(It it, bool success) { std::cout << "Insertion of " << it->first << (success ? " succeeded\n" : " failed\n"); } int main() { std::map<std::string, float> karasunoPlayerHeights; // Overload 3: insert from rvalue reference const auto [it_hinata, success] = karasunoPlayerHeights.insert({"Hinata"s, 162.8}); printInsertionStatus(it_hinata, success); { // Overload 1: insert from lvalue reference const auto [it, success2] = karasunoPlayerHeights.insert(*it_hinata); printInsertionStatus(it, success2); } { // Overload 2: insert via forwarding to emplace const auto [it, success] = karasunoPlayerHeights.insert(std::pair{"Kageyama", 180.6}); printInsertionStatus(it, success); } { // Overload 6: insert from rvalue reference with positional hint const std::size_t n = std::size(karasunoPlayerHeights); const auto it = karasunoPlayerHeights.insert(it_hinata, {"Azumane"s, 184.7}); printInsertionStatus(it, std::size(karasunoPlayerHeights) != n); } { // Overload 4: insert from lvalue reference with positional hint const std::size_t n = std::size(karasunoPlayerHeights); const auto it = karasunoPlayerHeights.insert(it_hinata, *it_hinata); printInsertionStatus(it, std::size(karasunoPlayerHeights) != n); } { // Overload 5: insert via forwarding to emplace with positional hint const std::size_t n = std::size(karasunoPlayerHeights); const auto it = karasunoPlayerHeights.insert(it_hinata, std::pair{"Tsukishima", 188.3}); printInsertionStatus(it, std::size(karasunoPlayerHeights) != n); } auto node_hinata = karasunoPlayerHeights.extract(it_hinata); std::map<std::string, float> playerHeights; // Overload 7: insert from iterator range playerHeights.insert(std::begin(karasunoPlayerHeights), std::end(karasunoPlayerHeights)); // Overload 8: insert from initializer_list playerHeights.insert({{"Kozume"s, 169.2}, {"Kuroo", 187.7}}); // Overload 9: insert node const auto status = playerHeights.insert(std::move(node_hinata)); printInsertionStatus(status.position, status.inserted); node_hinata = playerHeights.extract(status.position); { // Overload 10: insert node with positional hint const std::size_t n = std::size(playerHeights); const auto it = playerHeights.insert(std::begin(playerHeights), std::move(node_hinata)); printInsertionStatus(it, std::size(playerHeights) != n); } // Print resulting map std::cout << std::left << '\n'; for (const auto& [name, height] : playerHeights) std::cout << std::setw(10) << name << " | " << height << "cm\n"; } ``` Output: ``` Insertion of Hinata succeeded Insertion of Hinata failed Insertion of Kageyama succeeded Insertion of Azumane succeeded Insertion of Hinata failed Insertion of Tsukishima succeeded Insertion of Hinata succeeded Insertion of Hinata succeeded Azumane | 184.7cm Hinata | 162.8cm Kageyama | 180.6cm Kozume | 169.2cm Kuroo | 187.7cm Tsukishima | 188.3cm ``` ### See also | | | | --- | --- | | [emplace](emplace "cpp/container/map/emplace") (C++11) | constructs element in-place (public member function) | | [emplace\_hint](emplace_hint "cpp/container/map/emplace hint") (C++11) | constructs elements in-place using a hint (public member function) | | [insert\_or\_assign](insert_or_assign "cpp/container/map/insert or assign") (C++17) | inserts an element or assigns to the current element if the key already exists (public member function) | | [inserter](../../iterator/inserter "cpp/iterator/inserter") | creates a `[std::insert\_iterator](../../iterator/insert_iterator "cpp/iterator/insert iterator")` of type inferred from the argument (function template) |
programming_docs
cpp std::map<Key,T,Compare,Allocator>::get_allocator std::map<Key,T,Compare,Allocator>::get\_allocator ================================================= | | | | | --- | --- | --- | | ``` allocator_type get_allocator() const; ``` | | (until C++11) | | ``` allocator_type get_allocator() const noexcept; ``` | | (since C++11) | Returns the allocator associated with the container. ### Parameters (none). ### Return value The associated allocator. ### Complexity Constant. cpp std::map<Key,T,Compare,Allocator>::merge std::map<Key,T,Compare,Allocator>::merge ======================================== | | | | | --- | --- | --- | | ``` template<class C2> void merge( std::map<Key, T, C2, Allocator>& source ); ``` | (1) | (since C++17) | | ``` template<class C2> void merge( std::map<Key, T, C2, Allocator>&& source ); ``` | (2) | (since C++17) | | ``` template<class C2> void merge( std::multimap<Key, T, C2, Allocator>& source ); ``` | (3) | (since C++17) | | ``` template<class C2> void merge( std::multimap<Key, T, C2, Allocator>&& source ); ``` | (4) | (since C++17) | Attempts to extract ("splice") each element in `source` and insert it into `*this` using the comparison object of `*this`. If there is an element in `*this` with key equivalent to the key of an element from `source`, then that element is not extracted from `source`. No elements are copied or moved, only the internal pointers of the container nodes are repointed. All pointers and references to the transferred elements remain valid, but now refer into `*this`, not into `source`. The behavior is undefined if `get_allocator() != source.get_allocator()`. ### Parameters | | | | | --- | --- | --- | | source | - | compatible container to transfer the nodes from | ### Return value (none). ### Exceptions Does not throw unless comparison throws. ### Complexity N\*log(size()+N)), where N is `source.size()`. ### Example ``` #include <map> #include <iostream> #include <string> int main() { std::map<int, std::string> ma {{1, "apple"}, {5, "pear"}, {10, "banana"}}; std::map<int, std::string> mb {{2, "zorro"}, {4, "batman"}, {5, "X"}, {8, "alpaca"}}; std::map<int, std::string> u; u.merge(ma); std::cout << "ma.size(): " << ma.size() << '\n'; u.merge(mb); std::cout << "mb.size(): " << mb.size() << '\n'; std::cout << "mb.at(5): " << mb.at(5) << '\n'; for(auto const &kv: u) std::cout << kv.first << ", " << kv.second << '\n'; } ``` Output: ``` ma.size(): 0 mb.size(): 1 mb.at(5): X 1, apple 2, zorro 4, batman 5, pear 8, alpaca 10, banana ``` ### See also | | | | --- | --- | | [extract](extract "cpp/container/map/extract") (C++17) | extracts nodes from the container (public member function) | | [insert](insert "cpp/container/map/insert") | inserts elements or nodes (since C++17) (public member function) | cpp std::map<Key,T,Compare,Allocator>::extract std::map<Key,T,Compare,Allocator>::extract ========================================== | | | | | --- | --- | --- | | ``` node_type extract( const_iterator position ); ``` | (1) | (since C++17) | | ``` node_type extract( const Key& k ); ``` | (2) | (since C++17) | | ``` template< class K > node_type extract( K&& x ); ``` | (3) | (since C++23) | 1) Unlinks the node that contains the element pointed to by `position` and returns a [node handle](../node_handle "cpp/container/node handle") that owns it. 2) If the container has an element with key equivalent to `k`, unlinks the node that contains that element from the container and returns a [node handle](../node_handle "cpp/container/node handle") that owns it. Otherwise, returns an empty node handle. 3) Same as (2). This overload participates in overload resolution only if the qualified-id `Compare::is_transparent` is valid and denotes a type, and neither `iterator` nor `const_iterator` is implicitly convertible from `K`. It allows calling this function without constructing an instance of `Key`. In either case, no elements are copied or moved, only the internal pointers of the container nodes are repointed (rebalancing may occur, as with `[erase()](erase "cpp/container/map/erase")`). Extracting a node invalidates only the iterators to the extracted element. Pointers and references to the extracted element remain valid, but cannot be used while element is owned by a node handle: they become usable if the element is inserted into a container. ### Parameters | | | | | --- | --- | --- | | position | - | a valid iterator into this container | | k | - | a key to identify the node to be extracted | | x | - | a value of any type that can be transparently compared with a key identifying the node to be extracted | ### Return value A [node handle](../node_handle "cpp/container/node handle") that owns the extracted element, or empty node handle in case the element is not found in (2,3). ### Exceptions 1) Throws nothing. 2,3) Any exceptions thrown by the `Compare` object. ### Complexity 1) amortized constant 2,3) log(`a.size()`) ### Notes extract is the only way to change a key of a map element without reallocation: ``` std::map<int, std::string> m{{1, "mango"}, {2, "papaya"}, {3, "guava"}}; auto nh = m.extract(2); nh.key() = 4; m.insert(std::move(nh)); // m == {{1, "mango"}, {3, "guava"}, {4, "papaya"}} ``` | [Feature-test](../../utility/feature_test "cpp/utility/feature test") macro | Comment | | --- | --- | | [`__cpp_lib_associative_heterogeneous_erasure`](../../feature_test#Library_features "cpp/feature test") | for overload (3) | ### Example ``` #include <algorithm> #include <iostream> #include <string_view> #include <map> void print(std::string_view comment, const auto& data) { std::cout << comment; for (auto [k, v] : data) std::cout << ' ' << k << '(' << v << ')'; std::cout << '\n'; } int main() { std::map<int, char> cont{{1, 'a'}, {2, 'b'}, {3, 'c'}}; print("Start:", cont); // Extract node handle and change key auto nh = cont.extract(1); nh.key() = 4; print("After extract and before insert:", cont); // Insert node handle back cont.insert(std::move(nh)); print("End:", cont); } ``` Output: ``` Start: 1(a) 2(b) 3(c) After extract and before insert: 2(b) 3(c) End: 2(b) 3(c) 4(a) ``` ### See also | | | | --- | --- | | [merge](merge "cpp/container/map/merge") (C++17) | splices nodes from another container (public member function) | | [insert](insert "cpp/container/map/insert") | inserts elements or nodes (since C++17) (public member function) | | [erase](erase "cpp/container/map/erase") | erases elements (public member function) | cpp std::map<Key,T,Compare,Allocator>::lower_bound std::map<Key,T,Compare,Allocator>::lower\_bound =============================================== | | | | | --- | --- | --- | | ``` iterator lower_bound( const Key& key ); ``` | (1) | | | ``` const_iterator lower_bound( const Key& key ) const; ``` | (2) | | | ``` template< class K > iterator lower_bound( const K& x ); ``` | (3) | (since C++14) | | ``` template< class K > const_iterator lower_bound( const K& x ) const; ``` | (4) | (since C++14) | 1,2) Returns an iterator pointing to the first element that is *not less* than (i.e. greater or equal to) `key`. 3,4) Returns an iterator pointing to the first element that compares *not less* (i.e. greater or equal) to the value `x`. This overload participates in overload resolution only if the qualified-id `Compare::is_transparent` is valid and denotes a type. It allows calling this function without constructing an instance of `Key`. ### Parameters | | | | | --- | --- | --- | | key | - | key value to compare the elements to | | x | - | alternative value that can be compared to `Key` | ### Return value Iterator pointing to the first element that is not *less* than `key`. If no such element is found, a past-the-end iterator (see `[end()](end "cpp/container/map/end")`) is returned. ### Complexity Logarithmic in the size of the container. ### Notes | [Feature-test](../../utility/feature_test "cpp/utility/feature test") macro | Comment | | --- | --- | | [`__cpp_lib_generic_associative_lookup`](../../feature_test#Library_features "cpp/feature test") | for overloads (3,4) | ### Example ### See also | | | | --- | --- | | [equal\_range](equal_range "cpp/container/map/equal range") | returns range of elements matching a specific key (public member function) | | [upper\_bound](upper_bound "cpp/container/map/upper bound") | returns an iterator to the first element *greater* than the given key (public member function) | cpp std::map<Key,T,Compare,Allocator>::emplace_hint std::map<Key,T,Compare,Allocator>::emplace\_hint ================================================ | | | | | --- | --- | --- | | ``` template <class... Args> iterator emplace_hint( const_iterator hint, Args&&... args ); ``` | | (since C++11) | Inserts a new element to the container as close as possible to the position just before `hint`. The element is constructed in-place, i.e. no copy or move operations are performed. The constructor of the element type (`value_type`, that is, `[std::pair](http://en.cppreference.com/w/cpp/utility/pair)<const Key, T>`) is called with exactly the same arguments as supplied to the function, forwarded with `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Args>(args)...`. No iterators or references are invalidated. ### Parameters | | | | | --- | --- | --- | | hint | - | iterator to the position before which the new element will be inserted | | args | - | arguments to forward to the constructor of the element | ### Return value Returns an iterator to the newly inserted element. If the insertion failed because the element already exists, returns an iterator to the already existing element with the equivalent key. ### Exceptions If an exception is thrown by any operation, this function has no effect (strong exception guarantee). ### Complexity Logarithmic in the size of the container in general, but amortized constant if the new element is inserted just before `hint`. ### Example ``` #include <chrono> #include <functional> #include <iomanip> #include <iostream> #include <map> const int n_operations = 100500; std::size_t map_emplace() { std::map<int, char> map; for (int i = 0; i < n_operations; ++i) { map.emplace(i, 'a'); } return map.size(); } std::size_t map_emplace_hint() { std::map<int, char> map; auto it = map.begin(); for (int i = 0; i < n_operations; ++i) { map.emplace_hint(it, i, 'b'); it = map.end(); } return map.size(); } std::size_t map_emplace_hint_wrong() { std::map<int, char> map; auto it = map.begin(); for (int i = n_operations; i > 0; --i) { map.emplace_hint(it, i, 'c'); it = map.end(); } return map.size(); } std::size_t map_emplace_hint_corrected() { std::map<int, char> map; auto it = map.begin(); for (int i = n_operations; i > 0; --i) { map.emplace_hint(it, i, 'd'); it = map.begin(); } return map.size(); } std::size_t map_emplace_hint_closest() { std::map<int, char> map; auto it = map.begin(); for (int i = 0; i < n_operations; ++i) { it = map.emplace_hint(it, i, 'e'); } return map.size(); } void timeit(std::function<std::size_t()> map_test, std::string what = "") { auto start = std::chrono::system_clock::now(); std::size_t mapsize = map_test(); auto stop = std::chrono::system_clock::now(); std::chrono::duration<double, std::milli> time = stop - start; if (what.size() > 0 && mapsize > 0) { std::cout << std::setw(5) << time.count() << " ms for " << what << '\n'; } } int main() { std::cout << std::fixed << std::setprecision(2); timeit(map_emplace); // stack warmup timeit(map_emplace, "plain emplace"); timeit(map_emplace_hint, "emplace with correct hint"); timeit(map_emplace_hint_wrong, "emplace with wrong hint"); timeit(map_emplace_hint_corrected, "corrected emplace"); timeit(map_emplace_hint_closest, "emplace using returned iterator"); } ``` Possible output: ``` 22.64 ms for plain emplace 8.81 ms for emplace with correct hint 22.27 ms for emplace with wrong hint 7.76 ms for corrected emplace 8.30 ms for emplace using returned iterator ``` ### See also | | | | --- | --- | | [emplace](emplace "cpp/container/map/emplace") (C++11) | constructs element in-place (public member function) | | [insert](insert "cpp/container/map/insert") | inserts elements or nodes (since C++17) (public member function) | cpp std::map<Key,T,Compare,Allocator>::rbegin, std::map<Key,T,Compare,Allocator>::crbegin std::map<Key,T,Compare,Allocator>::rbegin, std::map<Key,T,Compare,Allocator>::crbegin ===================================================================================== | | | | | --- | --- | --- | | ``` reverse_iterator rbegin(); ``` | | (until C++11) | | ``` reverse_iterator rbegin() noexcept; ``` | | (since C++11) | | ``` const_reverse_iterator rbegin() const; ``` | | (until C++11) | | ``` const_reverse_iterator rbegin() const noexcept; ``` | | (since C++11) | | ``` const_reverse_iterator crbegin() const noexcept; ``` | | (since C++11) | Returns a reverse iterator to the first element of the reversed `map`. It corresponds to the last element of the non-reversed `map`. If the `map` is empty, the returned iterator is equal to `[rend()](rend "cpp/container/map/rend")`. ![range-rbegin-rend.svg]() ### Parameters (none). ### Return value Reverse iterator to the first element. ### Complexity Constant. ### Example ``` #include <iomanip> #include <iostream> #include <map> #include <string_view> int main() { const std::map<int, std::string_view> coins { {10, "dime"}, {100, "dollar"}, {50, "half dollar"}, {5, "nickel"}, {1, "penny"}, {25, "quarter"} }; // initializer entries in name alphabetical order std::cout << "US coins in circulation, largest to smallest denomination:\n"; for (auto it = coins.crbegin(); it != coins.crend(); ++it) { std::cout << std::setw(11) << it->second << " = ¢" << it->first << '\n'; } } ``` Output: ``` US coins in circulation, largest to smallest denomination: dollar = ¢100 half dollar = ¢50 quarter = ¢25 dime = ¢10 nickel = ¢5 penny = ¢1 ``` ### See also | | | | --- | --- | | [rendcrend](rend "cpp/container/map/rend") (C++11) | returns a reverse iterator to the end (public member function) | | [rbegincrbegin](../../iterator/rbegin "cpp/iterator/rbegin") (C++14) | returns a reverse iterator to the beginning of a container or array (function template) | cpp std::map<Key,T,Compare,Allocator>::at std::map<Key,T,Compare,Allocator>::at ===================================== | | | | | --- | --- | --- | | ``` T& at( const Key& key ); ``` | (1) | | | ``` const T& at( const Key& key ) const; ``` | (2) | | Returns a reference to the mapped value of the element with key equivalent to `key`. If no such element exists, an exception of type `[std::out\_of\_range](../../error/out_of_range "cpp/error/out of range")` is thrown. ### Parameters | | | | | --- | --- | --- | | key | - | the key of the element to find | ### Return value Reference to the mapped value of the requested element. ### Exceptions `[std::out\_of\_range](../../error/out_of_range "cpp/error/out of range")` if the container does not have an element with the specified `key`. ### Complexity Logarithmic in the size of the container. ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 464](https://cplusplus.github.io/LWG/issue464) | C++98 | `map` did not have this member function | added | ### See also | | | | --- | --- | | [operator[]](operator_at "cpp/container/map/operator at") | access or insert specified element (public member function) | cpp std::map<Key,T,Compare,Allocator>::operator[] std::map<Key,T,Compare,Allocator>::operator[] ============================================= | | | | | --- | --- | --- | | ``` T& operator[]( const Key& key ); ``` | (1) | | | ``` T& operator[]( Key&& key ); ``` | (2) | (since C++11) | Returns a reference to the value that is mapped to a key equivalent to `key`, performing an insertion if such key does not already exist. | | | | | | --- | --- | --- | --- | | 1) Inserts `value_type(key, T())` if the key does not exist. This function is equivalent to `return insert([std::make\_pair](http://en.cppreference.com/w/cpp/utility/pair/make_pair)(key, T())).first->second;` | | | --- | | -`key_type` must meet the requirements of [CopyConstructible](../../named_req/copyconstructible "cpp/named req/CopyConstructible"). | | -`mapped_type` must meet the requirements of [CopyConstructible](../../named_req/copyconstructible "cpp/named req/CopyConstructible") and [DefaultConstructible](../../named_req/defaultconstructible "cpp/named req/DefaultConstructible"). | If an insertion is performed, the mapped value is [value-initialized](../../language/value_initialization "cpp/language/value initialization") (default-constructed for class types, zero-initialized otherwise) and a reference to it is returned. | (until C++11) | | 1) Inserts a `value_type` object constructed in-place from `[std::piecewise\_construct](http://en.cppreference.com/w/cpp/utility/piecewise_construct), [std::forward\_as\_tuple](http://en.cppreference.com/w/cpp/utility/tuple/forward_as_tuple)(key), [std::tuple](http://en.cppreference.com/w/cpp/utility/tuple)<>()` if the key does not exist. This function is equivalent to `return this->try_emplace(key).first->second;`. (since C++17) When the default allocator is used, this results in the key being copy constructed from `key` and the mapped value being [value-initialized](../../language/value_initialization "cpp/language/value initialization"). | | | --- | | -`value_type` must be [EmplaceConstructible](../../named_req/emplaceconstructible "cpp/named req/EmplaceConstructible") from `[std::piecewise\_construct](http://en.cppreference.com/w/cpp/utility/piecewise_construct), [std::forward\_as\_tuple](http://en.cppreference.com/w/cpp/utility/tuple/forward_as_tuple)(key), [std::tuple](http://en.cppreference.com/w/cpp/utility/tuple)<>()`. When the default allocator is used, this means that `key_type` must be [CopyConstructible](../../named_req/copyconstructible "cpp/named req/CopyConstructible") and `mapped_type` must be [DefaultConstructible](../../named_req/defaultconstructible "cpp/named req/DefaultConstructible"). | 2) Inserts a `value_type` object constructed in-place from `[std::piecewise\_construct](http://en.cppreference.com/w/cpp/utility/piecewise_construct), [std::forward\_as\_tuple](http://en.cppreference.com/w/cpp/utility/tuple/forward_as_tuple)(std::move(key)), [std::tuple](http://en.cppreference.com/w/cpp/utility/tuple)<>()` if the key does not exist. This function is equivalent to `return this->try_emplace(std::move(key)).first->second;`. (since C++17) When the default allocator is used, this results in the key being move constructed from `key` and the mapped value being [value-initialized](../../language/value_initialization "cpp/language/value initialization"). | | | --- | | -`value_type` must be [EmplaceConstructible](../../named_req/emplaceconstructible "cpp/named req/EmplaceConstructible") from `[std::piecewise\_construct](http://en.cppreference.com/w/cpp/utility/piecewise_construct), [std::forward\_as\_tuple](http://en.cppreference.com/w/cpp/utility/tuple/forward_as_tuple)(std::move(key)), [std::tuple](http://en.cppreference.com/w/cpp/utility/tuple)<>()`. When the default allocator is used, this means that `key_type` must be [MoveConstructible](../../named_req/moveconstructible "cpp/named req/MoveConstructible") and `mapped_type` must be [DefaultConstructible](../../named_req/defaultconstructible "cpp/named req/DefaultConstructible"). | | (since C++11) | No iterators or references are invalidated. ### Parameters | | | | | --- | --- | --- | | key | - | the key of the element to find | ### Return value Reference to the mapped value of the new element if no element with key `key` existed. Otherwise a reference to the mapped value of the existing element whose key is equivalent to `key`. ### Exceptions If an exception is thrown by any operation, the insertion has no effect. ### Complexity Logarithmic in the size of the container. ### Notes In the published C++11 and C++14 standards, this function was specified to require `mapped_type` to be [DefaultInsertable](../../named_req/defaultinsertable "cpp/named req/DefaultInsertable") and `key_type` to be [CopyInsertable](../../named_req/copyinsertable "cpp/named req/CopyInsertable") or [MoveInsertable](../../named_req/moveinsertable "cpp/named req/MoveInsertable") into `*this`. This specification was defective and was fixed by [LWG issue 2469](https://cplusplus.github.io/LWG/issue2469), and the description above incorporates the resolution of that issue. However, one implementation (libc++) is known to construct the `key_type` and `mapped_type` objects via two separate allocator `construct()` calls, as arguably required by the standards as published, rather than emplacing a `value_type` object. `operator[]` is non-const because it inserts the key if it doesn't exist. If this behavior is undesirable or if the container is `const`, [`at()`](at "cpp/container/map/at") may be used. | | | | --- | --- | | [`insert_or_assign()`](insert_or_assign "cpp/container/map/insert or assign") returns more information than `operator[]` and does not require default-constructibility of the mapped type. | (since C++17) | ### Example ``` #include <iostream> #include <string> #include <map> auto print = [](auto const comment, auto const& map) { std::cout << comment << "{"; for (const auto &pair : map) { std::cout << "{" << pair.first << ": " << pair.second << "}"; } std::cout << "}\n"; }; int main() { std::map<char, int> letter_counts {{'a', 27}, {'b', 3}, {'c', 1}}; print("letter_counts initially contains: ", letter_counts); letter_counts['b'] = 42; // updates an existing value letter_counts['x'] = 9; // inserts a new value print("after modifications it contains: ", letter_counts); // count the number of occurrences of each word // (the first call to operator[] initialized the counter with zero) std::map<std::string, int> word_map; for (const auto &w : { "this", "sentence", "is", "not", "a", "sentence", "this", "sentence", "is", "a", "hoax"}) { ++word_map[w]; } word_map["that"]; // just inserts the pair {"that", 0} for (const auto &[word, count] : word_map) { std::cout << count << " occurrences of word '" << word << "'\n"; } } ``` Output: ``` letter_counts initially contains: {{a: 27}{b: 3}{c: 1}} after modifications it contains: {{a: 27}{b: 42}{c: 1}{x: 9}} 2 occurrences of word 'a' 1 occurrences of word 'hoax' 2 occurrences of word 'is' 1 occurrences of word 'not' 3 occurrences of word 'sentence' 0 occurrences of word 'that' 2 occurrences of word 'this' ``` ### See also | | | | --- | --- | | [at](at "cpp/container/map/at") | access specified element with bounds checking (public member function) | | [insert\_or\_assign](insert_or_assign "cpp/container/map/insert or assign") (C++17) | inserts an element or assigns to the current element if the key already exists (public member function) | | [try\_emplace](try_emplace "cpp/container/map/try emplace") (C++17) | inserts in-place if the key does not exist, does nothing if the key exists (public member function) |
programming_docs
cpp std::map<Key,T,Compare,Allocator>::swap std::map<Key,T,Compare,Allocator>::swap ======================================= | | | | | --- | --- | --- | | ``` void swap( map& other ); ``` | | (until C++17) | | ``` void swap( map& other ) noexcept(/* see below */); ``` | | (since C++17) | Exchanges the contents of the container with those of `other`. Does not invoke any move, copy, or swap operations on individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated. The `Compare` objects must be [Swappable](../../named_req/swappable "cpp/named req/Swappable"), and they are exchanged using unqualified call to non-member `swap`. | | | | --- | --- | | If `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<allocator_type>::propagate\_on\_container\_swap::value` is true, then the allocators are exchanged using an unqualified call to non-member `swap`. Otherwise, they are not swapped (and if `get_allocator() != other.get_allocator()`, the behavior is undefined). | (since C++11) | ### Parameters | | | | | --- | --- | --- | | other | - | container to exchange the contents with | ### Return value (none). ### Exceptions | | | | --- | --- | | Any exception thrown by the swap of the `Compare` objects. | (until C++17) | | [`noexcept`](../../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept([std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<Allocator>::is\_always\_equal::value && [std::is\_nothrow\_swappable](http://en.cppreference.com/w/cpp/types/is_swappable)<Compare>::value)` | (since C++17) | ### Complexity Constant. ### Example ``` #include <iostream> #include <string> #include <utility> #include <map> // print out a std::pair template <class Os, class U, class V> Os& operator<<(Os& os, const std::pair<U, V>& p) { return os << p.first << ":" << p.second; } // print out a container template <class Os, class Co> Os& operator<<(Os& os, const Co& co) { os << "{"; for (auto const& i : co) { os << ' ' << i; } return os << " }\n"; } int main() { std::map<std::string, std::string> m1 { {"γ", "gamma"}, {"β", "beta"}, {"α", "alpha"}, {"γ", "gamma"}, }, m2 { {"ε", "epsilon"}, {"δ", "delta"}, {"ε", "epsilon"} }; const auto& ref = *(m1.begin()); const auto iter = std::next(m1.cbegin()); std::cout << "──────── before swap ────────\n" << "m1: " << m1 << "m2: " << m2 << "ref: " << ref << "\niter: " << *iter << '\n'; m1.swap(m2); std::cout << "──────── after swap ────────\n" << "m1: " << m1 << "m2: " << m2 << "ref: " << ref << "\niter: " << *iter << '\n'; // Note that every iterator referring to an element in one container before // the swap refers to the same element in the other container after the swap. // Same is true for references. } ``` Output: ``` ──────── before swap ──────── m1: { α:alpha β:beta γ:gamma } m2: { δ:delta ε:epsilon } ref: α:alpha iter: β:beta ──────── after swap ──────── m1: { δ:delta ε:epsilon } m2: { α:alpha β:beta γ:gamma } ref: α:alpha iter: β:beta ``` ### See also | | | | --- | --- | | [std::swap(std::map)](swap2 "cpp/container/map/swap2") | specializes the `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | cpp std::map<Key,T,Compare,Allocator>::max_size std::map<Key,T,Compare,Allocator>::max\_size ============================================ | | | | | --- | --- | --- | | ``` size_type max_size() const; ``` | | (until C++11) | | ``` size_type max_size() const noexcept; ``` | | (since C++11) | Returns the maximum number of elements the container is able to hold due to system or library implementation limitations, i.e. `[std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(begin(), end())` for the largest container. ### Parameters (none). ### Return value Maximum number of elements. ### Complexity Constant. ### Notes This value typically reflects the theoretical limit on the size of the container, at most `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<difference_type>::max()`. At runtime, the size of the container may be limited to a value smaller than `max_size()` by the amount of RAM available. ### Example ``` #include <iostream> #include <locale> #include <map> int main() { std::map<char, char> q; std::cout.imbue(std::locale("en_US.UTF-8")); std::cout << "Maximum size of a std::map is " << q.max_size() << '\n'; } ``` Possible output: ``` Maximum size of a std::map is 576,460,752,303,423,487 ``` ### See also | | | | --- | --- | | [size](size "cpp/container/map/size") | returns the number of elements (public member function) | cpp std::map<Key,T,Compare,Allocator>::count std::map<Key,T,Compare,Allocator>::count ======================================== | | | | | --- | --- | --- | | ``` size_type count( const Key& key ) const; ``` | (1) | | | ``` template< class K > size_type count( const K& x ) const; ``` | (2) | (since C++14) | Returns the number of elements with key that compares *equivalent* to the specified argument, which is either 1 or 0 since this container does not allow duplicates. 1) Returns the number of elements with key `key`. 2) Returns the number of elements with key that compares equivalent to the value `x`. This overload participates in overload resolution only if the qualified-id `Compare::is_transparent` is valid and denotes a type. They allow calling this function without constructing an instance of `Key`. ### Parameters | | | | | --- | --- | --- | | key | - | key value of the elements to count | | x | - | alternative value to compare to the keys | ### Return value Number of elements with key that compares *equivalent* to `key` or `x`, which is either 1 or 0 for (1). ### Complexity Logarithmic in the size of the container. ### Example ### See also | | | | --- | --- | | [find](find "cpp/container/map/find") | finds element with specific key (public member function) | | [equal\_range](equal_range "cpp/container/map/equal range") | returns range of elements matching a specific key (public member function) | cpp std::map<Key,T,Compare,Allocator>::value_comp std::map<Key,T,Compare,Allocator>::value\_comp ============================================== | | | | | --- | --- | --- | | ``` std::map::value_compare value_comp() const; ``` | | | Returns a function object that compares objects of type std::map::value\_type (key-value pairs) by using `[key\_comp](key_comp "cpp/container/map/key comp")` to compare the first components of the pairs. ### Parameters (none). ### Return value The value comparison function object. ### Complexity Constant. ### Example ``` #include <cassert> #include <iostream> #include <map> // Example module 97 key compare function struct ModCmp { bool operator()(const int lhs, const int rhs) const { return (lhs % 97) < (rhs % 97); } }; int main() { std::map<int, char, ModCmp> cont; cont = { { 1, 'a' }, { 2, 'b' }, { 3, 'c' }, { 4, 'd' }, { 5, 'e' } }; auto comp_func = cont.value_comp(); const std::pair<int, char> val = { 100, 'a' }; for (auto it : cont) { bool before = comp_func(it, val); bool after = comp_func(val, it); std::cout << '(' << it.first << ',' << it.second; if (!before && !after) std::cout << ") equivalent to key " << val.first << '\n'; else if (before) std::cout << ") goes before key " << val.first << '\n'; else if (after) std::cout << ") goes after key " << val.first << '\n'; else assert(0); // Cannot happen } } ``` Output: ``` (1,a) goes before key 100 (2,b) goes before key 100 (3,c) equivalent to key 100 (4,d) goes after key 100 (5,e) goes after key 100 ``` ### See also | | | | --- | --- | | [key\_comp](key_comp "cpp/container/map/key comp") | returns the function that compares keys (public member function) | cpp std::map<Key,T,Compare,Allocator>::find std::map<Key,T,Compare,Allocator>::find ======================================= | | | | | --- | --- | --- | | ``` iterator find( const Key& key ); ``` | (1) | | | ``` const_iterator find( const Key& key ) const; ``` | (2) | | | ``` template< class K > iterator find( const K& x ); ``` | (3) | (since C++14) | | ``` template< class K > const_iterator find( const K& x ) const; ``` | (4) | (since C++14) | 1,2) Finds an element with key equivalent to `key`. 3,4) Finds an element with key that compares *equivalent* to the value `x`. This overload participates in overload resolution only if the qualified-id `Compare::is_transparent` is valid and denotes a type. It allows calling this function without constructing an instance of `Key`. ### Parameters | | | | | --- | --- | --- | | key | - | key value of the element to search for | | x | - | a value of any type that can be transparently compared with a key | ### Return value Iterator to an element with key equivalent to `key`. If no such element is found, past-the-end (see `[end()](end "cpp/container/map/end")`) iterator is returned. ### Complexity Logarithmic in the size of the container. ### Notes | [Feature-test](../../utility/feature_test "cpp/utility/feature test") macro | Comment | | --- | --- | | [`__cpp_lib_generic_associative_lookup`](../../feature_test#Library_features "cpp/feature test") | for overloads (3,4) | ### Example ``` #include <iostream> #include <map> struct FatKey { int x; int data[1000]; }; struct LightKey { int x; }; // Note: as detailed above, the container must use std::less<> (or other // transparent Comparator) to access these overloads. // This includes standard overloads, such as between std::string and std::string_view. bool operator<(const FatKey& fk, const LightKey& lk) { return fk.x < lk.x; } bool operator<(const LightKey& lk, const FatKey& fk) { return lk.x < fk.x; } bool operator<(const FatKey& fk1, const FatKey& fk2) { return fk1.x < fk2.x; } int main() { // simple comparison demo std::map<int,char> example = {{1,'a'},{2,'b'}}; auto search = example.find(2); if (search != example.end()) { std::cout << "Found " << search->first << " " << search->second << '\n'; } else { std::cout << "Not found\n"; } // transparent comparison demo std::map<FatKey, char, std::less<>> example2 = { { {1, {} },'a'}, { {2, {} },'b'} }; LightKey lk = {2}; auto search2 = example2.find(lk); if (search2 != example2.end()) { std::cout << "Found " << search2->first.x << " " << search2->second << '\n'; } else { std::cout << "Not found\n"; } // Obtaining const iterators. // Compiler decides whether to return iterator of (non) const type by way of accessing // map; to prevent modification on purpose, one of easiest choices is to access map by // const reference. const auto& example2ref = example2; auto search3 = example2ref.find(lk); if (search3 != example2.end()) { std::cout << "Found " << search3->first.x << ' ' << search3->second << '\n'; // search3->second = 'c'; // error: assignment of member // 'std::pair<const FatKey, char>::second' // in read-only object } } ``` Output: ``` Found 2 b Found 2 b Found 2 b ``` ### See also | | | | --- | --- | | [count](count "cpp/container/map/count") | returns the number of elements matching specific key (public member function) | | [equal\_range](equal_range "cpp/container/map/equal range") | returns range of elements matching a specific key (public member function) | cpp std::map<Key,T,Compare,Allocator>::value_compare std::map<Key,T,Compare,Allocator>::value\_compare ================================================= | | | | | --- | --- | --- | | ``` class value_compare; ``` | | | `std::map::value_compare` is a function object that compares objects of type `std::map::value_type` (key-value pairs) by comparing of the first components of the pairs. ### Member types | Type | Definition | | --- | --- | | `result_type` (deprecated in C++17)(removed in C++20) | `bool` | | `first_argument_type` (deprecated in C++17)(removed in C++20) | `value_type` | | `second_argument_type` (deprecated in C++17)(removed in C++20) | `value_type` | | | | | --- | --- | | These member types are obtained via publicly inheriting `[std::binary\_function](http://en.cppreference.com/w/cpp/utility/functional/binary_function)<value_type, value_type, bool>`. | (until C++11) | ### Protected member objects | | | | --- | --- | | Compare comp | the stored comparator (protected member object) | ### Member functions | | | | --- | --- | | **(constructor)** | constructs a new `value_compare` object (protected member function) | | **operator()** | compares two values of type `value_type` (public member function) | std::map<Key,T,Compare,Alloc>::value\_compare::value\_compare -------------------------------------------------------------- | | | | | --- | --- | --- | | ``` protected: value_compare( Compare c ); ``` | | | Initializes the internal instance of the comparator to `c`. ### Parameters | | | | | --- | --- | --- | | c | - | comparator to assign | std::map<Key,T,Compare,Alloc>::value\_compare::operator() ---------------------------------------------------------- | | | | | --- | --- | --- | | ``` bool operator()( const value_type& lhs, const value_type& rhs ) const; ``` | | | Compares `lhs.first` and `rhs.first` by calling the stored comparator. ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | values to compare | ### Return value `comp(lhs.first, rhs.first)`. ### Exceptions May throw implementation-defined exceptions. cpp std::map<Key,T,Compare,Allocator>::equal_range std::map<Key,T,Compare,Allocator>::equal\_range =============================================== | | | | | --- | --- | --- | | ``` std::pair<iterator,iterator> equal_range( const Key& key ); ``` | (1) | | | ``` std::pair<const_iterator,const_iterator> equal_range( const Key& key ) const; ``` | (2) | | | ``` template< class K > std::pair<iterator,iterator> equal_range( const K& x ); ``` | (3) | (since C++14) | | ``` template< class K > std::pair<const_iterator,const_iterator> equal_range( const K& x ) const; ``` | (4) | (since C++14) | Returns a range containing all elements with the given key in the container. The range is defined by two iterators, one pointing to the first element that is *not less* than `key` and another pointing to the first element *greater* than `key`. Alternatively, the first iterator may be obtained with `[lower\_bound()](lower_bound "cpp/container/map/lower bound")`, and the second with `[upper\_bound()](upper_bound "cpp/container/map/upper bound")`. 1,2) Compares the keys to `key`. 3,4) Compares the keys to the value `x`. This overload participates in overload resolution only if the qualified-id `Compare::is_transparent` is valid and denotes a type. It allows calling this function without constructing an instance of `Key`. ### Parameters | | | | | --- | --- | --- | | key | - | key value to compare the elements to | | x | - | alternative value that can be compared to `Key` | ### Return value `[std::pair](../../utility/pair "cpp/utility/pair")` containing a pair of iterators defining the wanted range: the first pointing to the first element that is not *less* than `key` and the second pointing to the first element *greater* than `key`. If there are no elements *not less* than `key`, past-the-end (see `[end()](end "cpp/container/map/end")`) iterator is returned as the first element. Similarly if there are no elements *greater* than `key`, past-the-end iterator is returned as the second element. ### Complexity Logarithmic in the size of the container. ### Notes | [Feature-test](../../utility/feature_test "cpp/utility/feature test") macro | Comment | | --- | --- | | [`__cpp_lib_generic_associative_lookup`](../../feature_test#Library_features "cpp/feature test") | for overloads (3,4) | ### Example ``` #include <map> #include <iostream> int main() { const std::map<int, const char*> m{ { 0, "zero" }, { 1, "one" }, { 2, "two" }, }; { auto p = m.equal_range(1); for (auto& q = p.first; q != p.second; ++q) { std::cout << "m[" << q->first << "] = " << q->second << '\n'; } if (p.second == m.find(2)) { std::cout << "end of equal_range (p.second) is one-past p.first\n"; } else { std::cout << "unexpected; p.second expected to be one-past p.first\n"; } } { auto pp = m.equal_range(-1); if (pp.first == m.begin()) { std::cout << "pp.first is iterator to first not-less than -1\n"; } else { std::cout << "unexpected pp.first\n"; } if (pp.second == m.begin()) { std::cout << "pp.second is iterator to first element greater-than -1\n"; } else { std::cout << "unexpected pp.second\n"; } } { auto ppp = m.equal_range(3); if (ppp.first == m.end()) { std::cout << "ppp.first is iterator to first not-less than 3\n"; } else { std::cout << "unexpected ppp.first\n"; } if (ppp.second == m.end()) { std::cout << "ppp.second is iterator to first element greater-than 3\n"; } else { std::cout << "unexpected ppp.second\n"; } } } ``` Output: ``` m[1] = one end of equal_range (p.second) is one-past p.first pp.first is iterator to first not-less than -1 pp.second is iterator to first element greater-than -1 ppp.first is iterator to first not-less than 3 ppp.second is iterator to first element greater-than 3 ``` ### See also | | | | --- | --- | | [find](find "cpp/container/map/find") | finds element with specific key (public member function) | | [contains](contains "cpp/container/map/contains") (C++20) | checks if the container contains element with specific key (public member function) | | [count](count "cpp/container/map/count") | returns the number of elements matching specific key (public member function) | | [upper\_bound](upper_bound "cpp/container/map/upper bound") | returns an iterator to the first element *greater* than the given key (public member function) | | [lower\_bound](lower_bound "cpp/container/map/lower bound") | returns an iterator to the first element *not less* than the given key (public member function) | | [equal\_range](../../algorithm/equal_range "cpp/algorithm/equal range") | returns range of elements matching a specific key (function template) | cpp std::map<Key,T,Compare,Allocator>::key_comp std::map<Key,T,Compare,Allocator>::key\_comp ============================================ | | | | | --- | --- | --- | | ``` key_compare key_comp() const; ``` | | | Returns the function object that compares the keys, which is a copy of this container's [constructor](map "cpp/container/map/map") argument `comp`. ### Parameters (none). ### Return value The key comparison function object. ### Complexity Constant. ### Example ``` #include <cassert> #include <iostream> #include <map> // Example module 97 key compare function struct ModCmp { bool operator()(const int lhs, const int rhs) const { return (lhs % 97) < (rhs % 97); } }; int main() { std::map<int, char, ModCmp> cont; cont = { { 1, 'a' }, { 2, 'b' }, { 3, 'c' }, { 4, 'd' }, { 5, 'e' } }; auto comp_func = cont.key_comp(); for (auto it : cont) { bool before = comp_func(it.first, 100); bool after = comp_func(100, it.first); std::cout << '(' << it.first << ',' << it.second; if (!before && !after) std::cout << ") equivalent to key 100\n"; else if (before) std::cout << ") goes before key 100\n"; else if (after) std::cout << ") goes after key 100\n"; else assert(0); // Cannot happen } } ``` Output: ``` (1,a) goes before key 100 (2,b) goes before key 100 (3,c) equivalent to key 100 (4,d) goes after key 100 (5,e) goes after key 100 ``` ### See also | | | | --- | --- | | [value\_comp](value_comp "cpp/container/map/value comp") | returns the function that compares keys in objects of type value\_type (public member function) |
programming_docs
cpp std::map<Key,T,Compare,Allocator>::erase std::map<Key,T,Compare,Allocator>::erase ======================================== | | | | | --- | --- | --- | | | (1) | | | ``` void erase( iterator pos ); ``` | (until C++11) | | ``` iterator erase( iterator pos ); ``` | (since C++11) | | ``` iterator erase( const_iterator pos ); ``` | (since C++11) | | | (2) | | | ``` void erase( iterator first, iterator last ); ``` | (until C++11) | | ``` iterator erase( const_iterator first, const_iterator last ); ``` | (since C++11) | | ``` size_type erase( const Key& key ); ``` | (3) | | | ``` template< class K > size_type erase( K&& x ); ``` | (4) | (since C++23) | Removes specified elements from the container. 1) Removes the element at `pos`. 2) Removes the elements in the range `[first; last)`, which must be a valid range in `*this`. 3) Removes the element (if one exists) with the key equivalent to `key`. 4) Removes the element (if one exists) with key that compares *equivalent* to the value `x`. This overload participates in overload resolution only if the qualified-id `Compare::is_transparent` is valid and denotes a type, and neither `iterator` nor `const_iterator` is implicitly convertible from `K`. It allows calling this function without constructing an instance of `Key`. References and iterators to the erased elements are invalidated. Other references and iterators are not affected. The iterator `pos` must be valid and dereferenceable. Thus the `[end()](end "cpp/container/map/end")` iterator (which is valid, but is not dereferenceable) cannot be used as a value for `pos`. ### Parameters | | | | | --- | --- | --- | | pos | - | iterator to the element to remove | | first, last | - | range of elements to remove | | key | - | key value of the elements to remove | | x | - | a value of any type that can be transparently compared with a key denoting the elements to remove | ### Return value 1-2) (none) (until C++11)Iterator following the last removed element. (since C++11) 3,4) Number of elements removed (`0` or `1`). ### Exceptions 1,2) Throws nothing. 3,4) Any exceptions thrown by the `Compare` object. ### Complexity Given an instance `c` of `map`: 1) Amortized constant 2) `log(c.size()) + [std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(first, last)` 3) `log(c.size()) + c.count(key)` 4) `log(c.size()) + c.count(x)` ### Notes | [Feature-test](../../utility/feature_test "cpp/utility/feature test") macro | Comment | | --- | --- | | [`__cpp_lib_associative_heterogeneous_erasure`](../../feature_test#Library_features "cpp/feature test") | for overload (4) | ### Example ``` #include <map> #include <iostream> int main() { std::map<int, std::string> c = { {1, "one" }, {2, "two" }, {3, "three"}, {4, "four"}, {5, "five"}, {6, "six" } }; // erase all odd numbers from c for(auto it = c.begin(); it != c.end(); ) { if(it->first % 2 != 0) it = c.erase(it); else ++it; } for(auto& p : c) { std::cout << p.second << ' '; } } ``` Output: ``` two four six ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 2059](https://cplusplus.github.io/LWG/issue2059) | C++11 | overload for one `const_iterator` introduced new ambiguity | overload for `iterator` added | ### See also | | | | --- | --- | | [clear](clear "cpp/container/map/clear") | clears the contents (public member function) | cpp std::swap(std::map) std::swap(std::map) =================== | Defined in header `[<map>](../../header/map "cpp/header/map")` | | | | --- | --- | --- | | ``` template< class Key, class T, class Compare, class Alloc > void swap( std::map<Key,T,Compare,Alloc>& lhs, std::map<Key,T,Compare,Alloc>& rhs ); ``` | | (until C++17) | | ``` template< class Key, class T, class Compare, class Alloc > void swap( std::map<Key,T,Compare,Alloc>& lhs, std::map<Key,T,Compare,Alloc>& rhs ) noexcept(/* see below */); ``` | | (since C++17) | Specializes the `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` algorithm for `[std::map](http://en.cppreference.com/w/cpp/container/map)`. Swaps the contents of `lhs` and `rhs`. Calls `lhs.swap(rhs)`. ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | containers whose contents to swap | ### Return value (none). ### Complexity Constant. ### Exceptions | | | | --- | --- | | [`noexcept`](../../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept(noexcept(lhs.swap(rhs)))` | (since C++17) | ### Notes Although the overloads of `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` for container adaptors are introduced in C++11, container adaptors can already be swapped by `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` in C++98. Such calls to `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` usually have linear time complexity, but better complexity may be provided. ### Example ``` #include <algorithm> #include <iostream> #include <map> int main() { std::map<int, char> alice{{1, 'a'}, {2, 'b'}, {3, 'c'}}; std::map<int, char> bob{{7, 'Z'}, {8, 'Y'}, {9, 'X'}, {10, 'W'}}; auto print = [](std::pair<const int, char>& n) { std::cout << " " << n.first << '(' << n.second << ')'; }; // Print state before swap std::cout << "alice:"; std::for_each(alice.begin(), alice.end(), print); std::cout << "\n" "bob :"; std::for_each(bob.begin(), bob.end(), print); std::cout << '\n'; std::cout << "-- SWAP\n"; std::swap(alice, bob); // Print state after swap std::cout << "alice:"; std::for_each(alice.begin(), alice.end(), print); std::cout << "\n" "bob :"; std::for_each(bob.begin(), bob.end(), print); std::cout << '\n'; } ``` Output: ``` alice: 1(a) 2(b) 3(c) bob : 7(Z) 8(Y) 9(X) 10(W) -- SWAP alice: 7(Z) 8(Y) 9(X) 10(W) bob : 1(a) 2(b) 3(c) ``` ### See also | | | | --- | --- | | [swap](swap "cpp/container/map/swap") | swaps the contents (public member function) | cpp std::map<Key,T,Compare,Allocator>::try_emplace std::map<Key,T,Compare,Allocator>::try\_emplace =============================================== | | | | | --- | --- | --- | | ``` template< class... Args > pair<iterator, bool> try_emplace( const Key& k, Args&&... args ); ``` | (1) | (since C++17) | | ``` template< class... Args > pair<iterator, bool> try_emplace( Key&& k, Args&&... args ); ``` | (2) | (since C++17) | | ``` template< class... Args > iterator try_emplace( const_iterator hint, const Key& k, Args&&... args ); ``` | (3) | (since C++17) | | ``` template< class... Args > iterator try_emplace( const_iterator hint, Key&& k, Args&&... args ); ``` | (4) | (since C++17) | Inserts a new element into the container with key `k` and value constructed with `args`, if there is no element with the key in the container. 1) If a key equivalent to `k` already exists in the container, does nothing. Otherwise, behaves like [`emplace`](emplace "cpp/container/map/emplace") except that the element is constructed as `value_type([std::piecewise\_construct](http://en.cppreference.com/w/cpp/utility/piecewise_construct), [std::forward\_as\_tuple](http://en.cppreference.com/w/cpp/utility/tuple/forward_as_tuple)(k), [std::forward\_as\_tuple](http://en.cppreference.com/w/cpp/utility/tuple/forward_as_tuple). ([std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Args>(args)...))` 2) If a key equivalent to `k` already exists in the container, does nothing. Otherwise, behaves like [`emplace`](emplace "cpp/container/map/emplace") except that the element is constructed as `value_type([std::piecewise\_construct](http://en.cppreference.com/w/cpp/utility/piecewise_construct), [std::forward\_as\_tuple](http://en.cppreference.com/w/cpp/utility/tuple/forward_as_tuple)(std::move(k)), [std::forward\_as\_tuple](http://en.cppreference.com/w/cpp/utility/tuple/forward_as_tuple). ([std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Args>(args)...))` 3) If a key equivalent to `k` already exists in the container, does nothing. Otherwise, behaves like [`emplace_hint`](emplace_hint "cpp/container/map/emplace hint") except that the element is constructed as `value_type([std::piecewise\_construct](http://en.cppreference.com/w/cpp/utility/piecewise_construct), [std::forward\_as\_tuple](http://en.cppreference.com/w/cpp/utility/tuple/forward_as_tuple)(k), [std::forward\_as\_tuple](http://en.cppreference.com/w/cpp/utility/tuple/forward_as_tuple). ([std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Args>(args)...))` 4) If a key equivalent to `k` already exists in the container, does nothing. Otherwise, behaves like [`emplace_hint`](emplace_hint "cpp/container/map/emplace hint") except that the element is constructed as `value_type([std::piecewise\_construct](http://en.cppreference.com/w/cpp/utility/piecewise_construct), [std::forward\_as\_tuple](http://en.cppreference.com/w/cpp/utility/tuple/forward_as_tuple)(std::move(k)), [std::forward\_as\_tuple](http://en.cppreference.com/w/cpp/utility/tuple/forward_as_tuple). ([std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Args>(args)...))` No iterators or references are invalidated. ### Parameters | | | | | --- | --- | --- | | k | - | the key used both to look up and to insert if not found | | hint | - | iterator to the position before which the new element will be inserted | | args | - | arguments to forward to the constructor of the element | ### Return value 1,2) Same as for [`emplace`](emplace "cpp/container/map/emplace") 3,4) Same as for [`emplace_hint`](emplace_hint "cpp/container/map/emplace hint") ### Complexity 1,2) Same as for [`emplace`](emplace "cpp/container/map/emplace") 3,4) Same as for [`emplace_hint`](emplace_hint "cpp/container/map/emplace hint") ### Notes Unlike [`insert`](insert "cpp/container/map/insert") or [`emplace`](emplace "cpp/container/map/emplace"), these functions do not move from rvalue arguments if the insertion does not happen, which makes it easy to manipulate maps whose values are move-only types, such as `[std::map](http://en.cppreference.com/w/cpp/container/map)<[std::string](http://en.cppreference.com/w/cpp/string/basic_string), [std::unique\_ptr](http://en.cppreference.com/w/cpp/memory/unique_ptr)<foo>>`. In addition, `try_emplace` treats the key and the arguments to the `mapped_type` separately, unlike [`emplace`](emplace "cpp/container/map/emplace"), which requires the arguments to construct a `value_type` (that is, a `[std::pair](../../utility/pair "cpp/utility/pair")`). | [Feature-test](../../utility/feature_test "cpp/utility/feature test") macro | | --- | | [`__cpp_lib_map_try_emplace`](../../feature_test#Library_features "cpp/feature test") | ### Example ``` #include <iostream> #include <utility> #include <string> #include <map> auto print_node = [](const auto &node) { std::cout << "[" << node.first << "] = " << node.second << '\n'; }; auto print_result = [](auto const &pair) { std::cout << (pair.second ? "inserted: " : "ignored: "); print_node(*pair.first); }; int main() { using namespace std::literals; std::map<std::string, std::string> m; print_result( m.try_emplace("a", "a"s) ); print_result( m.try_emplace("b", "abcd") ); print_result( m.try_emplace("c", 10, 'c') ); print_result( m.try_emplace("c", "Won't be inserted") ); for (const auto &p : m) { print_node(p); } } ``` Output: ``` inserted: [a] = a inserted: [b] = abcd inserted: [c] = cccccccccc ignored: [c] = cccccccccc [a] = a [b] = abcd [c] = cccccccccc ``` ### See also | | | | --- | --- | | [emplace](emplace "cpp/container/map/emplace") (C++11) | constructs element in-place (public member function) | | [emplace\_hint](emplace_hint "cpp/container/map/emplace hint") (C++11) | constructs elements in-place using a hint (public member function) | | [insert](insert "cpp/container/map/insert") | inserts elements or nodes (since C++17) (public member function) | cpp std::erase_if (std::map) std::erase\_if (std::map) ========================= | Defined in header `[<map>](../../header/map "cpp/header/map")` | | | | --- | --- | --- | | ``` template< class Key, class T, class Compare, class Alloc, class Pred > typename std::map<Key,T,Compare,Alloc>::size_type erase_if( std::map<Key,T,Compare,Alloc>& c, Pred pred ); ``` | | (since C++20) | Erases all elements that satisfy the predicate `pred` from the container. Equivalent to. ``` auto old_size = c.size(); for (auto i = c.begin(), last = c.end(); i != last; ) { if (pred(*i)) { i = c.erase(i); } else { ++i; } } return old_size - c.size(); ``` ### Parameters | | | | | --- | --- | --- | | c | - | container from which to erase | | pred | - | predicate that returns `true` if the element should be erased | ### Return value The number of erased elements. ### Complexity Linear. ### Example ``` #include <map> #include <iostream> template<typename Os, typename Container> inline Os& operator<<(Os& os, Container const& cont) { os << "{"; for (const auto& item : cont) { os << "{" << item.first << ", " << item.second << "}"; } return os << "}"; } int main() { std::map<int, char> data {{1, 'a'},{2, 'b'},{3, 'c'},{4, 'd'}, {5, 'e'},{4, 'f'},{5, 'g'},{5, 'g'}}; std::cout << "Original:\n" << data << '\n'; const auto count = std::erase_if(data, [](const auto& item) { auto const& [key, value] = item; return (key & 1) == 1; }); std::cout << "Erase items with odd keys:\n" << data << '\n' << count << " items removed.\n"; } ``` Output: ``` Original: {{1, a}{2, b}{3, c}{4, d}{5, e}} Erase items with odd keys: {{2, b}{4, d}} 3 items removed. ``` ### See also | | | | --- | --- | | [removeremove\_if](../../algorithm/remove "cpp/algorithm/remove") | removes elements satisfying specific criteria (function template) | cpp std::map<Key,T,Compare,Allocator>::~map std::map<Key,T,Compare,Allocator>::~map ======================================= | | | | | --- | --- | --- | | ``` ~map(); ``` | | | Destructs the `map`. The destructors of the elements are called and the used storage is deallocated. Note, that if the elements are pointers, the pointed-to objects are not destroyed. ### Complexity Linear in the size of the `map`. cpp std::map<Key,T,Compare,Allocator>::operator= std::map<Key,T,Compare,Allocator>::operator= ============================================ | | | | | --- | --- | --- | | ``` map& operator=( const map& other ); ``` | (1) | | | | (2) | | | ``` map& operator=( map&& other ); ``` | (since C++11) (until C++17) | | ``` map& operator=( map&& other ) noexcept(/* see below */); ``` | (since C++17) | | ``` map& operator=( std::initializer_list<value_type> ilist ); ``` | (3) | (since C++11) | Replaces the contents of the container. 1) Copy assignment operator. Replaces the contents with a copy of the contents of `other`. | | | | --- | --- | | If `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<allocator_type>::propagate\_on\_container\_copy\_assignment::value` is `true`, the allocator of `*this` is replaced by a copy of that of `other`. If the allocator of `*this` after assignment would compare unequal to its old value, the old allocator is used to deallocate the memory, then the new allocator is used to allocate it before copying the elements. Otherwise, the memory owned by `*this` may be reused when possible. In any case, the elements originally belonging to `*this` may be either destroyed or replaced by element-wise copy-assignment. | (since C++11) | 2) Move assignment operator. Replaces the contents with those of `other` using move semantics (i.e. the data in `other` is moved from `other` into this container). `other` is in a valid but unspecified state afterwards. If `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<allocator_type>::propagate\_on\_container\_move\_assignment::value` is `true`, the allocator of `*this` is replaced by a copy of that of `other`. If it is `false` and the allocators of `*this` and `other` do not compare equal, `*this` cannot take ownership of the memory owned by `other` and must move-assign each element individually, allocating additional memory using its own allocator as needed. In any case, all elements originally belonging to `*this` are either destroyed or replaced by element-wise move-assignment. 3) Replaces the contents with those identified by initializer list `ilist`. ### Parameters | | | | | --- | --- | --- | | other | - | another container to use as data source | | ilist | - | initializer list to use as data source | ### Return value `*this`. ### Complexity 1) Linear in the size of `*this` and `other`. 2) Linear in the size of `*this` unless the allocators do not compare equal and do not propagate, in which case linear in the size of `*this` and `other`. 3) O(NlogN) in general, where N is `size() + ilist.size()`. Linear if `ilist` is sorted with respect to `[value\_comp()](value_comp "cpp/container/map/value comp")`. ### Exceptions | | | | --- | --- | | May throw implementation-defined exceptions. | (until C++17) | | 1,3) May throw implementation-defined exceptions. 2) [`noexcept`](../../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept([std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<Allocator>::is\_always\_equal::value && [std::is\_nothrow\_move\_assignable](http://en.cppreference.com/w/cpp/types/is_move_assignable)<Compare>::value)` | (since C++17) | ### Notes After container move assignment (overload (2)), unless element-wise move assignment is forced by incompatible allocators, references, pointers, and iterators (other than the end iterator) to `other` remain valid, but refer to elements that are now in `*this`. The current standard makes this guarantee via the blanket statement in [[container.requirements.general]/12](https://eel.is/c++draft/container.requirements.general#12), and a more direct guarantee is under consideration via [LWG 2321](https://cplusplus.github.io/LWG/issue2321). ### Example The following code uses `operator=` to assign one `[std::map](../map "cpp/container/map")` to another: ``` #include <map> #include <iterator> #include <iostream> #include <utility> #include <initializer_list> void print(auto const comment, auto const& container) { auto size = std::size(container); std::cout << comment << "{ "; for (auto const& [key, value]: container) std::cout << '{' << key << ',' << value << (--size ? "}, " : "} "); std::cout << "}\n"; } int main() { std::map<int, int> x { {1,1}, {2,2}, {3,3} }, y, z; const auto w = { std::pair<const int, int>{4,4}, {5,5}, {6,6}, {7,7} }; std::cout << "Initially:\n"; print("x = ", x); print("y = ", y); print("z = ", z); std::cout << "Copy assignment copies data from x to y:\n"; y = x; print("x = ", x); print("y = ", y); std::cout << "Move assignment moves data from x to z, modifying both x and z:\n"; z = std::move(x); print("x = ", x); print("z = ", z); std::cout << "Assignment of initializer_list w to z:\n"; z = w; print("w = ", w); print("z = ", z); } ``` Output: ``` Initially: x = { {1,1}, {2,2}, {3,3} } y = { } z = { } Copy assignment copies data from x to y: x = { {1,1}, {2,2}, {3,3} } y = { {1,1}, {2,2}, {3,3} } Move assignment moves data from x to z, modifying both x and z: x = { } z = { {1,1}, {2,2}, {3,3} } Assignment of initializer_list w to z: w = { {4,4}, {5,5}, {6,6}, {7,7} } z = { {4,4}, {5,5}, {6,6}, {7,7} } ``` ### See also | | | | --- | --- | | [(constructor)](map "cpp/container/map/map") | constructs the `map` (public member function) |
programming_docs
cpp std::map<Key,T,Compare,Allocator>::rend, std::map<Key,T,Compare,Allocator>::crend std::map<Key,T,Compare,Allocator>::rend, std::map<Key,T,Compare,Allocator>::crend ================================================================================= | | | | | --- | --- | --- | | ``` reverse_iterator rend(); ``` | | (until C++11) | | ``` reverse_iterator rend() noexcept; ``` | | (since C++11) | | ``` const_reverse_iterator rend() const; ``` | | (until C++11) | | ``` const_reverse_iterator rend() const noexcept; ``` | | (since C++11) | | ``` const_reverse_iterator crend() const noexcept; ``` | | (since C++11) | Returns a reverse iterator to the element following the last element of the reversed `map`. It corresponds to the element preceding the first element of the non-reversed `map`. This element acts as a placeholder, attempting to access it results in undefined behavior. ![range-rbegin-rend.svg]() ### Parameters (none). ### Return value Reverse iterator to the element following the last element. ### Complexity Constant. ### Example ``` #include <iostream> #include <iomanip> #include <chrono> #include <map> #include <string_view> using namespace std::chrono; // until C++20 chrono operator<< ready std::ostream& operator<<(std::ostream& os, const year_month_day& ymd) { return os << std::setfill('0') << static_cast<int>(ymd.year()) << '/' << std::setw(2) << static_cast<unsigned>(ymd.month()) << '/' << std::setw(2) << static_cast<unsigned>(ymd.day()); } int main() { const std::map<year_month_day, int> messages { { February/17/2023 , 10 }, { February/17/2023 , 20 }, { February/16/2022 , 30 }, { October/22/2022 , 40 }, { June/14/2022 , 50 }, { November/23/2021 , 60 }, { December/10/2022 , 55 }, { December/12/2021 , 45 }, { April/1/2020 , 42 }, { April/1/2020 , 24 }, }; std::cout << "Messages received, reverse date order:\n"; for (auto it = messages.crbegin(); it != messages.crend(); ++it) { std::cout << it->first << " : " << it->second << '\n'; } } ``` Possible output: ``` Messages received, reverse date order: 2023/02/17 : 10 2022/12/10 : 55 2022/10/22 : 40 2022/06/14 : 50 2022/02/16 : 30 2021/12/12 : 45 2021/11/23 : 60 2020/04/01 : 42 ``` ### See also | | | | --- | --- | | [rbegincrbegin](rbegin "cpp/container/map/rbegin") (C++11) | returns a reverse iterator to the beginning (public member function) | | [rendcrend](../../iterator/rend "cpp/iterator/rend") (C++14) | returns a reverse end iterator for a container or array (function template) | cpp std::map<Key,T,Compare,Allocator>::clear std::map<Key,T,Compare,Allocator>::clear ======================================== | | | | | --- | --- | --- | | ``` void clear(); ``` | | (until C++11) | | ``` void clear() noexcept; ``` | | (since C++11) | Erases all elements from the container. After this call, `[size()](size "cpp/container/map/size")` returns zero. Invalidates any references, pointers, or iterators referring to contained elements. Any past-the-end iterator remains valid. ### Parameters (none). ### Return value (none). ### Complexity Linear in the size of the container, i.e., the number of elements. ### Example ``` #include <algorithm> #include <iostream> #include <map> int main() { std::map<int, char> container{{1, 'x'}, {2, 'y'}, {3, 'z'}}; auto print = [](std::pair<const int, char>& n) { std::cout << " " << n.first << '(' << n.second << ')'; }; std::cout << "Before clear:"; std::for_each(container.begin(), container.end(), print); std::cout << "\nSize=" << container.size() << '\n'; std::cout << "Clear\n"; container.clear(); std::cout << "After clear:"; std::for_each(container.begin(), container.end(), print); std::cout << "\nSize=" << container.size() << '\n'; } ``` Output: ``` Before clear: 1(x) 2(y) 3(z) Size=3 Clear After clear: Size=0 ``` ### See also | | | | --- | --- | | [erase](erase "cpp/container/map/erase") | erases elements (public member function) | cpp std::map<Key,T,Compare,Allocator>::upper_bound std::map<Key,T,Compare,Allocator>::upper\_bound =============================================== | | | | | --- | --- | --- | | ``` iterator upper_bound( const Key& key ); ``` | (1) | | | ``` const_iterator upper_bound( const Key& key ) const; ``` | (2) | | | ``` template< class K > iterator upper_bound( const K& x ); ``` | (3) | (since C++14) | | ``` template< class K > const_iterator upper_bound( const K& x ) const; ``` | (4) | (since C++14) | 1,2) Returns an iterator pointing to the first element that is *greater* than `key`. 3,4) Returns an iterator pointing to the first element that compares *greater* to the value `x`. This overload participates in overload resolution only if the qualified-id `Compare::is_transparent` is valid and denotes a type. It allows calling this function without constructing an instance of `Key`. ### Parameters | | | | | --- | --- | --- | | key | - | key value to compare the elements to | | x | - | alternative value that can be compared to `Key` | ### Return value Iterator pointing to the first element that is *greater* than `key`. If no such element is found, past-the-end (see `[end()](end "cpp/container/map/end")`) iterator is returned. ### Complexity Logarithmic in the size of the container. ### Notes | [Feature-test](../../utility/feature_test "cpp/utility/feature test") macro | Comment | | --- | --- | | [`__cpp_lib_generic_associative_lookup`](../../feature_test#Library_features "cpp/feature test") | for overloads (3,4) | ### Example ### See also | | | | --- | --- | | [equal\_range](equal_range "cpp/container/map/equal range") | returns range of elements matching a specific key (public member function) | | [lower\_bound](lower_bound "cpp/container/map/lower bound") | returns an iterator to the first element *not less* than the given key (public member function) | cpp std::map<Key,T,Compare,Allocator>::empty std::map<Key,T,Compare,Allocator>::empty ======================================== | | | | | --- | --- | --- | | ``` bool empty() const; ``` | | (until C++11) | | ``` bool empty() const noexcept; ``` | | (since C++11) (until C++20) | | ``` [[nodiscard]] bool empty() const noexcept; ``` | | (since C++20) | Checks if the container has no elements, i.e. whether `begin() == end()`. ### Parameters (none). ### Return value `true` if the container is empty, `false` otherwise. ### Complexity Constant. ### Example The following code uses `empty` to check if a `[std::map](http://en.cppreference.com/w/cpp/container/map)<int, int>` contains any elements: ``` #include <map> #include <iostream> #include <utility> int main() { std::map<int,int> numbers; std::cout << std::boolalpha; std::cout << "Initially, numbers.empty(): " << numbers.empty() << '\n'; numbers.emplace(42, 13); numbers.insert(std::make_pair(13317, 123)); std::cout << "After adding elements, numbers.empty(): " << numbers.empty() << '\n'; } ``` Output: ``` Initially, numbers.empty(): true After adding elements, numbers.empty(): false ``` ### See also | | | | --- | --- | | [size](size "cpp/container/map/size") | returns the number of elements (public member function) | | [empty](../../iterator/empty "cpp/iterator/empty") (C++17) | checks whether the container is empty (function template) | cpp std::map<Key,T,Compare,Allocator>::begin, std::map<Key,T,Compare,Allocator>::cbegin std::map<Key,T,Compare,Allocator>::begin, std::map<Key,T,Compare,Allocator>::cbegin =================================================================================== | | | | | --- | --- | --- | | ``` iterator begin(); ``` | | (until C++11) | | ``` iterator begin() noexcept; ``` | | (since C++11) | | ``` const_iterator begin() const; ``` | | (until C++11) | | ``` const_iterator begin() const noexcept; ``` | | (since C++11) | | ``` const_iterator cbegin() const noexcept; ``` | | (since C++11) | Returns an iterator to the first element of the `map`. If the `map` is empty, the returned iterator will be equal to `[end()](end "cpp/container/map/end")`. ![range-begin-end.svg]() ### Parameters (none). ### Return value Iterator to the first element. ### Complexity Constant. ### Example ``` #include <iostream> #include <map> int main() { std::map<int, float> num_map; num_map[4] = 4.13; num_map[9] = 9.24; num_map[1] = 1.09; // calls a_map.begin() and a_map.end() for (auto it = num_map.begin(); it != num_map.end(); ++it) { std::cout << it->first << ", " << it->second << '\n'; } } ``` Output: ``` 1, 1.09 4, 4.13 9, 9.24 ``` #### Example using a custom comparison function ``` #include <cmath> #include <iostream> #include <map> struct Point { double x, y; }; //Compare the x-coordinates of two Point pointers struct PointCmp { bool operator()(const Point *lhs, const Point *rhs) const { return lhs->x < rhs->x; } }; int main() { //Note that although the x-coordinates are out of order, the // map will be iterated through by increasing x-coordinates Point points[3] = { {2, 0}, {1, 0}, {3, 0} }; //mag is a map sending the address of node to its magnitude in the x-y plane //Although the keys are pointers-to-Point, we want to order the map by the // x-coordinates of the points and NOT by the addresses of the Points. This // is done by using the PointCmp class's comparison method. std::map<Point *, double, PointCmp> mag({ { points, 2 }, { points + 1, 1 }, { points + 2, 3 } }); //Change each y-coordinate from 0 to the magnitude for(auto iter = mag.begin(); iter != mag.end(); ++iter){ auto cur = iter->first; // pointer to Node cur->y = mag[cur]; // could also have used cur->y = iter->second; } //Update and print the magnitude of each node for(auto iter = mag.begin(); iter != mag.end(); ++iter){ auto cur = iter->first; mag[cur] = std::hypot(cur->x, cur->y); std::cout << "The magnitude of (" << cur->x << ", " << cur->y << ") is "; std::cout << iter->second << '\n'; } //Repeat the above with the range-based for loop for(auto i : mag) { auto cur = i.first; cur->y = i.second; mag[cur] = std::hypot(cur->x, cur->y); std::cout << "The magnitude of (" << cur->x << ", " << cur->y << ") is "; std::cout << mag[cur] << '\n'; // Note that in contrast to std::cout << iter->second << '\n'; above, // std::cout << i.second << '\n'; will NOT print the updated magnitude // If auto &i: mag was used instead, it will print the updated magnitude } } ``` Output: ``` The magnitude of (1, 1) is 1.41421 The magnitude of (2, 2) is 2.82843 The magnitude of (3, 3) is 4.24264 The magnitude of (1, 1.41421) is 1.73205 The magnitude of (2, 2.82843) is 3.4641 The magnitude of (3, 4.24264) is 5.19615 ``` ### See also | | | | --- | --- | | [end cend](end "cpp/container/map/end") (C++11) | returns an iterator to the end (public member function) | | [begincbegin](../../iterator/begin "cpp/iterator/begin") (C++11)(C++14) | returns an iterator to the beginning of a container or array (function template) | cpp std::map<Key,T,Compare,Allocator>::end, std::map<Key,T,Compare,Allocator>::cend std::map<Key,T,Compare,Allocator>::end, std::map<Key,T,Compare,Allocator>::cend =============================================================================== | | | | | --- | --- | --- | | ``` iterator end(); ``` | | (until C++11) | | ``` iterator end() noexcept; ``` | | (since C++11) | | ``` const_iterator end() const; ``` | | (until C++11) | | ``` const_iterator end() const noexcept; ``` | | (since C++11) | | ``` const_iterator cend() const noexcept; ``` | | (since C++11) | Returns an iterator to the element following the last element of the `map`. This element acts as a placeholder; attempting to access it results in undefined behavior. ![range-begin-end.svg]() ### Parameters (none). ### Return value Iterator to the element following the last element. ### Complexity Constant. ### Example ``` #include <iostream> #include <map> int main() { std::map<int, float> num_map; num_map[4] = 4.13; num_map[9] = 9.24; num_map[1] = 1.09; // calls a_map.begin() and a_map.end() for (auto it = num_map.begin(); it != num_map.end(); ++it) { std::cout << it->first << ", " << it->second << '\n'; } } ``` Output: ``` 1, 1.09 4, 4.13 9, 9.24 ``` #### Example using a custom comparison function ``` #include <cmath> #include <iostream> #include <map> struct Point { double x, y; }; //Compare the x-coordinates of two Point pointers struct PointCmp { bool operator()(const Point *lhs, const Point *rhs) const { return lhs->x < rhs->x; } }; int main() { //Note that although the x-coordinates are out of order, the // map will be iterated through by increasing x-coordinates Point points[3] = { {2, 0}, {1, 0}, {3, 0} }; //mag is a map sending the address of node to its magnitude in the x-y plane //Although the keys are pointers-to-Point, we want to order the map by the // x-coordinates of the points and NOT by the addresses of the Points. This // is done by using the PointCmp class's comparison method. std::map<Point *, double, PointCmp> mag({ { points, 2 }, { points + 1, 1 }, { points + 2, 3 } }); //Change each y-coordinate from 0 to the magnitude for(auto iter = mag.begin(); iter != mag.end(); ++iter){ auto cur = iter->first; // pointer to Node cur->y = mag[cur]; // could also have used cur->y = iter->second; } //Update and print the magnitude of each node for(auto iter = mag.begin(); iter != mag.end(); ++iter){ auto cur = iter->first; mag[cur] = std::hypot(cur->x, cur->y); std::cout << "The magnitude of (" << cur->x << ", " << cur->y << ") is "; std::cout << iter->second << '\n'; } //Repeat the above with the range-based for loop for(auto i : mag) { auto cur = i.first; cur->y = i.second; mag[cur] = std::hypot(cur->x, cur->y); std::cout << "The magnitude of (" << cur->x << ", " << cur->y << ") is "; std::cout << mag[cur] << '\n'; // Note that in contrast to std::cout << iter->second << '\n'; above, // std::cout << i.second << '\n'; will NOT print the updated magnitude // If auto &i: mag was used instead, it will print the updated magnitude } } ``` Output: ``` The magnitude of (1, 1) is 1.41421 The magnitude of (2, 2) is 2.82843 The magnitude of (3, 3) is 4.24264 The magnitude of (1, 1.41421) is 1.73205 The magnitude of (2, 2.82843) is 3.4641 The magnitude of (3, 4.24264) is 5.19615 ``` ### See also | | | | --- | --- | | [begin cbegin](begin "cpp/container/map/begin") (C++11) | returns an iterator to the beginning (public member function) | | [endcend](../../iterator/end "cpp/iterator/end") (C++11)(C++14) | returns an iterator to the end of a container or array (function template) | cpp std::span<T,Extent>::size std::span<T,Extent>::size ========================= | | | | | --- | --- | --- | | ``` constexpr size_type size() const noexcept; ``` | | | Returns the number of elements in the span. ### Parameters (none). ### Return value The number of elements in the span. ### Note | [Feature-test](../../utility/feature_test "cpp/utility/feature test") macro | | --- | | [`__cpp_lib_ssize`](../../feature_test#Library_features "cpp/feature test") | ### Example ``` #include <iostream> #include <span> void show_sizes(std::span<const int> span) { std::cout << span .size() << ' ' // 8 << span.first(7) .size() << ' ' // 7 << span.first<6>() .size() << ' ' // 6 << span.last(5) .size() << ' ' // 5 << span.last<4>() .size() << ' ' // 4 << span.subspan(2, 3) .size() << ' ' // 3 << span.subspan<3, 2>() .size() << ' ' // 2 << '\n'; } int main() { int antique_array[] { 1, 2, 3, 4, 5, 6, 7, 8 }; show_sizes(antique_array); } ``` Output: ``` 8 7 6 5 4 3 2 ``` ### See also | | | | --- | --- | | [(constructor)](span "cpp/container/span/span") | constructs a `span` (public member function) | | [size\_bytes](size_bytes "cpp/container/span/size bytes") | returns the size of the sequence in bytes (public member function) | cpp deduction guides for std::span deduction guides for `std::span` ================================ | Defined in header `[<span>](../../header/span "cpp/header/span")` | | | | --- | --- | --- | | ``` template <class It, class EndOrSize> span(It, EndOrSize) -> span<std::remove_reference_t<std::iter_reference_t<It>>>; ``` | (1) | | | ``` template<class T, std::size_t N> span(T (&)[N]) -> span<T, N>; ``` | (2) | | | ``` template<class T, std::size_t N> span(std::array<T, N>&) -> span<T, N>; ``` | (3) | | | ``` template<class T, std::size_t N> span(const std::array<T, N>&) -> span<const T, N>; ``` | (4) | | | ``` template<class R> span(R&&) -> span<std::remove_reference_t<std::ranges::range_reference_t<R>>>; ``` | (5) | | The following [deduction guides](../../language/class_template_argument_deduction "cpp/language/class template argument deduction") are provided for `span`. (1) allow the element type to be deduced from the iterator-sentinel pair. This overload participates in overload resolution only if `It` satisfies [`contiguous_iterator`](../../iterator/contiguous_iterator "cpp/iterator/contiguous iterator"). (2-4) allow the static extent to be deduced from built-in arrays and `[std::array](../array "cpp/container/array")`. (5) allow the element type to be deduced from ranges. This overload participates in overload resolution only if `R` satisfies [`contiguous_range`](../../ranges/contiguous_range "cpp/ranges/contiguous range"). ### Example ``` #include <array> #include <cstddef> #include <iomanip> #include <iostream> #include <span> #include <string_view> #include <vector> void print(std::string_view rem = "", std::size_t size_of = 0, std::size_t extent = 0) { if (rem.empty()) { std::cout << "name │ sizeof │ extent\n─────┼────────┼────────\n"; return; } std::cout << std::setw(4) << rem << " │ " << std::setw(6) << size_of << " │ "; if (extent == std::dynamic_extent) std::cout << "dynamic"; else std::cout << extent; std::cout << '\n'; } int main() { int a[] {1, 2, 3, 4, 5}; print(); std::span s1 {std::begin(a), std::end(a)}; // guide (1) print("s1", sizeof s1, s1.extent); std::span s2 {std::begin(a), 3}; // guide (1) print("s2", sizeof s2, s2.extent); std::span s3 {a}; // guide (2) print("s3", sizeof s3, s3.extent); std::span<int> s4 {a}; // does not use a guide, makes a dynamic span print("s4", sizeof s4, s4.extent); std::array arr {6, 7, 8}; std::span s5 {arr}; // guide (3) print("s5", sizeof s5, s5.extent); s5[0] = 42; // OK, element_type is 'int' const std::array arr2 {9, 10, 11}; std::span s6 {arr2}; // guide (4) print("s6", sizeof s6, s6.extent); // s6[0] = 42; // Error: element_type is 'const int' std::vector v {66, 69, 99}; std::span s7 {v}; // guide (5) print("s7", sizeof s7, s7.extent); } ``` Output: ``` name │ sizeof │ extent ─────┼────────┼──────── s1 │ 16 │ dynamic s2 │ 16 │ dynamic s3 │ 8 │ 5 s4 │ 16 │ dynamic s5 │ 8 │ 3 s6 │ 8 │ 3 s7 │ 16 │ dynamic ```
programming_docs
cpp std::span<T,Extent>::last std::span<T,Extent>::last ========================= | | | | | --- | --- | --- | | ``` template< std::size_t Count > constexpr std::span<element_type, Count> last() const; ``` | | | | ``` constexpr std::span<element_type, std::dynamic_extent> last( size_type Count ) const; ``` | | | Obtains a span that is a view over the last `Count` elements of this span. The program is ill-formed if `Count > Extent`. The behavior is undefined if `Count > size()`. ### Return value A span `r` that is a view over the last `Count` elements of `*this`, such that `r.data() == this->data() + (this->size() - Count) && r.size() == Count`. ### Example ``` #include <iostream> #include <span> #include <string_view> auto print = [](std::string_view const title, auto const& container) { std::cout << title << "[" << std::size(container) << "]{ "; for (auto const& elem : container) std::cout << elem << ", "; std::cout << "};\n"; }; void run(std::span<const int> span) { print("span: ", span); std::span<const int, 3> span_last = span.last<3>(); print("span.last<3>(): ", span_last); std::span<const int, std::dynamic_extent> span_last_dynamic = span.last(2); print("span.last(2): ", span_last_dynamic); } int main() { int a[8]{ 1, 2, 3, 4, 5, 6, 7, 8, }; print("int a", a); run(a); } ``` Output: ``` int a[8]{ 1, 2, 3, 4, 5, 6, 7, 8, }; span: [8]{ 1, 2, 3, 4, 5, 6, 7, 8, }; span.last<3>(): [3]{ 6, 7, 8, }; span.last(2): [2]{ 7, 8, }; ``` ### See also | | | | --- | --- | | [first](first "cpp/container/span/first") | obtains a subspan consisting of the first N elements of the sequence (public member function) | | [subspan](subspan "cpp/container/span/subspan") | obtains a subspan (public member function) | cpp std::span<T,Extent>::rbegin std::span<T,Extent>::rbegin =========================== | | | | | --- | --- | --- | | ``` constexpr reverse_iterator rbegin() const noexcept; ``` | | | Returns a reverse iterator to the first element of the reversed `span`. It corresponds to the last element of the non-reversed `span`. If the `span` is empty, the returned iterator is equal to `rend()`. ![range-rbegin-rend.svg]() ### Parameters (none). ### Return value Reverse iterator to the first element. ### Complexity Constant. ### Example ``` #include <algorithm> #include <iostream> #include <iterator> #include <span> int main() { constexpr std::span<const char> code{ "@droNE_T0P_w$s@s#_SECRET_a,p^42!" }; auto hacker = [](const unsigned O) { return O-0141<120; }; std::copy_if(code.rbegin(), code.rend(), std::ostream_iterator<const char>(std::cout), hacker); } ``` Output: ``` password ``` ### See also | | | | --- | --- | | [rend](rend "cpp/container/span/rend") (C++20) | returns a reverse iterator to the end (public member function) | | [rbegincrbegin](../../iterator/rbegin "cpp/iterator/rbegin") (C++14) | returns a reverse iterator to the beginning of a container or array (function template) | cpp std::span<T,Extent>::size_bytes std::span<T,Extent>::size\_bytes ================================ | | | | | --- | --- | --- | | ``` constexpr size_type size_bytes() const noexcept; ``` | | | Returns the size of the sequence in bytes. ### Parameters (none). ### Return value The size of the sequence in bytes, i.e., `size() * sizeof(element_type)`. ### Example ``` #include <span> #include <cstdint> int main() { static constexpr std::int32_t a[] { 1, 2, 3, 4, 5 }; constexpr std::span s{a}; static_assert( sizeof(int32_t) == 4 ); static_assert( std::size(a) == 5 ); static_assert( sizeof(a) == 20 ); static_assert( s.size() == 5 ); static_assert( s.size_bytes() == 20 ); } ``` ### See also | | | | --- | --- | | [size](size "cpp/container/span/size") | returns the number of elements in the sequence (public member function) | cpp std::span<T,Extent>::operator[] std::span<T,Extent>::operator[] =============================== | | | | | --- | --- | --- | | ``` constexpr reference operator[](size_type idx) const; ``` | | | Returns a reference to the `idx`-th element of the sequence. The behavior is undefined if `idx` is out of range (i.e., if it is greater than or equal to `size()`). ### Parameters | | | | | --- | --- | --- | | idx | - | the index of the element to access | ### Return value A reference to the `idx`-th element of the sequence, i.e., `data()[idx]` ### Exceptions Throws nothing. ### Example ``` #include <iostream> #include <span> #include <utility> void reverse(std::span<int> span) { for (std::size_t i = 0, j = std::size(span); i < j; ++i) { --j; std::swap(span[i], span[j]); } } void print(std::span<const int> const span) { for (int element: span) { std::cout << element << ' '; } std::cout << '\n'; } int main() { int data[]{ 1, 2, 3, 4, 5 }; print(data); reverse(data); print(data); } ``` Output: ``` 1 2 3 4 5 5 4 3 2 1 ``` ### See also | | | | --- | --- | | [data](data "cpp/container/span/data") | returns a pointer to the beginning of the sequence of elements (public member function) | | [size](size "cpp/container/span/size") | returns the number of elements in the sequence (public member function) | cpp std::span<T,Extent>::back std::span<T,Extent>::back ========================= | | | | | --- | --- | --- | | ``` constexpr reference back() const; ``` | | | Returns a reference to the last element in the span. Calling `back` on an empty span results in undefined behavior. ### Parameters (none). ### Return value A reference to the back element. ### Complexity Constant. ### Notes For a span `c`, the expression `c.back()` is equivalent to `*(c.end()-1)`. ### Example ``` #include <span> #include <iostream> void print_forward(std::span<const int> const span) { for (auto n { span.size() }; n != 0; --n ) { std::cout << span.last(n).front() << ' '; } std::cout << '\n'; } void print_backward(std::span<const int> const span) { for (auto n { span.size() }; n != 0; --n) { std::cout << span.first(n).back() << ' '; } std::cout << '\n'; } int main() { constexpr int numbers[] { 0, 1, 2, 3, 4 }; print_forward(numbers); print_backward(numbers); } ``` Output: ``` 0 1 2 3 4 4 3 2 1 0 ``` ### See also | | | | --- | --- | | [front](front "cpp/container/span/front") (C++20) | access the first element (public member function) | cpp std::span<T,Extent>::data std::span<T,Extent>::data ========================= | | | | | --- | --- | --- | | ``` constexpr pointer data() const noexcept; ``` | | | Returns a pointer to the beginning of the sequence. ### Return value A pointer to the beginning of the sequence. ### Example ``` #include <span> #include <iostream> int main() { constexpr char str[] = "ABCDEF\n"; const std::span sp{str}; for (auto n{sp.size()}; n != 2; --n) { std::cout << sp.last(n).data(); } } ``` Output: ``` ABCDEF BCDEF CDEF DEF EF F ``` ### See also | | | | --- | --- | | [(constructor)](span "cpp/container/span/span") | constructs a `span` (public member function) | cpp std::span<T,Extent>::front std::span<T,Extent>::front ========================== | | | | | --- | --- | --- | | ``` constexpr reference front() const; ``` | | | Returns a reference to the first element in the span. Calling `front` on an empty span results in undefined behavior. ### Parameters (none). ### Return value A reference to the first element. ### Complexity Constant. ### Notes For a span `c`, the expression `c.front()` is equivalent to `*c.begin()`. ### Example ``` #include <span> #include <iostream> void print(std::span<const int> const data) { for (auto offset{0U}; offset != data.size(); ++offset) { std::cout << data.subspan(offset).front() << ' '; } std::cout << '\n'; } int main() { constexpr int data[] { 0, 1, 2, 3, 4, 5, 6 }; print({data, 4}); } ``` Output: ``` 0 1 2 3 ``` ### See also | | | | --- | --- | | [back](back "cpp/container/span/back") (C++20) | access the last element (public member function) | cpp std::span<T,Extent>::operator= std::span<T,Extent>::operator= ============================== | | | | | --- | --- | --- | | ``` constexpr span& operator=( const span& other ) noexcept = default; ``` | | | Assigns `other` to `*this`. This defaulted assignment operator performs a shallow copy of the data pointer and the size, i.e., after a call to this function, `data() == other.data()` and `size() == other.size()`. ### Parameters | | | | | --- | --- | --- | | other | - | another span to copy from | ### Return value `*this`. ### Example ``` #include <algorithm> #include <array> #include <cassert> #include <cstddef> #include <iostream> #include <span> #include <string_view> void print(std::string_view info = "", std::span<const int> span = {}, std::size_t extent = 0, std::size_t size_of = 0) { if (span.size() == 0) { std::cout << info << '\n'; return; } std::cout << info << '[' << span.size() << "] {"; std::ranges::for_each(span, [](const int x) { std::cout << ' ' << x; }); std::cout << " }"; if (extent != 0) { std::cout << " extent = "; if (extent == std::dynamic_extent) std::cout << "dynamic"; else std::cout << extent; } if (size_of != 0) { std::cout << ", sizeof = " << size_of; } std::cout << '\n'; } int main() { std::array<int,6> a1; std::array<int,6> a2; a1.fill(3); a2.fill(4); auto s1 = std::span(a1); auto s2 = std::span(a2); print("s1", s1, s1.extent, sizeof(s1)); print("s2", s2, s2.extent, sizeof(s2)); // Check that assignment performs a shallow copy. s1 = s2; (s1.data() == s2.data() && s1.size() == s2.size()) ? print("s1 = s2; is a shallow copy!") : print("s1 = s2; is a deep copy!"); print("s1", s1); print("Fill s1 with 5:"); std::ranges::fill(s1, 5); // s2 is also 'updated' since s1 and s2 point to the same data assert(std::ranges::equal(s1, s2)); print("s1", s1); print("s2", s2); print(); int a3[] {1, 2, 3, 4}; int a4[] {2, 3, 4, 5}; int a5[] {3, 4, 5}; std::span<int, std::dynamic_extent> dynamic_1 {a3}; std::span<int, std::dynamic_extent> dynamic_2 {a4, 3}; std::span<int, 4> static_1 {a3}; std::span<int, 4> static_2 {a4}; std::span<int, 3> static_3 {a5}; print("dynamic_1", dynamic_1, dynamic_1.extent, sizeof(dynamic_1)); print("dynamic_2", dynamic_2, dynamic_2.extent, sizeof(dynamic_2)); print("static_1", static_1, static_1.extent, sizeof(static_1)); print("static_2", static_2, static_2.extent, sizeof(static_2)); print("static_3", static_3, static_3.extent, sizeof(static_3)); dynamic_1 = dynamic_2; // OK dynamic_1 = static_1; // OK // static_1 = dynamic_1; // ERROR: no match for ‘operator=’ static_1 = static_2; // OK: same extents = 4 // static_1 = static_3; // ERROR: different extents: 4 and 3 } ``` Output: ``` s1[6] { 3 3 3 3 3 3 } extent = 6, sizeof = 8 s2[6] { 4 4 4 4 4 4 } extent = 6, sizeof = 8 s1 = s2; is a shallow copy! s1[6] { 4 4 4 4 4 4 } Fill s1 with 5: s1[6] { 5 5 5 5 5 5 } s2[6] { 5 5 5 5 5 5 } dynamic_1[4] { 1 2 3 4 } extent = dynamic, sizeof = 16 dynamic_2[3] { 2 3 4 } extent = dynamic, sizeof = 16 static_1[4] { 1 2 3 4 } extent = 4, sizeof = 8 static_2[4] { 2 3 4 5 } extent = 4, sizeof = 8 static_3[3] { 3 4 5 } extent = 3, sizeof = 8 ``` ### See also | | | | --- | --- | | [(constructor)](span "cpp/container/span/span") | constructs a `span` (public member function) | | [data](data "cpp/container/span/data") | returns a pointer to the beginning of the sequence of elements (public member function) | | [size](size "cpp/container/span/size") | returns the number of elements in the sequence (public member function) | cpp std::span<T,Extent>::rend std::span<T,Extent>::rend ========================= | | | | | --- | --- | --- | | ``` constexpr reverse_iterator rend() const noexcept; ``` | | | Returns a reverse iterator to the element following the last element of the reversed `span`. It corresponds to the element preceding the first element of the non-reversed `span`. This element acts as a placeholder, attempting to access it results in undefined behavior. ![range-rbegin-rend.svg]() ### Parameters (none). ### Return value Reverse iterator to the element following the last element. ### Complexity Constant. ### Example ``` #include <algorithm> #include <iostream> #include <span> #include <string_view> void ascending(const std::span<const std::string_view> data, const std::string_view term) { std::for_each(data.begin(), data.end(), [](const std::string_view x) { std::cout << x << " "; }); std::cout << term; } void descending(const std::span<const std::string_view> data, const std::string_view term) { std::for_each(data.rbegin(), data.rend(), [](const std::string_view x) { std::cout << x << " "; }); std::cout << term; } int main() { constexpr std::string_view bars[]{ "▁","▂","▃","▄","▅","▆","▇","█" }; ascending(bars, " "); descending(bars, "\n"); } ``` Output: ``` ▁ ▂ ▃ ▄ ▅ ▆ ▇ █ █ ▇ ▆ ▅ ▄ ▃ ▂ ▁ ``` ### See also | | | | --- | --- | | [rbegin](rbegin "cpp/container/span/rbegin") (C++20) | returns a reverse iterator to the beginning (public member function) | | [rendcrend](../../iterator/rend "cpp/iterator/rend") (C++14) | returns a reverse end iterator for a container or array (function template) | cpp std::span<T,Extent>::subspan std::span<T,Extent>::subspan ============================ | | | | | --- | --- | --- | | ``` template< std::size_t Offset, std::size_t Count = std::dynamic_extent > constexpr std::span<element_type, E /* see below */> subspan() const; ``` | (1) | | | ``` constexpr std::span<element_type, std::dynamic_extent> subspan( size_type Offset, size_type Count = std::dynamic_extent ) const; ``` | (2) | | Obtains a span that is a view over the `Count` elements of this span starting at offset `Offset`. If `Count` is `std::dynamic_extent`, the number of elements in the subspan is `size() - offset` (i.e., it ends at the end of `*this`.). (1) is ill-formed if. * `Offset` is greater than `Extent`, or * `Count` is not `std::dynamic_extent` and `Count` is greater than `Extent - Offset`. The behavior is undefined if either `Offset` or `Count` is out of range. This happens if. * `Offset` is greater than `size()`, or * `Count` is not `std::dynamic_extent` and `Count` is greater than `size() - Offset`. The extent `E` of the span returned by (1) is determined as follows: * If `Count` is not `std::dynamic_extent`, `Count`; * Otherwise, if `Extent` is not `std::dynamic_extent`, `Extent - Offset`; * Otherwise, `std::dynamic_extent`. ### Return value The requested subspan `r`, such that `r.data() == this->data() + Offset`. If `Count` is `std::dynamic_extent`, `r.size() == this->size() - Offset`; otherwise `r.size() == Count`. ### Example ``` #include <algorithm> #include <cstdio> #include <numeric> #include <ranges> #include <span> void display(std::span<const char> abc) { const auto columns{ 20U }; const auto rows{ abc.size() - columns + 1 }; for (auto offset{ 0U }; offset < rows; ++offset) { std::ranges::for_each( abc.subspan(offset, columns), std::putchar ); std::putchar('\n'); } } int main() { char abc[26]; std::iota(std::begin(abc), std::end(abc), 'A'); display(abc); } ``` Output: ``` ABCDEFGHIJKLMNOPQRST BCDEFGHIJKLMNOPQRSTU CDEFGHIJKLMNOPQRSTUV DEFGHIJKLMNOPQRSTUVW EFGHIJKLMNOPQRSTUVWX FGHIJKLMNOPQRSTUVWXY GHIJKLMNOPQRSTUVWXYZ ``` ### See also | | | | --- | --- | | [first](first "cpp/container/span/first") | obtains a subspan consisting of the first N elements of the sequence (public member function) | | [last](last "cpp/container/span/last") | obtains a subspan consisting of the last N elements of the sequence (public member function) | cpp std::as_bytes, std::as_writable_bytes std::as\_bytes, std::as\_writable\_bytes ======================================== | Defined in header `[<span>](../../header/span "cpp/header/span")` | | | | --- | --- | --- | | ``` template< class T, std::size_t N> std::span<const std::byte, S/* see below */> as_bytes(std::span<T, N> s) noexcept; ``` | (1) | (since C++20) | | ``` template< class T, std::size_t N> std::span<std::byte, S/* see below */> as_writable_bytes(std::span<T, N> s) noexcept; ``` | (2) | (since C++20) | Obtains a view to the object representation of the elements of the span `s`. If `N` is `std::dynamic_extent`, the extent of the returned span `S` is also `std::dynamic_extent`; otherwise it is `sizeof(T) * N`. `as_writable_bytes` only participates in overload resolution if `[std::is\_const\_v](http://en.cppreference.com/w/cpp/types/is_const)<T>` is `false`. ### Return value 1) A span constructed with `{reinterpret\_cast<const [std::byte](http://en.cppreference.com/w/cpp/types/byte)\*>(s.data()), s.size\_bytes()}`. 2) A span constructed with `{reinterpret\_cast<[std::byte](http://en.cppreference.com/w/cpp/types/byte)\*>(s.data()), s.size\_bytes()}`. ### Example ``` #include <cstddef> #include <iomanip> #include <iostream> #include <span> void print(float const x, std::span<const std::byte> const bytes) { std::cout << std::setprecision(6) << std::setw(8) << x << " = { " << std::hex << std::uppercase << std::setfill('0'); for (auto const b : bytes) { std::cout << std::setw(2) << std::to_integer<int>(b) << ' '; } std::cout << std::dec << "}\n"; } int main() { /* mutable */ float data[1] { 3.141592f }; auto const const_bytes = std::as_bytes(std::span{ data }); print(data[0], const_bytes); auto const writable_bytes = std::as_writable_bytes(std::span{ data }); // Change the sign bit that is the MSB (IEEE 754 Floating-Point Standard). writable_bytes[3] |= std::byte{ 0b1000'0000 }; print(data[0], const_bytes); } ``` Possible output: ``` 3.14159 = { D8 0F 49 40 } -3.14159 = { D8 0F 49 C0 } ``` ### See also | | | | --- | --- | | [byte](../../types/byte "cpp/types/byte") (C++17) | the byte type (enum) | cpp std::span<T,Extent>::span std::span<T,Extent>::span ========================= | | | | | --- | --- | --- | | ``` constexpr span() noexcept; ``` | (1) | | | ``` template< class It > explicit(extent != std::dynamic_extent) constexpr span( It first, size_type count ); ``` | (2) | | | ``` template< class It, class End > explicit(extent != std::dynamic_extent) constexpr span( It first, End last ); ``` | (3) | | | ``` template< std::size_t N > constexpr span( element_type (&arr)[N] ) noexcept; ``` | (4) | | | ``` template< class U, std::size_t N > constexpr span( std::array<U, N>& arr ) noexcept; ``` | (5) | | | ``` template< class U, std::size_t N > constexpr span( const std::array<U, N>& arr ) noexcept; ``` | (6) | | | ``` template< class R > explicit(extent != std::dynamic_extent) constexpr span( R&& range ); ``` | (7) | | | ``` template< class U, std::size_t N > explicit(extent != std::dynamic_extent && N == std::dynamic_extent) constexpr span( const std::span<U, N>& source ) noexcept; ``` | (8) | | | ``` constexpr span( const span& other ) noexcept = default; ``` | (9) | | Constructs a `span`. 1) Constructs an empty span whose `data() == nullptr` and `size() == 0`. * This overload participates in overload resolution only if `extent == 0 || extent == [std::dynamic\_extent](http://en.cppreference.com/w/cpp/container/span/dynamic_extent)`. 2) Constructs a span that is a view over the range `[first, first + count)`; the resulting span has `data() == [std::to\_address](http://en.cppreference.com/w/cpp/memory/to_address)(first)` and `size() == count`. * The behavior is undefined if `[first, first + count)` is not a valid range, if `It` does not actually model [`contiguous_iterator`](../../iterator/contiguous_iterator "cpp/iterator/contiguous iterator"), or if `extent != [std::dynamic\_extent](http://en.cppreference.com/w/cpp/container/span/dynamic_extent) && count != extent`. * This overload participates in overload resolution only if + `It` satisfies [`contiguous_iterator`](../../iterator/contiguous_iterator "cpp/iterator/contiguous iterator") + the conversion from `[std::iter\_reference\_t](http://en.cppreference.com/w/cpp/iterator/iter_t)<It>` to `element_type` is at most a qualification conversion. 3) Constructs a span that is a view over the range `[first, last)`; the resulting span has `data() == [std::to\_address](http://en.cppreference.com/w/cpp/memory/to_address)(first)` and `size() == last-first`. * The behavior is undefined if `[first, last)` is not a valid range, if `It` does not actually model [`contiguous_iterator`](../../iterator/contiguous_iterator "cpp/iterator/contiguous iterator"), if `End` does not actually model [`sized_sentinel_for`](../../iterator/sized_sentinel_for "cpp/iterator/sized sentinel for") for `It`, or if `extent != [std::dynamic\_extent](http://en.cppreference.com/w/cpp/container/span/dynamic_extent) && last-first != extent`. * This overload participates in overload resolution only if + `It` satisfies [`contiguous_iterator`](../../iterator/contiguous_iterator "cpp/iterator/contiguous iterator"), + `End` satisfies [`sized_sentinel_for`](../../iterator/sized_sentinel_for "cpp/iterator/sized sentinel for") for `It`, + the conversion from `[std::iter\_reference\_t](http://en.cppreference.com/w/cpp/iterator/iter_t)<It>` to `element_type` is at most a qualification conversion, and + `[std::is\_convertible\_v](http://en.cppreference.com/w/cpp/types/is_convertible)<End, [std::size\_t](http://en.cppreference.com/w/cpp/types/size_t)>` is `false`. 4-6) Constructs a span that is a view over the array `arr`; the resulting span has `size() == N` and `data() == [std::data](http://en.cppreference.com/w/cpp/iterator/data)(arr)`. * These overloads participate in overload resolution only if `extent == [std::dynamic\_extent](http://en.cppreference.com/w/cpp/container/span/dynamic_extent) || N == extent` is `true` and the conversion from `[std::remove\_pointer\_t](http://en.cppreference.com/w/cpp/types/remove_pointer)<decltype(data(arr))>` to `element_type` is at most a qualification conversion. These constructor templates are never used for class template argument deduction. 7) Constructs a span that is a view over the range `range`; the resulting span has `size() == std::[ranges::size](http://en.cppreference.com/w/cpp/ranges/size)(range)` and `data() == std::[ranges::data](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/data)(range)`. * The behavior is undefined if `R` does not actually model [`contiguous_range`](../../ranges/contiguous_range "cpp/ranges/contiguous range") and [`sized_range`](../../ranges/sized_range "cpp/ranges/sized range") or if `R` does not model [`borrowed_range`](../../ranges/borrowed_range "cpp/ranges/borrowed range") while `element_type` is non-const or both `extent != dynamic_extent` and `std::[ranges::size](http://en.cppreference.com/w/cpp/ranges/size)(range) != extent` are `true`. * This overload participates in overload resolution only if + `R` satisfies [`contiguous_range`](../../ranges/contiguous_range "cpp/ranges/contiguous range") and [`sized_range`](../../ranges/sized_range "cpp/ranges/sized range"), + either `R` satisfies [`borrowed_range`](../../ranges/borrowed_range "cpp/ranges/borrowed range") or `[std::is\_const\_v](http://en.cppreference.com/w/cpp/types/is_const)<element_type>` is `true` + `[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<R>` is not a specialization of `std::span`, + `[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<R>` is not a specialization of `[std::array](../array "cpp/container/array")` + `[std::is\_array\_v](http://en.cppreference.com/w/cpp/types/is_array)<[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<R>>` is false, and + the conversion from `std::[ranges::range\_reference\_t](http://en.cppreference.com/w/cpp/ranges/iterator_t)<R>` to `element_type` is at most a qualification conversion. 8) Converting constructor from another span `source`; the resulting span has `size() == source.size()` and `data() == source.data()`. * The behavior is undefined if both `extent != dynamic_extent` and `source.size() != extent` are `true`. * This overload participates in overload resolution only if at least one of `extent == [std::dynamic\_extent](http://en.cppreference.com/w/cpp/container/span/dynamic_extent)`, `N == [std::dynamic\_extent](http://en.cppreference.com/w/cpp/container/span/dynamic_extent)` and `N == extent` is `true` and the conversion from `U` to `element_type` is at most a qualification conversion. 9) Defaulted copy constructor copies the size and data pointer; the resulting span has `size() == other.size()` and `data() == other.data()`. ### Parameters | | | | | --- | --- | --- | | first | - | iterator to the first element of the sequence | | count | - | number of elements in the sequence | | last | - | iterator past the last element of the sequence or another sentinel | | arr | - | array to construct a view for | | range | - | range to construct a view for | | source | - | another span to convert from | | other | - | another span to copy from | ### Exceptions 2) Throws nothing. 3) Throws what and when `last - first` throws. 7) Throws what and when `std::[ranges::size](http://en.cppreference.com/w/cpp/ranges/size)(r)` and `std::[ranges::data](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/data)(r)` throw. ### See also | | | | --- | --- | | [data](data "cpp/container/span/data") | returns a pointer to the beginning of the sequence of elements (public member function) | | [size](size "cpp/container/span/size") | returns the number of elements in the sequence (public member function) | | [operator=](operator= "cpp/container/span/operator=") | assigns a `span` (public member function) | | [sizessize](../../iterator/size "cpp/iterator/size") (C++17)(C++20) | returns the size of a container or array (function template) | | [data](../../iterator/data "cpp/iterator/data") (C++17) | obtains the pointer to the underlying array (function template) |
programming_docs
cpp std::span<T,Extent>::empty std::span<T,Extent>::empty ========================== | | | | | --- | --- | --- | | ``` [[nodiscard]] constexpr bool empty() const noexcept; ``` | | | Checks if the span is empty. ### Parameters (none). ### Return value `true` if the span is empty (i.e., `size() == 0`); `false` otherwise. ### Example ``` #include <span> #include <iostream> #include <iomanip> int main() { std::span<const char> span{ "ABCDEF" }; while (!span.empty()) { std::cout << std::quoted(span.data()) << '\n'; span = span.last(span.size() - 1); } } ``` Output: ``` "ABCDEF" "BCDEF" "CDEF" "DEF" "EF" "F" "" ``` ### See also | | | | --- | --- | | [size](size "cpp/container/span/size") | returns the number of elements in the sequence (public member function) | cpp std::span<T,Extent>::begin std::span<T,Extent>::begin ========================== | | | | | --- | --- | --- | | ``` constexpr iterator begin() const noexcept; ``` | | | Returns an iterator to the first element of the `span`. If the `span` is empty, the returned iterator will be equal to `end()`. ![range-begin-end.svg]() ### Parameters (none). ### Return value Iterator to the first element. ### Complexity Constant. ### Example ``` #include <span> #include <iostream> void print(std::span<const int> sp) { for(auto it = sp.begin(); it != sp.end(); ++it) { std::cout << *it << ' '; } std::cout << '\n'; } void transmogrify(std::span<int> sp) { if (!sp.empty()) { std::cout << *sp.begin() << '\n'; *sp.begin() = 2; } } int main() { int array[] { 1, 3, 4, 5 }; print(array); transmogrify(array); print(array); } ``` Output: ``` 1 3 4 5 1 2 3 4 5 ``` ### See also | | | | --- | --- | | [end](end "cpp/container/span/end") (C++20) | returns an iterator to the end (public member function) | | [begincbegin](../../iterator/begin "cpp/iterator/begin") (C++11)(C++14) | returns an iterator to the beginning of a container or array (function template) | cpp std::dynamic_extent std::dynamic\_extent ==================== | Defined in header `[<span>](../../header/span "cpp/header/span")` | | | | --- | --- | --- | | ``` inline constexpr std::size_t dynamic_extent = std::numeric_limits<std::size_t>::max(); ``` | | (since C++20) | `std::dynamic_extent` is a constant of type `[std::size\_t](../../types/size_t "cpp/types/size t")` that is used to differentiate [`std::span`](../span "cpp/container/span") of static and dynamic extent. ### Note Since `std::size_t` is an unsigned type, an equivalent definition is: ``` inline constexpr std::size_t dynamic_extent = -1; ``` See [integral conversions](../../language/implicit_conversion#Integral_conversions "cpp/language/implicit conversion"). ### Example ``` #include <array> #include <cassert> #include <cstddef> #include <iostream> #include <span> #include <string_view> #include <vector> int main() { auto print = [](std::string_view const name, std::size_t ex) { std::cout << name << ", "; if (ex == std::dynamic_extent) { std::cout << "dynamic extent\n"; } else { std::cout << "static extent = " << ex << '\n'; } }; int a[]{1,2,3,4,5}; std::span span1{a}; print("span1", span1.extent); std::span<int, std::dynamic_extent> span2{a}; print("span2", span2.extent); std::array ar{1,2,3,4,5}; std::span span3{ar}; print("span3", span3.extent); std::vector v{1,2,3,4,5}; std::span span4{v}; print("span4", span4.extent); } ``` Output: ``` span1, static extent = 5 span2, dynamic extent span3, static extent = 5 span4, dynamic extent ``` ### See also | | | | --- | --- | | [span](../span "cpp/container/span") (C++20) | a non-owning view over a contiguous sequence of objects (class template) | cpp std::span<T,Extent>::first std::span<T,Extent>::first ========================== | | | | | --- | --- | --- | | ``` template< std::size_t Count > constexpr std::span<element_type, Count> first() const; ``` | | | | ``` constexpr std::span<element_type, std::dynamic_extent> first( size_type Count ) const; ``` | | | Obtains a span that is a view over the first `Count` elements of this span. The program is ill-formed if `Count > Extent`. The behavior is undefined if `Count > size()`. ### Return value A span `r` that is a view over the first `Count` elements of `*this`, such that `r.data() == this->data() && r.size() == Count`. ### Example ``` #include <iostream> #include <span> #include <string_view> void print(std::string_view const title, /* std::ranges::forward_range */ auto const& container) { std::cout << title << "[" << std::size(container) << "]{ "; for (auto const& elem : container) std::cout << elem << ", "; std::cout << "};\n"; } void run_game(std::span<const int> span) { print("span: ", span); std::span<const int, 5> span_first = span.first<5>(); print("span.first<5>(): ", span_first); std::span<const int, std::dynamic_extent> span_first_dynamic = span.first(4); print("span.first(4): ", span_first_dynamic); } int main() { int a[8]{ 1, 2, 3, 4, 5, 6, 7, 8, }; print("int a", a); run_game(a); } ``` Output: ``` int a[8]{ 1, 2, 3, 4, 5, 6, 7, 8, }; span: [8]{ 1, 2, 3, 4, 5, 6, 7, 8, }; span.first<5>(): [5]{ 1, 2, 3, 4, 5, }; span.first(4): [4]{ 1, 2, 3, 4, }; ``` ### See also | | | | --- | --- | | [last](last "cpp/container/span/last") | obtains a subspan consisting of the last N elements of the sequence (public member function) | | [subspan](subspan "cpp/container/span/subspan") | obtains a subspan (public member function) | cpp std::span<T,Extent>::end std::span<T,Extent>::end ======================== | | | | | --- | --- | --- | | ``` constexpr iterator end() const noexcept; ``` | | | Returns an iterator to the element following the last element of the `span`. This element acts as a placeholder; attempting to access it results in undefined behavior. ![range-begin-end.svg]() ### Parameters (none). ### Return value Iterator to the element following the last element. ### Complexity Constant. ### Example ``` #include <span> #include <iostream> void print(std::span<const int> sp) { for(auto it = sp.begin(); it != sp.end(); ++it) { std::cout << *it << ' '; } std::cout << '\n'; } void transmogrify(std::span<int> sp) { if (!sp.empty()) { std::cout << *sp.begin() << '\n'; *sp.begin() = 2; } } int main() { int array[] { 1, 3, 4, 5 }; print(array); transmogrify(array); print(array); } ``` Output: ``` 1 3 4 5 1 2 3 4 5 ``` ### See also | | | | --- | --- | | [begin](begin "cpp/container/span/begin") (C++20) | returns an iterator to the beginning (public member function) | | [endcend](../../iterator/end "cpp/iterator/end") (C++11)(C++14) | returns an iterator to the end of a container or array (function template) | cpp std::multimap<Key,T,Compare,Allocator>::contains std::multimap<Key,T,Compare,Allocator>::contains ================================================ | | | | | --- | --- | --- | | ``` bool contains( const Key& key ) const; ``` | (1) | (since C++20) | | ``` template< class K > bool contains( const K& x ) const; ``` | (2) | (since C++20) | 1) Checks if there is an element with key equivalent to `key` in the container. 2) Checks if there is an element with key that compares *equivalent* to the value `x`. This overload participates in overload resolution only if the qualified-id `Compare::is_transparent` is valid and denotes a type. It allows calling this function without constructing an instance of `Key`. ### Parameters | | | | | --- | --- | --- | | key | - | key value of the element to search for | | x | - | a value of any type that can be transparently compared with a key | ### Return value `true` if there is such an element, otherwise `false`. ### Complexity Logarithmic in the size of the container. ### Example ``` #include <iostream> #include <map> int main() { std::multimap<int,char> example = {{1,'a'},{2,'b'}}; for(int x: {2, 5}) { if(example.contains(x)) { std::cout << x << ": Found\n"; } else { std::cout << x << ": Not found\n"; } } } ``` Output: ``` 2: Found 5: Not found ``` ### See also | | | | --- | --- | | [find](find "cpp/container/multimap/find") | finds element with specific key (public member function) | | [count](count "cpp/container/multimap/count") | returns the number of elements matching specific key (public member function) | | [equal\_range](equal_range "cpp/container/multimap/equal range") | returns range of elements matching a specific key (public member function) | cpp std::multimap<Key,T,Compare,Allocator>::size std::multimap<Key,T,Compare,Allocator>::size ============================================ | | | | | --- | --- | --- | | ``` size_type size() const; ``` | | (until C++11) | | ``` size_type size() const noexcept; ``` | | (since C++11) | Returns the number of elements in the container, i.e. `[std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(begin(), end())`. ### Parameters (none). ### Return value The number of elements in the container. ### Complexity Constant. ### Example The following code uses `size` to display the number of elements in a `[std::multimap](../multimap "cpp/container/multimap")`: ``` #include <map> #include <iostream> int main() { std::multimap<int,char> nums {{1, 'a'}, {3, 'b'}, {5, 'c'}, {7, 'd'}}; std::cout << "nums contains " << nums.size() << " elements.\n"; } ``` Output: ``` nums contains 4 elements. ``` ### See also | | | | --- | --- | | [empty](empty "cpp/container/multimap/empty") | checks whether the container is empty (public member function) | | [max\_size](max_size "cpp/container/multimap/max size") | returns the maximum possible number of elements (public member function) | | [sizessize](../../iterator/size "cpp/iterator/size") (C++17)(C++20) | returns the size of a container or array (function template) | cpp deduction guides for std::multimap deduction guides for `std::multimap` ==================================== | Defined in header `[<map>](../../header/map "cpp/header/map")` | | | | --- | --- | --- | | ``` template< class InputIt, class Comp = std::less<iter_key_t<InputIt>>, class Alloc = std::allocator<iter_to_alloc_t<InputIt>> > multimap( InputIt, InputIt, Comp = Comp(), Alloc = Alloc() ) -> multimap<iter_key_t<InputIt>, iter_val_t<InputIt>, Comp, Alloc>; ``` | (1) | (since C++17) | | ``` template< class Key, class T, class Comp = std::less<Key>, class Alloc = std::allocator<std::pair<const Key, T>> > multimap( std::initializer_list<std::pair<Key, T>>, Comp = Comp(), Alloc = Alloc() ) -> multimap<Key, T, Comp, Alloc>; ``` | (2) | (since C++17) | | ``` template< class InputIt, class Alloc > multimap( InputIt, InputIt, Alloc ) -> multimap<iter_key_t<InputIt>, iter_val_t<InputIt>, std::less<iter_key_t<InputIt>>, Alloc>; ``` | (3) | (since C++17) | | ``` template< class Key, class T, class Allocator > multimap( std::initializer_list<std::pair<Key, T>>, Allocator ) -> multimap<Key, T, std::less<Key>, Allocator>; ``` | (4) | (since C++17) | where the type aliases `iter_key_t`, `iter_val_t`, `iter_to_alloc_t` are defined as if as follows. | | | | | --- | --- | --- | | ``` template< class InputIt > using iter_key_t = std::remove_const_t< typename std::iterator_traits<InputIt>::value_type::first_type>; ``` | | (exposition only) | | ``` template< class InputIt > using iter_val_t = typename std::iterator_traits<InputIt>::value_type::second_type; ``` | | (exposition only) | | ``` template< class InputIt > using iter_to_alloc_t = std::pair< std::add_const_t<typename std::iterator_traits<InputIt>::value_type::first_type>, typename std::iterator_traits<InputIt>::value_type::second_type > ``` | | (exposition only) | This [deduction guide](../../language/class_template_argument_deduction "cpp/language/class template argument deduction") is provided for multimap to allow deduction from an iterator range (overloads (1,3)) and `[std::initializer\_list](../../utility/initializer_list "cpp/utility/initializer list")` (overloads (2,4)). These overloads participate in overload resolution only if `InputIt` satisfies [LegacyInputIterator](../../named_req/inputiterator "cpp/named req/InputIterator"), `Alloc` satisfies [Allocator](../../named_req/allocator "cpp/named req/Allocator"), and `Comp` does not satisfy [Allocator](../../named_req/allocator "cpp/named req/Allocator"). Note: the extent to which the library determines that a type does not satisfy [LegacyInputIterator](../../named_req/inputiterator "cpp/named req/InputIterator") is unspecified, except that as a minimum integral types do not qualify as input iterators. Likewise, the extent to which it determines that a type does not satisfy [Allocator](../../named_req/allocator "cpp/named req/Allocator") is unspecified, except that as a minimum the member type `Alloc::value_type` must exist and the expression `[std::declval](http://en.cppreference.com/w/cpp/utility/declval)<Alloc&>().allocate([std::size\_t](http://en.cppreference.com/w/cpp/types/size_t){})` must be well-formed when treated as an unevaluated operand. ### Example ``` #include <map> int main() { // std::multimap m1 = {{"foo", 1}, {"bar", 2}}; // Error: braced-init-list has no type; // cannot deduce pair<Key, T> from // {"foo", 1} or {"bar", 2} std::multimap m1 = {std::pair{"foo", 2}, {"bar", 3}}; // guide #2 std::multimap m2(m1.begin(), m1.end()); // guide #1 } ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 3025](https://cplusplus.github.io/LWG/issue3025) | C++17 | initializer-list guides take `[std::pair](http://en.cppreference.com/w/cpp/utility/pair)<const Key, T>` | use `[std::pair](http://en.cppreference.com/w/cpp/utility/pair)<Key, T>` | cpp std::multimap<Key,T,Compare,Allocator>::emplace std::multimap<Key,T,Compare,Allocator>::emplace =============================================== | | | | | --- | --- | --- | | ``` template< class... Args > iterator emplace( Args&&... args ); ``` | | (since C++11) | Inserts a new element into the container constructed in-place with the given `args` . Careful use of `emplace` allows the new element to be constructed while avoiding unnecessary copy or move operations. The constructor of the new element (i.e. `[std::pair](http://en.cppreference.com/w/cpp/utility/pair)<const Key, T>`) is called with exactly the same arguments as supplied to `emplace`, forwarded via `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Args>(args)...`. No iterators or references are invalidated. ### Parameters | | | | | --- | --- | --- | | args | - | arguments to forward to the constructor of the element | ### Return value Returns an iterator to the inserted element. ### Exceptions If an exception is thrown by any operation, this function has no effect (strong exception guarantee). ### Complexity Logarithmic in the size of the container. ### Example ``` #include <iostream> #include <utility> #include <string> #include <map> int main() { std::multimap<std::string, std::string> m; // uses pair's move constructor m.emplace(std::make_pair(std::string("a"), std::string("a"))); // uses pair's converting move constructor m.emplace(std::make_pair("b", "abcd")); // uses pair's template constructor m.emplace("d", "ddd"); // uses pair's piecewise constructor m.emplace(std::piecewise_construct, std::forward_as_tuple("c"), std::forward_as_tuple(10, 'c')); for (const auto &p : m) { std::cout << p.first << " => " << p.second << '\n'; } } ``` Output: ``` a => a b => abcd c => cccccccccc d => ddd ``` ### See also | | | | --- | --- | | [emplace\_hint](emplace_hint "cpp/container/multimap/emplace hint") (C++11) | constructs elements in-place using a hint (public member function) | | [insert](insert "cpp/container/multimap/insert") | inserts elements or nodes (since C++17) (public member function) | cpp std::multimap<Key,T,Compare,Allocator>::~multimap std::multimap<Key,T,Compare,Allocator>::~multimap ================================================= | | | | | --- | --- | --- | | ``` ~multimap(); ``` | | | Destructs the `multimap`. The destructors of the elements are called and the used storage is deallocated. Note, that if the elements are pointers, the pointed-to objects are not destroyed. ### Complexity Linear in the size of the `multimap`. cpp std::multimap<Key,T,Compare,Allocator>::insert std::multimap<Key,T,Compare,Allocator>::insert ============================================== | | | | | --- | --- | --- | | ``` iterator insert( const value_type& value ); ``` | (1) | | | ``` iterator insert( value_type&& value ); ``` | (1) | (since C++17) | | ``` template< class P > iterator insert( P&& value ); ``` | (2) | (since C++11) | | | (3) | | | ``` iterator insert( iterator hint, const value_type& value ); ``` | (until C++11) | | ``` iterator insert( const_iterator hint, const value_type& value ); ``` | (since C++11) | | ``` iterator insert( const_iterator hint, value_type&& value ); ``` | (3) | (since C++17) | | ``` template< class P > iterator insert( const_iterator hint, P&& value ); ``` | (4) | (since C++11) | | ``` template< class InputIt > void insert( InputIt first, InputIt last ); ``` | (5) | | | ``` void insert( std::initializer_list<value_type> ilist ); ``` | (6) | (since C++11) | | ``` iterator insert( node_type&& nh ); ``` | (7) | (since C++17) | | ``` iterator insert( const_iterator hint, node_type&& nh ); ``` | (8) | (since C++17) | Inserts element(s) into the container. 1-2) inserts `value`. If the container has elements with equivalent key, inserts at the upper bound of that range.(since C++11) The overload (2) is equivalent to `emplace([std::forward](http://en.cppreference.com/w/cpp/utility/forward)<P>(value))` and only participates in overload resolution if `[std::is\_constructible](http://en.cppreference.com/w/cpp/types/is_constructible)<value_type, P&&>::value == true`. 3-4) inserts `value` in the position as close as possible, just prior(since C++11), to `hint`. The overload (4) is equivalent to `emplace_hint(hint, [std::forward](http://en.cppreference.com/w/cpp/utility/forward)<P>(value))` and only participates in overload resolution if `[std::is\_constructible](http://en.cppreference.com/w/cpp/types/is_constructible)<value_type, P&&>::value == true`. 5) inserts elements from range `[first, last)`. 6) inserts elements from initializer list `ilist`. 7) If `nh` is an empty [node handle](../node_handle "cpp/container/node handle"), does nothing. Otherwise, inserts the element owned by `nh` into the container and returns an iterator pointing at the inserted element. If a range containing elements with keys equivalent to `nh.key()` exists in the container, the element is inserted at the end of that range. The behavior is undefined if `nh` is not empty and `get_allocator() != nh.get_allocator()`. 8) If `nh` is an empty [node handle](../node_handle "cpp/container/node handle"), does nothing and returns the end iterator. Otherwise, inserts the element owned by `nh` into the container, and 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 `hint`. The behavior is undefined if `nh` is not empty and `get_allocator() != nh.get_allocator()`. No iterators or references are invalidated. If the insertion is successful, pointers and references to the element obtained while it is held in the node handle are invalidated, and pointers and references obtained to that element before it was extracted become valid. (since C++17). ### Parameters | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | | hint | - | | | | | --- | --- | | iterator, used as a suggestion as to where to start the search | (until C++11) | | iterator to the position before which the new element will be inserted | (since C++11) | | | value | - | element value to insert | | first, last | - | range of elements to insert | | ilist | - | initializer list to insert the values from | | nh | - | a compatible [node handle](../node_handle "cpp/container/node handle") | | Type requirements | | -`InputIt` must meet the requirements of [LegacyInputIterator](../../named_req/inputiterator "cpp/named req/InputIterator"). | ### Return value 1-4) Returns an iterator to the inserted element. 5-6) (none) 7,8) End iterator if `nh` was empty, iterator pointing to the inserted element otherwise. ### Exceptions 1-4) If an exception is thrown by any operation, the insertion has no effect. ### Complexity 1-2) Logarithmic in the size of the container, `O(log(size()))`. | | | | --- | --- | | 3-4) Amortized constant if the insertion happens in the position just *after* the hint, logarithmic in the size of the container otherwise. | (until C++11) | | 3-4) Amortized constant if the insertion happens in the position just *before* the hint, logarithmic in the size of the container otherwise. | (since C++11) | 5-6) `O(N*log(size() + N))`, where N is the number of elements to insert. 7) Logarithmic in the size of the container, `O(log(size()))`. 8) Amortized constant if the insertion happens in the position just *before* the hint, logarithmic in the size of the container otherwise. ### Example ``` #include <iostream> #include <string> #include <map> #include <utility> #include <functional> #include <string_view> template<class M> void print(const std::string_view rem, const M& mmap) { std::cout << rem << " "; for (const auto & e : mmap) std::cout << "{" << e.first << "," << e.second << "} "; std::cout << '\n'; } int main() { // list-initialize std::multimap<int, std::string, std::greater<int>> mmap {{2, "foo"}, {2, "bar"}, {3, "baz"}, {1, "abc"}, {5, "def"}}; print("#1", mmap); // insert using value_type mmap.insert(decltype(mmap)::value_type(5, "pqr")); print("#2", mmap); // insert using pair mmap.insert(std::pair{6, "uvw"}); print("#3", mmap); mmap.insert({7, "xyz"}); print("#4", mmap); // insert using initializer_list mmap.insert({{5, "one"}, {5, "two"}}); print("#5", mmap); // insert using a pair of iterators mmap.clear(); const auto il = { std::pair{1, "ä"}, {2, "ё"}, {2, "ö"}, {3, "ü"} }; mmap.insert(il.begin(), il.end()); print("#6", mmap); } ``` Output: ``` #1 {5,def} {3,baz} {2,foo} {2,bar} {1,abc} #2 {5,def} {5,pqr} {3,baz} {2,foo} {2,bar} {1,abc} #3 {6,uvw} {5,def} {5,pqr} {3,baz} {2,foo} {2,bar} {1,abc} #4 {7,xyz} {6,uvw} {5,def} {5,pqr} {3,baz} {2,foo} {2,bar} {1,abc} #5 {7,xyz} {6,uvw} {5,def} {5,pqr} {5,one} {5,two} {3,baz} {2,foo} {2,bar} {1,abc} #6 {3,ü} {2,ё} {2,ö} {1,ä} ``` ### See also | | | | --- | --- | | [emplace](emplace "cpp/container/multimap/emplace") (C++11) | constructs element in-place (public member function) | | [emplace\_hint](emplace_hint "cpp/container/multimap/emplace hint") (C++11) | constructs elements in-place using a hint (public member function) | | [inserter](../../iterator/inserter "cpp/iterator/inserter") | creates a `[std::insert\_iterator](../../iterator/insert_iterator "cpp/iterator/insert iterator")` of type inferred from the argument (function template) |
programming_docs
cpp std::multimap<Key,T,Compare,Allocator>::get_allocator std::multimap<Key,T,Compare,Allocator>::get\_allocator ====================================================== | | | | | --- | --- | --- | | ``` allocator_type get_allocator() const; ``` | | (until C++11) | | ``` allocator_type get_allocator() const noexcept; ``` | | (since C++11) | Returns the allocator associated with the container. ### Parameters (none). ### Return value The associated allocator. ### Complexity Constant. cpp std::multimap<Key,T,Compare,Allocator>::merge std::multimap<Key,T,Compare,Allocator>::merge ============================================= | | | | | --- | --- | --- | | ``` template<class C2> void merge( std::map<Key, T, C2, Allocator>& source ); ``` | (1) | (since C++17) | | ``` template<class C2> void merge( std::map<Key, T, C2, Allocator>&& source ); ``` | (2) | (since C++17) | | ``` template<class C2> void merge( std::multimap<Key, T, C2, Allocator>& source ); ``` | (3) | (since C++17) | | ``` template<class C2> void merge( std::multimap<Key, T, C2, Allocator>&& source ); ``` | (4) | (since C++17) | Attempts to extract ("splice") each element in `source` and insert it into `*this` using the comparison object of `*this`. No elements are copied or moved, only the internal pointers of the container nodes are repointed. All pointers and references to the transferred elements remain valid, but now refer into `*this`, not into `source`. The behavior is undefined if `get_allocator() != source.get_allocator()`. ### Parameters | | | | | --- | --- | --- | | source | - | compatible container to transfer the nodes from | ### Return value (none). ### Exceptions Does not throw unless comparison throws. ### Complexity N\*log(size()+N)), where N is `source.size()`. ### Example ``` #include <map> #include <iostream> #include <string> int main() { std::multimap<int, std::string> ma {{1, "apple"}, {5, "pear"}, {10, "banana"}}; std::multimap<int, std::string> mb {{2, "zorro"}, {4, "batman"}, {5, "X"}, {8, "alpaca"}}; std::multimap<int, std::string> u; u.merge(ma); std::cout << "ma.size(): " << ma.size() << '\n'; u.merge(mb); std::cout << "mb.size(): " << mb.size() << '\n'; for(auto const &kv: u) std::cout << kv.first << ", " << kv.second << '\n'; } ``` Output: ``` ma.size(): 0 mb.size(): 0 1, apple 2, zorro 4, batman 5, pear 5, X 8, alpaca 10, banana ``` ### See also | | | | --- | --- | | [extract](extract "cpp/container/multimap/extract") (C++17) | extracts nodes from the container (public member function) | | [insert](insert "cpp/container/multimap/insert") | inserts elements or nodes (since C++17) (public member function) | cpp std::multimap<Key,T,Compare,Allocator>::extract std::multimap<Key,T,Compare,Allocator>::extract =============================================== | | | | | --- | --- | --- | | ``` node_type extract( const_iterator position ); ``` | (1) | (since C++17) | | ``` node_type extract( const Key& k ); ``` | (2) | (since C++17) | | ``` template< class K > node_type extract( K&& x ); ``` | (3) | (since C++23) | 1) Unlinks the node that contains the element pointed to by `position` and returns a [node handle](../node_handle "cpp/container/node handle") that owns it. 2) If the container has an element with key equivalent to `k`, unlinks the node that contains the first such element from the container and returns a [node handle](../node_handle "cpp/container/node handle") that owns it. Otherwise, returns an empty node handle. 3) Same as (2). This overload participates in overload resolution only if the qualified-id `Compare::is_transparent` is valid and denotes a type, and neither `iterator` nor `const_iterator` is implicitly convertible from `K`. It allows calling this function without constructing an instance of `Key`. In either case, no elements are copied or moved, only the internal pointers of the container nodes are repointed (rebalancing may occur, as with `[erase()](erase "cpp/container/multimap/erase")`). Extracting a node invalidates only the iterators to the extracted element. Pointers and references to the extracted element remain valid, but cannot be used while element is owned by a node handle: they become usable if the element is inserted into a container. ### Parameters | | | | | --- | --- | --- | | position | - | a valid iterator into this container | | k | - | a key to identify the node to be extracted | | x | - | a value of any type that can be transparently compared with a key identifying the node to be extracted | ### Return value A [node handle](../node_handle "cpp/container/node handle") that owns the extracted element, or empty node handle in case the element is not found in (2,3). ### Exceptions 1) Throws nothing. 2,3) Any exceptions thrown by the `Compare` object. ### Complexity 1) amortized constant 2,3) log(`a.size()`) ### Notes extract is the only way to change a key of a map element without reallocation: ``` std::map<int, std::string> m{{1, "mango"}, {2, "papaya"}, {3, "guava"}}; auto nh = m.extract(2); nh.key() = 4; m.insert(std::move(nh)); // m == {{1, "mango"}, {3, "guava"}, {4, "papaya"}} ``` | [Feature-test](../../utility/feature_test "cpp/utility/feature test") macro | Comment | | --- | --- | | [`__cpp_lib_associative_heterogeneous_erasure`](../../feature_test#Library_features "cpp/feature test") | for overload (3) | ### Example ``` #include <algorithm> #include <iostream> #include <string_view> #include <map> void print(std::string_view comment, const auto& data) { std::cout << comment; for (auto [k, v] : data) std::cout << ' ' << k << '(' << v << ')'; std::cout << '\n'; } int main() { std::multimap<int, char> cont{{1, 'a'}, {2, 'b'}, {3, 'c'}}; print("Start:", cont); // Extract node handle and change key auto nh = cont.extract(1); nh.key() = 4; print("After extract and before insert:", cont); // Insert node handle back cont.insert(std::move(nh)); print("End:", cont); } ``` Output: ``` Start: 1(a) 2(b) 3(c) After extract and before insert: 2(b) 3(c) End: 2(b) 3(c) 4(a) ``` ### See also | | | | --- | --- | | [merge](merge "cpp/container/multimap/merge") (C++17) | splices nodes from another container (public member function) | | [insert](insert "cpp/container/multimap/insert") | inserts elements or nodes (since C++17) (public member function) | | [erase](erase "cpp/container/multimap/erase") | erases elements (public member function) | cpp std::multimap<Key,T,Compare,Allocator>::lower_bound std::multimap<Key,T,Compare,Allocator>::lower\_bound ==================================================== | | | | | --- | --- | --- | | ``` iterator lower_bound( const Key& key ); ``` | (1) | | | ``` const_iterator lower_bound( const Key& key ) const; ``` | (2) | | | ``` template< class K > iterator lower_bound( const K& x ); ``` | (3) | (since C++14) | | ``` template< class K > const_iterator lower_bound( const K& x ) const; ``` | (4) | (since C++14) | 1,2) Returns an iterator pointing to the first element that is *not less* than (i.e. greater or equal to) `key`. 3,4) Returns an iterator pointing to the first element that compares *not less* (i.e. greater or equal) to the value `x`. This overload participates in overload resolution only if the qualified-id `Compare::is_transparent` is valid and denotes a type. It allows calling this function without constructing an instance of `Key`. ### Parameters | | | | | --- | --- | --- | | key | - | key value to compare the elements to | | x | - | alternative value that can be compared to `Key` | ### Return value Iterator pointing to the first element that is not *less* than `key`. If no such element is found, a past-the-end iterator (see `[end()](end "cpp/container/multimap/end")`) is returned. ### Complexity Logarithmic in the size of the container. ### Notes | [Feature-test](../../utility/feature_test "cpp/utility/feature test") macro | Comment | | --- | --- | | [`__cpp_lib_generic_associative_lookup`](../../feature_test#Library_features "cpp/feature test") | for overloads (3,4) | ### Example ### See also | | | | --- | --- | | [equal\_range](equal_range "cpp/container/multimap/equal range") | returns range of elements matching a specific key (public member function) | | [upper\_bound](upper_bound "cpp/container/multimap/upper bound") | returns an iterator to the first element *greater* than the given key (public member function) | cpp std::multimap<Key,T,Compare,Allocator>::emplace_hint std::multimap<Key,T,Compare,Allocator>::emplace\_hint ===================================================== | | | | | --- | --- | --- | | ``` template <class... Args> iterator emplace_hint( const_iterator hint, Args&&... args ); ``` | | (since C++11) | Inserts a new element into the container as close as possible to the position just before `hint`. The element is constructed in-place, i.e. no copy or move operations are performed. The constructor of the element type (`value_type`, that is, `[std::pair](http://en.cppreference.com/w/cpp/utility/pair)<const Key, T>`) is called with exactly the same arguments as supplied to the function, forwarded with `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Args>(args)...`. No iterators or references are invalidated. ### Parameters | | | | | --- | --- | --- | | hint | - | iterator to the position before which the new element will be inserted | | args | - | arguments to forward to the constructor of the element | ### Return value Returns an iterator to the newly inserted element. ### Exceptions If an exception is thrown by any operation, this function has no effect (strong exception guarantee). ### Complexity Logarithmic in the size of the container in general, but amortized constant if the new element is inserted just before `hint`. ### See also | | | | --- | --- | | [emplace](emplace "cpp/container/multimap/emplace") (C++11) | constructs element in-place (public member function) | | [insert](insert "cpp/container/multimap/insert") | inserts elements or nodes (since C++17) (public member function) | cpp std::multimap<Key,T,Compare,Allocator>::rbegin, std::multimap<Key,T,Compare,Allocator>::crbegin std::multimap<Key,T,Compare,Allocator>::rbegin, std::multimap<Key,T,Compare,Allocator>::crbegin =============================================================================================== | | | | | --- | --- | --- | | ``` reverse_iterator rbegin(); ``` | | (until C++11) | | ``` reverse_iterator rbegin() noexcept; ``` | | (since C++11) | | ``` const_reverse_iterator rbegin() const; ``` | | (until C++11) | | ``` const_reverse_iterator rbegin() const noexcept; ``` | | (since C++11) | | ``` const_reverse_iterator crbegin() const noexcept; ``` | | (since C++11) | Returns a reverse iterator to the first element of the reversed `multimap`. It corresponds to the last element of the non-reversed `multimap`. If the `multimap` is empty, the returned iterator is equal to `[rend()](rend "cpp/container/multimap/rend")`. ![range-rbegin-rend.svg]() ### Parameters (none). ### Return value Reverse iterator to the first element. ### Complexity Constant. ### Example ``` #include <algorithm> #include <iostream> #include <map> #include <string> int main() { std::multimap<std::string, int> multimap { { "█", 1 }, { "▒", 5 }, { "░", 3 }, { "▓", 7 }, { "▓", 8 }, { "░", 4 }, { "▒", 6 }, { "█", 2 }, }; std::cout << "Print out in reverse order using const reverse iterators:\n"; std::for_each(multimap.crbegin(), multimap.crend(), [](std::pair<const std::string, int> const& e) { std::cout << "{ \"" << e.first << "\", " << e.second << " };\n"; }); multimap.rbegin()->second = 42; // OK: non-const value is modifiable // multimap.crbegin()->second = 42; // Error: can't modify the const value } ``` Possible output: ``` Print out in reverse order using const reverse iterators: { "▓", 8 }; { "▓", 7 }; { "▒", 6 }; { "▒", 5 }; { "░", 4 }; { "░", 3 }; { "█", 2 }; { "█", 1 }; ``` ### See also | | | | --- | --- | | [rendcrend](rend "cpp/container/multimap/rend") (C++11) | returns a reverse iterator to the end (public member function) | | [rbegincrbegin](../../iterator/rbegin "cpp/iterator/rbegin") (C++14) | returns a reverse iterator to the beginning of a container or array (function template) | cpp std::multimap<Key,T,Compare,Allocator>::swap std::multimap<Key,T,Compare,Allocator>::swap ============================================ | | | | | --- | --- | --- | | ``` void swap( multimap& other ); ``` | | (until C++17) | | ``` void swap( multimap& other ) noexcept(/* see below */); ``` | | (since C++17) | Exchanges the contents of the container with those of `other`. Does not invoke any move, copy, or swap operations on individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated. The `Compare` objects must be [Swappable](../../named_req/swappable "cpp/named req/Swappable"), and they are exchanged using unqualified call to non-member `swap`. | | | | --- | --- | | If `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<allocator_type>::propagate\_on\_container\_swap::value` is true, then the allocators are exchanged using an unqualified call to non-member `swap`. Otherwise, they are not swapped (and if `get_allocator() != other.get_allocator()`, the behavior is undefined). | (since C++11) | ### Parameters | | | | | --- | --- | --- | | other | - | container to exchange the contents with | ### Return value (none). ### Exceptions | | | | --- | --- | | Any exception thrown by the swap of the `Compare` objects. | (until C++17) | | [`noexcept`](../../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept([std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<Allocator>::is\_always\_equal::value && [std::is\_nothrow\_swappable](http://en.cppreference.com/w/cpp/types/is_swappable)<Compare>::value)` | (since C++17) | ### Complexity Constant. ### Example ``` #include <iostream> #include <string> #include <utility> #include <map> // print out a std::pair template <class Os, class U, class V> Os& operator<<(Os& os, const std::pair<U, V>& p) { return os << p.first << ":" << p.second; } // print out a container template <class Os, class Co> Os& operator<<(Os& os, const Co& co) { os << "{"; for (auto const& i : co) { os << ' ' << i; } return os << " }\n"; } int main() { std::multimap<std::string, std::string> m1 { {"γ", "gamma"}, {"β", "beta"}, {"α", "alpha"}, {"γ", "gamma"}, }, m2 { {"ε", "epsilon"}, {"δ", "delta"}, {"ε", "epsilon"} }; const auto& ref = *(m1.begin()); const auto iter = std::next(m1.cbegin()); std::cout << "──────── before swap ────────\n" << "m1: " << m1 << "m2: " << m2 << "ref: " << ref << "\niter: " << *iter << '\n'; m1.swap(m2); std::cout << "──────── after swap ────────\n" << "m1: " << m1 << "m2: " << m2 << "ref: " << ref << "\niter: " << *iter << '\n'; // Note that every iterator referring to an element in one container before // the swap refers to the same element in the other container after the swap. // Same is true for references. } ``` Output: ``` ──────── before swap ──────── m1: { α:alpha β:beta γ:gamma γ:gamma } m2: { δ:delta ε:epsilon ε:epsilon } ref: α:alpha iter: β:beta ──────── after swap ──────── m1: { δ:delta ε:epsilon ε:epsilon } m2: { α:alpha β:beta γ:gamma γ:gamma } ref: α:alpha iter: β:beta ``` ### See also | | | | --- | --- | | [std::swap(std::multimap)](swap2 "cpp/container/multimap/swap2") | specializes the `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) | cpp std::multimap<Key,T,Compare,Allocator>::max_size std::multimap<Key,T,Compare,Allocator>::max\_size ================================================= | | | | | --- | --- | --- | | ``` size_type max_size() const; ``` | | (until C++11) | | ``` size_type max_size() const noexcept; ``` | | (since C++11) | Returns the maximum number of elements the container is able to hold due to system or library implementation limitations, i.e. `[std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(begin(), end())` for the largest container. ### Parameters (none). ### Return value Maximum number of elements. ### Complexity Constant. ### Notes This value typically reflects the theoretical limit on the size of the container, at most `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<difference_type>::max()`. At runtime, the size of the container may be limited to a value smaller than `max_size()` by the amount of RAM available. ### Example ``` #include <iostream> #include <locale> #include <map> int main() { std::multimap<char, char> q; std::cout.imbue(std::locale("en_US.UTF-8")); std::cout << "Maximum size of a std::multimap is " << q.max_size() << '\n'; } ``` Possible output: ``` Maximum size of a std::multimap is 576,460,752,303,423,487 ``` ### See also | | | | --- | --- | | [size](size "cpp/container/multimap/size") | returns the number of elements (public member function) | cpp std::multimap<Key,T,Compare,Allocator>::count std::multimap<Key,T,Compare,Allocator>::count ============================================= | | | | | --- | --- | --- | | ``` size_type count( const Key& key ) const; ``` | (1) | | | ``` template< class K > size_type count( const K& x ) const; ``` | (2) | (since C++14) | Returns the number of elements with key that compares *equivalent* to the specified argument. 1) Returns the number of elements with key `key`. 2) Returns the number of elements with key that compares equivalent to the value `x`. This overload participates in overload resolution only if the qualified-id `Compare::is_transparent` is valid and denotes a type. They allow calling this function without constructing an instance of `Key`. ### Parameters | | | | | --- | --- | --- | | key | - | key value of the elements to count | | x | - | alternative value to compare to the keys | ### Return value Number of elements with key that compares *equivalent* to `key` or `x`. ### Complexity Logarithmic in the size of the container plus linear in the number of the elements found. ### Example ### See also | | | | --- | --- | | [find](find "cpp/container/multimap/find") | finds element with specific key (public member function) | | [equal\_range](equal_range "cpp/container/multimap/equal range") | returns range of elements matching a specific key (public member function) | cpp std::multimap<Key,T,Compare,Allocator>::value_comp std::multimap<Key,T,Compare,Allocator>::value\_comp =================================================== | | | | | --- | --- | --- | | ``` std::multimap::value_compare value_comp() const; ``` | | | Returns a function object that compares objects of type std::multimap::value\_type (key-value pairs) by using `[key\_comp](key_comp "cpp/container/multimap/key comp")` to compare the first components of the pairs. ### Parameters (none). ### Return value The value comparison function object. ### Complexity Constant. ### Example ``` #include <cassert> #include <iostream> #include <map> // Example module 97 key compare function struct ModCmp { bool operator()(const int lhs, const int rhs) const { return (lhs % 97) < (rhs % 97); } }; int main() { std::multimap<int, char, ModCmp> cont; cont = { { 1, 'a' }, { 2, 'b' }, { 3, 'c' }, { 4, 'd' }, { 5, 'e' } }; auto comp_func = cont.value_comp(); const std::pair<int, char> val = { 100, 'a' }; for (auto it : cont) { bool before = comp_func(it, val); bool after = comp_func(val, it); std::cout << '(' << it.first << ',' << it.second; if (!before && !after) std::cout << ") equivalent to key " << val.first << '\n'; else if (before) std::cout << ") goes before key " << val.first << '\n'; else if (after) std::cout << ") goes after key " << val.first << '\n'; else assert(0); // Cannot happen } } ``` Output: ``` (1,a) goes before key 100 (2,b) goes before key 100 (3,c) equivalent to key 100 (4,d) goes after key 100 (5,e) goes after key 100 ``` ### See also | | | | --- | --- | | [key\_comp](key_comp "cpp/container/multimap/key comp") | returns the function that compares keys (public member function) |
programming_docs
cpp std::multimap<Key,T,Compare,Allocator>::find std::multimap<Key,T,Compare,Allocator>::find ============================================ | | | | | --- | --- | --- | | ``` iterator find( const Key& key ); ``` | (1) | | | ``` const_iterator find( const Key& key ) const; ``` | (2) | | | ``` template< class K > iterator find( const K& x ); ``` | (3) | (since C++14) | | ``` template< class K > const_iterator find( const K& x ) const; ``` | (4) | (since C++14) | 1,2) Finds an element with key equivalent to `key`. If there are several elements with `key` in the container, any of them may be returned. 3,4) Finds an element with key that compares *equivalent* to the value `x`. This overload participates in overload resolution only if the qualified-id `Compare::is_transparent` is valid and denotes a type. It allows calling this function without constructing an instance of `Key`. ### Parameters | | | | | --- | --- | --- | | key | - | key value of the element to search for | | x | - | a value of any type that can be transparently compared with a key | ### Return value Iterator to an element with key equivalent to `key`. If no such element is found, past-the-end (see `[end()](end "cpp/container/multimap/end")`) iterator is returned. ### Complexity Logarithmic in the size of the container. ### Notes | [Feature-test](../../utility/feature_test "cpp/utility/feature test") macro | Comment | | --- | --- | | [`__cpp_lib_generic_associative_lookup`](../../feature_test#Library_features "cpp/feature test") | for overloads (3,4) | ### Example ``` #include <iostream> #include <map> struct FatKey { int x; int data[1000]; }; struct LightKey { int x; }; // Note: as detailed above, the container must use std::less<> (or other // transparent Comparator) to access these overloads. // This includes standard overloads, such as between std::string and std::string_view. bool operator<(const FatKey& fk, const LightKey& lk) { return fk.x < lk.x; } bool operator<(const LightKey& lk, const FatKey& fk) { return lk.x < fk.x; } bool operator<(const FatKey& fk1, const FatKey& fk2) { return fk1.x < fk2.x; } int main() { // simple comparison demo std::multimap<int,char> example = {{1,'a'},{2,'b'}}; auto search = example.find(2); if (search != example.end()) { std::cout << "Found " << search->first << " " << search->second << '\n'; } else { std::cout << "Not found\n"; } // transparent comparison demo std::multimap<FatKey, char, std::less<>> example2 = { { {1, {} },'a'}, { {2, {} },'b'} }; LightKey lk = {2}; auto search2 = example2.find(lk); if (search2 != example2.end()) { std::cout << "Found " << search2->first.x << " " << search2->second << '\n'; } else { std::cout << "Not found\n"; } // Obtaining const iterators. // Compiler decides whether to return iterator of (non) const type by way of accessing // map; to prevent modification on purpose, one of easiest choices is to access map by // const reference. const auto& example2ref = example2; auto search3 = example2ref.find(lk); if (search3 != example2.end()) { std::cout << "Found " << search3->first.x << ' ' << search3->second << '\n'; // search3->second = 'c'; // error: assignment of member // 'std::pair<const FatKey, char>::second' // in read-only object } } ``` Output: ``` Found 2 b Found 2 b Found 2 b ``` ### See also | | | | --- | --- | | [count](count "cpp/container/multimap/count") | returns the number of elements matching specific key (public member function) | | [equal\_range](equal_range "cpp/container/multimap/equal range") | returns range of elements matching a specific key (public member function) | cpp std::multimap<Key,T,Compare,Allocator>::value_compare std::multimap<Key,T,Compare,Allocator>::value\_compare ====================================================== | | | | | --- | --- | --- | | ``` class value_compare; ``` | | | `std::multimap::value_compare` is a function object that compares objects of type `std::multimap::value_type` (key-value pairs) by comparing of the first components of the pairs. ### Member types | Type | Definition | | --- | --- | | `result_type` (deprecated in C++17)(removed in C++20) | `bool` | | `first_argument_type` (deprecated in C++17)(removed in C++20) | `value_type` | | `second_argument_type` (deprecated in C++17)(removed in C++20) | `value_type` | | | | | --- | --- | | These member types are obtained via publicly inheriting `[std::binary\_function](http://en.cppreference.com/w/cpp/utility/functional/binary_function)<value_type, value_type, bool>`. | (until C++11) | ### Protected member objects | | | | --- | --- | | Compare comp | the stored comparator (protected member object) | ### Member functions | | | | --- | --- | | **(constructor)** | constructs a new `value_compare` object (protected member function) | | **operator()** | compares two values of type `value_type` (public member function) | std::multimap<Key,T,Compare,Alloc>::value\_compare::value\_compare ------------------------------------------------------------------- | | | | | --- | --- | --- | | ``` protected: value_compare( Compare c ); ``` | | | Initializes the internal instance of the comparator to `c`. ### Parameters | | | | | --- | --- | --- | | c | - | comparator to assign | std::multimap<Key,T,Compare,Alloc>::value\_compare::operator() --------------------------------------------------------------- | | | | | --- | --- | --- | | ``` bool operator()( const value_type& lhs, const value_type& rhs ) const; ``` | | | Compares `lhs.first` and `rhs.first` by calling the stored comparator. ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | values to compare | ### Return value `comp(lhs.first, rhs.first)`. ### Exceptions May throw implementation-defined exceptions. cpp std::multimap<Key,T,Compare,Allocator>::equal_range std::multimap<Key,T,Compare,Allocator>::equal\_range ==================================================== | | | | | --- | --- | --- | | ``` std::pair<iterator,iterator> equal_range( const Key& key ); ``` | (1) | | | ``` std::pair<const_iterator,const_iterator> equal_range( const Key& key ) const; ``` | (2) | | | ``` template< class K > std::pair<iterator,iterator> equal_range( const K& x ); ``` | (3) | (since C++14) | | ``` template< class K > std::pair<const_iterator,const_iterator> equal_range( const K& x ) const; ``` | (4) | (since C++14) | Returns a range containing all elements with the given key in the container. The range is defined by two iterators, one pointing to the first element that is *not less* than `key` and another pointing to the first element *greater* than `key`. Alternatively, the first iterator may be obtained with `[lower\_bound()](lower_bound "cpp/container/multimap/lower bound")`, and the second with `[upper\_bound()](upper_bound "cpp/container/multimap/upper bound")`. 1,2) Compares the keys to `key`. 3,4) Compares the keys to the value `x`. This overload participates in overload resolution only if the qualified-id `Compare::is_transparent` is valid and denotes a type. It allows calling this function without constructing an instance of `Key`. ### Parameters | | | | | --- | --- | --- | | key | - | key value to compare the elements to | | x | - | alternative value that can be compared to `Key` | ### Return value `[std::pair](../../utility/pair "cpp/utility/pair")` containing a pair of iterators defining the wanted range: the first pointing to the first element that is not *less* than `key` and the second pointing to the first element *greater* than `key`. If there are no elements *not less* than `key`, past-the-end (see `[end()](end "cpp/container/multimap/end")`) iterator is returned as the first element. Similarly if there are no elements *greater* than `key`, past-the-end iterator is returned as the second element. | | | | --- | --- | | Since [`emplace`](emplace "cpp/container/multimap/emplace") and unhinted [`insert`](insert "cpp/container/multimap/insert") always insert at the upper bound, the order of equivalent elements in the equal range is the order of insertion unless hinted [`insert`](insert "cpp/container/multimap/insert") or [`emplace_hint`](emplace_hint "cpp/container/multimap/emplace hint") was used to insert an element at a different position. | (since C++11) | ### Complexity Logarithmic in the size of the container. ### Notes | [Feature-test](../../utility/feature_test "cpp/utility/feature test") macro | Comment | | --- | --- | | [`__cpp_lib_generic_associative_lookup`](../../feature_test#Library_features "cpp/feature test") | for overloads (3,4) | ### Example ``` #include <iostream> #include <map> int main() { std::multimap<int, char> dict { {1, 'A'}, {2, 'B'}, {2, 'C'}, {2, 'D'}, {4, 'E'}, {3, 'F'} }; auto range = dict.equal_range(2); for (auto i = range.first; i != range.second; ++i) { std::cout << i->first << ": " << i->second << '\n'; } } ``` Output: ``` 2: B 2: C 2: D ``` ### See also | | | | --- | --- | | [find](find "cpp/container/multimap/find") | finds element with specific key (public member function) | | [contains](contains "cpp/container/multimap/contains") (C++20) | checks if the container contains element with specific key (public member function) | | [count](count "cpp/container/multimap/count") | returns the number of elements matching specific key (public member function) | | [upper\_bound](upper_bound "cpp/container/multimap/upper bound") | returns an iterator to the first element *greater* than the given key (public member function) | | [lower\_bound](lower_bound "cpp/container/multimap/lower bound") | returns an iterator to the first element *not less* than the given key (public member function) | | [equal\_range](../../algorithm/equal_range "cpp/algorithm/equal range") | returns range of elements matching a specific key (function template) | cpp std::multimap<Key,T,Compare,Allocator>::key_comp std::multimap<Key,T,Compare,Allocator>::key\_comp ================================================= | | | | | --- | --- | --- | | ``` key_compare key_comp() const; ``` | | | Returns the function object that compares the keys, which is a copy of this container's [constructor](multimap "cpp/container/multimap/multimap") argument `comp`. ### Parameters (none). ### Return value The key comparison function object. ### Complexity Constant. ### Example ``` #include <cassert> #include <iostream> #include <map> // Example module 97 key compare function struct ModCmp { bool operator()(const int lhs, const int rhs) const { return (lhs % 97) < (rhs % 97); } }; int main() { std::multimap<int, char, ModCmp> cont; cont = { { 1, 'a' }, { 2, 'b' }, { 3, 'c' }, { 4, 'd' }, { 5, 'e' } }; auto comp_func = cont.key_comp(); for (auto it : cont) { bool before = comp_func(it.first, 100); bool after = comp_func(100, it.first); std::cout << '(' << it.first << ',' << it.second; if (!before && !after) std::cout << ") equivalent to key 100\n"; else if (before) std::cout << ") goes before key 100\n"; else if (after) std::cout << ") goes after key 100\n"; else assert(0); // Cannot happen } } ``` Output: ``` (1,a) goes before key 100 (2,b) goes before key 100 (3,c) equivalent to key 100 (4,d) goes after key 100 (5,e) goes after key 100 ``` ### See also | | | | --- | --- | | [value\_comp](value_comp "cpp/container/multimap/value comp") | returns the function that compares keys in objects of type value\_type (public member function) | cpp std::multimap<Key,T,Compare,Allocator>::erase std::multimap<Key,T,Compare,Allocator>::erase ============================================= | | | | | --- | --- | --- | | | (1) | | | ``` void erase( iterator pos ); ``` | (until C++11) | | ``` iterator erase( iterator pos ); ``` | (since C++11) | | ``` iterator erase( const_iterator pos ); ``` | (since C++11) | | | (2) | | | ``` void erase( iterator first, iterator last ); ``` | (until C++11) | | ``` iterator erase( const_iterator first, const_iterator last ); ``` | (since C++11) | | ``` size_type erase( const Key& key ); ``` | (3) | | | ``` template< class K > size_type erase( K&& x ); ``` | (4) | (since C++23) | Removes specified elements from the container. 1) Removes the element at `pos`. 2) Removes the elements in the range `[first; last)`, which must be a valid range in `*this`. 3) Removes all elements with the key equivalent to `key`. 4) Removes all elements with key that compares *equivalent* to the value `x`. This overload participates in overload resolution only if the qualified-id `Compare::is_transparent` is valid and denotes a type, and neither `iterator` nor `const_iterator` is implicitly convertible from `K`. It allows calling this function without constructing an instance of `Key`. References and iterators to the erased elements are invalidated. Other references and iterators are not affected. The iterator `pos` must be valid and dereferenceable. Thus the `[end()](end "cpp/container/multimap/end")` iterator (which is valid, but is not dereferenceable) cannot be used as a value for `pos`. ### Parameters | | | | | --- | --- | --- | | pos | - | iterator to the element to remove | | first, last | - | range of elements to remove | | key | - | key value of the elements to remove | | x | - | a value of any type that can be transparently compared with a key denoting the elements to remove | ### Return value 1-2) (none) (until C++11)Iterator following the last removed element. (since C++11) 3,4) Number of elements removed. ### Exceptions 1,2) Throws nothing. 3,4) Any exceptions thrown by the `Compare` object. ### Complexity Given an instance `c` of `multimap`: 1) Amortized constant 2) `log(c.size()) + [std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(first, last)` 3) `log(c.size()) + c.count(key)` 4) `log(c.size()) + c.count(x)` ### Notes | [Feature-test](../../utility/feature_test "cpp/utility/feature test") macro | Comment | | --- | --- | | [`__cpp_lib_associative_heterogeneous_erasure`](../../feature_test#Library_features "cpp/feature test") | for overload (4) | ### Example ``` #include <map> #include <iostream> int main() { std::multimap<int, std::string> c = { {1, "one" }, {2, "two" }, {3, "three"}, {4, "four"}, {5, "five"}, {6, "six" } }; // erase all odd numbers from c for(auto it = c.begin(); it != c.end(); ) { if(it->first % 2 != 0) it = c.erase(it); else ++it; } for(auto& p : c) { std::cout << p.second << ' '; } } ``` Output: ``` two four six ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 2059](https://cplusplus.github.io/LWG/issue2059) | C++11 | overload for one `const_iterator` introduced new ambiguity | overload for `iterator` added | ### See also | | | | --- | --- | | [clear](clear "cpp/container/multimap/clear") | clears the contents (public member function) | cpp std::swap(std::multimap) std::swap(std::multimap) ======================== | Defined in header `[<map>](../../header/map "cpp/header/map")` | | | | --- | --- | --- | | ``` template< class Key, class T, class Compare, class Alloc > void swap( std::multimap<Key,T,Compare,Alloc>& lhs, std::multimap<Key,T,Compare,Alloc>& rhs ); ``` | | (until C++17) | | ``` template< class Key, class T, class Compare, class Alloc > void swap( std::multimap<Key,T,Compare,Alloc>& lhs, std::multimap<Key,T,Compare,Alloc>& rhs ) noexcept(/* see below */); ``` | | (since C++17) | Specializes the `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` algorithm for `[std::multimap](http://en.cppreference.com/w/cpp/container/multimap)`. Swaps the contents of `lhs` and `rhs`. Calls `lhs.swap(rhs)`. ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | containers whose contents to swap | ### Return value (none). ### Complexity Constant. ### Exceptions | | | | --- | --- | | [`noexcept`](../../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept(noexcept(lhs.swap(rhs)))` | (since C++17) | ### Notes Although the overloads of `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` for container adaptors are introduced in C++11, container adaptors can already be swapped by `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` in C++98. Such calls to `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` usually have linear time complexity, but better complexity may be provided. ### Example ``` #include <algorithm> #include <iostream> #include <map> int main() { std::multimap<int, char> alice{{1, 'a'}, {2, 'b'}, {3, 'c'}}; std::multimap<int, char> bob{{7, 'Z'}, {8, 'Y'}, {9, 'X'}, {10, 'W'}}; auto print = [](std::pair<const int, char>& n) { std::cout << " " << n.first << '(' << n.second << ')'; }; // Print state before swap std::cout << "alice:"; std::for_each(alice.begin(), alice.end(), print); std::cout << "\n" "bob :"; std::for_each(bob.begin(), bob.end(), print); std::cout << '\n'; std::cout << "-- SWAP\n"; std::swap(alice, bob); // Print state after swap std::cout << "alice:"; std::for_each(alice.begin(), alice.end(), print); std::cout << "\n" "bob :"; std::for_each(bob.begin(), bob.end(), print); std::cout << '\n'; } ``` Output: ``` alice: 1(a) 2(b) 3(c) bob : 7(Z) 8(Y) 9(X) 10(W) -- SWAP alice: 7(Z) 8(Y) 9(X) 10(W) bob : 1(a) 2(b) 3(c) ``` ### See also | | | | --- | --- | | [swap](swap "cpp/container/multimap/swap") | swaps the contents (public member function) | cpp std::multimap<Key,T,Compare,Allocator>::operator= std::multimap<Key,T,Compare,Allocator>::operator= ================================================= | | | | | --- | --- | --- | | ``` multimap& operator=( const multimap& other ); ``` | (1) | | | | (2) | | | ``` multimap& operator=( multimap&& other ); ``` | (since C++11) (until C++17) | | ``` multimap& operator=( multimap&& other ) noexcept(/* see below */); ``` | (since C++17) | | ``` multimap& operator=( std::initializer_list<value_type> ilist ); ``` | (3) | (since C++11) | Replaces the contents of the container. 1) Copy assignment operator. Replaces the contents with a copy of the contents of `other`. | | | | --- | --- | | If `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<allocator_type>::propagate\_on\_container\_copy\_assignment::value` is `true`, the allocator of `*this` is replaced by a copy of that of `other`. If the allocator of `*this` after assignment would compare unequal to its old value, the old allocator is used to deallocate the memory, then the new allocator is used to allocate it before copying the elements. Otherwise, the memory owned by `*this` may be reused when possible. In any case, the elements originally belonging to `*this` may be either destroyed or replaced by element-wise copy-assignment. | (since C++11) | 2) Move assignment operator. Replaces the contents with those of `other` using move semantics (i.e. the data in `other` is moved from `other` into this container). `other` is in a valid but unspecified state afterwards. If `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<allocator_type>::propagate\_on\_container\_move\_assignment::value` is `true`, the allocator of `*this` is replaced by a copy of that of `other`. If it is `false` and the allocators of `*this` and `other` do not compare equal, `*this` cannot take ownership of the memory owned by `other` and must move-assign each element individually, allocating additional memory using its own allocator as needed. In any case, all elements originally belonging to `*this` are either destroyed or replaced by element-wise move-assignment. 3) Replaces the contents with those identified by initializer list `ilist`. ### Parameters | | | | | --- | --- | --- | | other | - | another container to use as data source | | ilist | - | initializer list to use as data source | ### Return value `*this`. ### Complexity 1) Linear in the size of `*this` and `other`. 2) Linear in the size of `*this` unless the allocators do not compare equal and do not propagate, in which case linear in the size of `*this` and `other`. 3) O(NlogN) in general, where N is `size() + ilist.size()`. Linear if `ilist` is sorted with respect to `[value\_comp()](value_comp "cpp/container/multimap/value comp")`. ### Exceptions | | | | --- | --- | | May throw implementation-defined exceptions. | (until C++17) | | 1,3) May throw implementation-defined exceptions. 2) [`noexcept`](../../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept([std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<Allocator>::is\_always\_equal::value && [std::is\_nothrow\_move\_assignable](http://en.cppreference.com/w/cpp/types/is_move_assignable)<Compare>::value)` | (since C++17) | ### Notes After container move assignment (overload (2)), unless element-wise move assignment is forced by incompatible allocators, references, pointers, and iterators (other than the end iterator) to `other` remain valid, but refer to elements that are now in `*this`. The current standard makes this guarantee via the blanket statement in [[container.requirements.general]/12](https://eel.is/c++draft/container.requirements.general#12), and a more direct guarantee is under consideration via [LWG 2321](https://cplusplus.github.io/LWG/issue2321). ### Example The following code uses `operator=` to assign one `[std::multimap](../multimap "cpp/container/multimap")` to another: ``` #include <map> #include <iterator> #include <iostream> #include <utility> #include <initializer_list> void print(auto const comment, auto const& container) { auto size = std::size(container); std::cout << comment << "{ "; for (auto const& [key, value]: container) std::cout << '{' << key << ',' << value << (--size ? "}, " : "} "); std::cout << "}\n"; } int main() { std::multimap<int, int> x { {1,1}, {2,2}, {3,3} }, y, z; const auto w = { std::pair<const int, int>{4,4}, {5,5}, {6,6}, {7,7} }; std::cout << "Initially:\n"; print("x = ", x); print("y = ", y); print("z = ", z); std::cout << "Copy assignment copies data from x to y:\n"; y = x; print("x = ", x); print("y = ", y); std::cout << "Move assignment moves data from x to z, modifying both x and z:\n"; z = std::move(x); print("x = ", x); print("z = ", z); std::cout << "Assignment of initializer_list w to z:\n"; z = w; print("w = ", w); print("z = ", z); } ``` Output: ``` Initially: x = { {1,1}, {2,2}, {3,3} } y = { } z = { } Copy assignment copies data from x to y: x = { {1,1}, {2,2}, {3,3} } y = { {1,1}, {2,2}, {3,3} } Move assignment moves data from x to z, modifying both x and z: x = { } z = { {1,1}, {2,2}, {3,3} } Assignment of initializer_list w to z: w = { {4,4}, {5,5}, {6,6}, {7,7} } z = { {4,4}, {5,5}, {6,6}, {7,7} } ``` ### See also | | | | --- | --- | | [(constructor)](multimap "cpp/container/multimap/multimap") | constructs the `multimap` (public member function) |
programming_docs
cpp std::multimap<Key,T,Compare,Allocator>::rend, std::multimap<Key,T,Compare,Allocator>::crend std::multimap<Key,T,Compare,Allocator>::rend, std::multimap<Key,T,Compare,Allocator>::crend =========================================================================================== | | | | | --- | --- | --- | | ``` reverse_iterator rend(); ``` | | (until C++11) | | ``` reverse_iterator rend() noexcept; ``` | | (since C++11) | | ``` const_reverse_iterator rend() const; ``` | | (until C++11) | | ``` const_reverse_iterator rend() const noexcept; ``` | | (since C++11) | | ``` const_reverse_iterator crend() const noexcept; ``` | | (since C++11) | Returns a reverse iterator to the element following the last element of the reversed `multimap`. It corresponds to the element preceding the first element of the non-reversed `multimap`. This element acts as a placeholder, attempting to access it results in undefined behavior. ![range-rbegin-rend.svg]() ### Parameters (none). ### Return value Reverse iterator to the element following the last element. ### Complexity Constant. ### Example ``` #include <iostream> #include <iomanip> #include <chrono> #include <map> #include <string_view> using namespace std::chrono; // until C++20 chrono operator<< ready std::ostream& operator<<(std::ostream& os, const year_month_day& ymd) { return os << std::setfill('0') << static_cast<int>(ymd.year()) << '/' << std::setw(2) << static_cast<unsigned>(ymd.month()) << '/' << std::setw(2) << static_cast<unsigned>(ymd.day()); } int main() { const std::multimap<year_month_day, int> messages { { February/17/2023 , 10 }, { February/17/2023 , 20 }, { February/16/2022 , 30 }, { October/22/2022 , 40 }, { June/14/2022 , 50 }, { November/23/2021 , 60 }, { December/10/2022 , 55 }, { December/12/2021 , 45 }, { April/1/2020 , 42 }, { April/1/2020 , 24 }, }; std::cout << "Messages received, reverse date order:\n"; for (auto it = messages.crbegin(); it != messages.crend(); ++it) { std::cout << it->first << " : " << it->second << '\n'; } } ``` Possible output: ``` Messages received, reverse date order: 2023/02/17 : 20 2023/02/17 : 10 2022/12/10 : 55 2022/10/22 : 40 2022/06/14 : 50 2022/02/16 : 30 2021/12/12 : 45 2021/11/23 : 60 2020/04/01 : 24 2020/04/01 : 42 ``` ### See also | | | | --- | --- | | [rbegincrbegin](rbegin "cpp/container/multimap/rbegin") (C++11) | returns a reverse iterator to the beginning (public member function) | | [rendcrend](../../iterator/rend "cpp/iterator/rend") (C++14) | returns a reverse end iterator for a container or array (function template) | cpp std::multimap<Key,T,Compare,Allocator>::clear std::multimap<Key,T,Compare,Allocator>::clear ============================================= | | | | | --- | --- | --- | | ``` void clear(); ``` | | (until C++11) | | ``` void clear() noexcept; ``` | | (since C++11) | Erases all elements from the container. After this call, `[size()](size "cpp/container/multimap/size")` returns zero. Invalidates any references, pointers, or iterators referring to contained elements. Any past-the-end iterator remains valid. ### Parameters (none). ### Return value (none). ### Complexity Linear in the size of the container, i.e., the number of elements. ### Example ``` #include <algorithm> #include <iostream> #include <map> int main() { std::multimap<int, char> container{{1, 'x'}, {2, 'y'}, {3, 'z'}}; auto print = [](std::pair<const int, char>& n) { std::cout << " " << n.first << '(' << n.second << ')'; }; std::cout << "Before clear:"; std::for_each(container.begin(), container.end(), print); std::cout << "\nSize=" << container.size() << '\n'; std::cout << "Clear\n"; container.clear(); std::cout << "After clear:"; std::for_each(container.begin(), container.end(), print); std::cout << "\nSize=" << container.size() << '\n'; } ``` Output: ``` Before clear: 1(x) 2(y) 3(z) Size=3 Clear After clear: Size=0 ``` ### See also | | | | --- | --- | | [erase](erase "cpp/container/multimap/erase") | erases elements (public member function) | cpp std::multimap<Key,T,Compare,Allocator>::upper_bound std::multimap<Key,T,Compare,Allocator>::upper\_bound ==================================================== | | | | | --- | --- | --- | | ``` iterator upper_bound( const Key& key ); ``` | (1) | | | ``` const_iterator upper_bound( const Key& key ) const; ``` | (2) | | | ``` template< class K > iterator upper_bound( const K& x ); ``` | (3) | (since C++14) | | ``` template< class K > const_iterator upper_bound( const K& x ) const; ``` | (4) | (since C++14) | 1,2) Returns an iterator pointing to the first element that is *greater* than `key`. 3,4) Returns an iterator pointing to the first element that compares *greater* to the value `x`. This overload participates in overload resolution only if the qualified-id `Compare::is_transparent` is valid and denotes a type. It allows calling this function without constructing an instance of `Key`. ### Parameters | | | | | --- | --- | --- | | key | - | key value to compare the elements to | | x | - | alternative value that can be compared to `Key` | ### Return value Iterator pointing to the first element that is *greater* than `key`. If no such element is found, past-the-end (see `[end()](end "cpp/container/multimap/end")`) iterator is returned. ### Complexity Logarithmic in the size of the container. ### Notes | [Feature-test](../../utility/feature_test "cpp/utility/feature test") macro | Comment | | --- | --- | | [`__cpp_lib_generic_associative_lookup`](../../feature_test#Library_features "cpp/feature test") | for overloads (3,4) | ### Example ### See also | | | | --- | --- | | [equal\_range](equal_range "cpp/container/multimap/equal range") | returns range of elements matching a specific key (public member function) | | [lower\_bound](lower_bound "cpp/container/multimap/lower bound") | returns an iterator to the first element *not less* than the given key (public member function) | cpp std::multimap<Key,T,Compare,Allocator>::empty std::multimap<Key,T,Compare,Allocator>::empty ============================================= | | | | | --- | --- | --- | | ``` bool empty() const; ``` | | (until C++11) | | ``` bool empty() const noexcept; ``` | | (since C++11) (until C++20) | | ``` [[nodiscard]] bool empty() const noexcept; ``` | | (since C++20) | Checks if the container has no elements, i.e. whether `begin() == end()`. ### Parameters (none). ### Return value `true` if the container is empty, `false` otherwise. ### Complexity Constant. ### Example The following code uses `empty` to check if a `[std::multimap](http://en.cppreference.com/w/cpp/container/multimap)<int, int>` contains any elements: ``` #include <map> #include <iostream> #include <utility> int main() { std::multimap<int, int> numbers; std::cout << std::boolalpha; std::cout << "Initially, numbers.empty(): " << numbers.empty() << '\n'; numbers.emplace(42, 13); numbers.insert(std::make_pair(13317, 123)); std::cout << "After adding elements, numbers.empty(): " << numbers.empty() << '\n'; } ``` Output: ``` Initially, numbers.empty(): true After adding elements, numbers.empty(): false ``` ### See also | | | | --- | --- | | [size](size "cpp/container/multimap/size") | returns the number of elements (public member function) | | [empty](../../iterator/empty "cpp/iterator/empty") (C++17) | checks whether the container is empty (function template) | cpp std::multimap<Key,T,Compare,Allocator>::begin, std::multimap<Key,T,Compare,Allocator>::cbegin std::multimap<Key,T,Compare,Allocator>::begin, std::multimap<Key,T,Compare,Allocator>::cbegin ============================================================================================= | | | | | --- | --- | --- | | ``` iterator begin(); ``` | | (until C++11) | | ``` iterator begin() noexcept; ``` | | (since C++11) | | ``` const_iterator begin() const; ``` | | (until C++11) | | ``` const_iterator begin() const noexcept; ``` | | (since C++11) | | ``` const_iterator cbegin() const noexcept; ``` | | (since C++11) | Returns an iterator to the first element of the `multimap`. If the `multimap` is empty, the returned iterator will be equal to `[end()](end "cpp/container/multimap/end")`. ![range-begin-end.svg]() ### Parameters (none). ### Return value Iterator to the first element. ### Complexity Constant. ### Example ``` #include <algorithm> #include <cassert> #include <iostream> #include <map> #include <string> #include <cstddef> int main() { auto show_node = [](const auto& node, char ending = '\n') { std::cout << "{ " << node.first << ", " << node.second << " }" << ending; }; std::multimap<std::size_t, std::string> mmap; assert(mmap.begin() == mmap.end()); // OK assert(mmap.cbegin() == mmap.cend()); // OK mmap.insert({ sizeof(long), "LONG" }); show_node(*(mmap.cbegin())); assert(mmap.begin() != mmap.end()); // OK assert(mmap.cbegin() != mmap.cend()); // OK mmap.begin()->second = "long"; show_node(*(mmap.cbegin())); mmap.insert({ sizeof(int), "int" }); show_node(*mmap.cbegin()); mmap.insert({ sizeof(short), "short" }); show_node(*mmap.cbegin()); mmap.insert({ sizeof(char), "char" }); show_node(*mmap.cbegin()); mmap.insert({{ sizeof(float), "float" }, { sizeof(double), "double" }}); std::cout << "mmap = { "; std::for_each(mmap.cbegin(), mmap.cend(), [&](const auto& n) { show_node(n, ' '); }); std::cout << "};\n"; } ``` Possible output: ``` { 8, LONG } { 8, long } { 4, int } { 2, short } { 1, char } mmap = { { 1, char } { 2, short } { 4, int } { 4, float } { 8, long } { 8, double } }; ``` ### See also | | | | --- | --- | | [end cend](end "cpp/container/multimap/end") (C++11) | returns an iterator to the end (public member function) | | [begincbegin](../../iterator/begin "cpp/iterator/begin") (C++11)(C++14) | returns an iterator to the beginning of a container or array (function template) | cpp std::multimap<Key,T,Compare,Allocator>::multimap std::multimap<Key,T,Compare,Allocator>::multimap ================================================ | | | | | --- | --- | --- | | ``` multimap(); ``` | (1) | | | ``` explicit multimap( const Compare& comp, const Allocator& alloc = Allocator() ); ``` | (2) | | | ``` explicit multimap( const Allocator& alloc ); ``` | (3) | (since C++11) | | ``` template< class InputIt > multimap( InputIt first, InputIt last, const Compare& comp = Compare(), const Allocator& alloc = Allocator() ); ``` | (4) | | | ``` template< class InputIt > multimap( InputIt first, InputIt last, const Allocator& alloc ); ``` | (5) | (since C++14) | | ``` multimap( const multimap& other ); ``` | (6) | | | ``` multimap( const multimap& other, const Allocator& alloc ); ``` | (7) | (since C++11) | | ``` multimap( multimap&& other ); ``` | (8) | (since C++11) | | ``` multimap( multimap&& other, const Allocator& alloc ); ``` | (9) | (since C++11) | | ``` multimap( std::initializer_list<value_type> init, const Compare& comp = Compare(), const Allocator& alloc = Allocator() ); ``` | (10) | (since C++11) | | ``` multimap( std::initializer_list<value_type> init, const Allocator& ); ``` | (11) | (since C++14) | Constructs new container from a variety of data sources and optionally using user supplied allocator `alloc` or comparison function object `comp`. 1-3) Constructs an empty container. 4-5) Constructs the container with the contents of the range `[first, last)`. 6-7) Copy constructor. Constructs the container with the copy of the contents of `other`. | | | | --- | --- | | If `alloc` is not provided, allocator is obtained by calling `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<allocator_type>::select\_on\_container\_copy\_construction( other.get\_allocator())`. | (since C++11) | | The template parameter `Allocator` is only deduced from the first argument while used in [class template argument deduction](../../language/class_template_argument_deduction "cpp/language/class template argument deduction"). | (since C++23) | 8-9) Move constructor. Constructs the container with the contents of `other` using move semantics. If `alloc` is not provided, allocator is obtained by move-construction from the allocator belonging to `other`. | | | | --- | --- | | The template parameter `Allocator` is only deduced from the first argument while used in [class template argument deduction](../../language/class_template_argument_deduction "cpp/language/class template argument deduction"). | (since C++23) | 10-11) Constructs the container with the contents of the initializer list `init`. ### Parameters | | | | | --- | --- | --- | | alloc | - | allocator to use for all memory allocations of this container | | comp | - | comparison function object to use for all comparisons of keys | | first, last | - | the range to copy the elements from | | other | - | another container to be used as source to initialize the elements of the container with | | init | - | initializer list to initialize the elements of the container with | | Type requirements | | -`InputIt` must meet the requirements of [LegacyInputIterator](../../named_req/inputiterator "cpp/named req/InputIterator"). | | -`Compare` must meet the requirements of [Compare](../../named_req/compare "cpp/named req/Compare"). | | -`Allocator` must meet the requirements of [Allocator](../../named_req/allocator "cpp/named req/Allocator"). | ### Complexity 1-3) Constant 4-5) N log(N) where `N = [std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(first, last)` in general, linear in `N` if the range is already sorted by `value_comp()`. 6-7) Linear in size of `other` 8-9) Constant. If `alloc` is given and `alloc != other.get_allocator()`, then linear. 10-11) N log(N) where `N = init.size()` in general, linear in `N` if `init` is already sorted by `value_comp()`. ### Exceptions Calls to `Allocator::allocate` may throw. ### Notes After container move construction (overload (8-9)), references, pointers, and iterators (other than the end iterator) to `other` remain valid, but refer to elements that are now in `*this`. The current standard makes this guarantee via the blanket statement in [[container.requirements.general]/12](https://eel.is/c++draft/container.requirements.general#12), and a more direct guarantee is under consideration via [LWG 2321](https://cplusplus.github.io/LWG/issue2321). Although not formally required until C++23, some implementations has already put the template parameter `Allocator` into [non-deduced contexts](../../language/template_argument_deduction#Non-deduced_contexts "cpp/language/template argument deduction") in earlier modes. ### Example ``` #include <iostream> #include <map> struct Point { double x, y; }; struct PointCmp { bool operator()(const Point& lhs, const Point& rhs) const { return lhs.x < rhs.x; // NB. ignores y on purpose } }; int main() { std::multimap<int, int> m = {{1,1},{2,2},{3,3},{4,4},{5,5},{4,4},{3,3},{2,2},{1,1}}; for(auto& p: m) std::cout << p.first << ' ' << p.second << '\n'; // custom comparison std::multimap<Point, double, PointCmp> mag{ { {5, 12}, 13 }, { {3, 4}, 5 }, { {8, 15}, 17 }, { {3, -3}, -1 }, }; for(auto p : mag) std::cout << "The magnitude of (" << p.first.x << ", " << p.first.y << ") is " << p.second << '\n'; } ``` Output: ``` 1 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4 5 5 The magnitude of (3, 4) is 5 The magnitude of (3, -3) is -1 The magnitude of (5, 12) is 13 The magnitude of (8, 15) is 17 ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 2193](https://cplusplus.github.io/LWG/issue2193) | C++11 | the default constructor is explicit | made non-explicit | ### See also | | | | --- | --- | | [operator=](operator= "cpp/container/multimap/operator=") | assigns values to the container (public member function) | cpp std::multimap<Key,T,Compare,Allocator>::end, std::multimap<Key,T,Compare,Allocator>::cend std::multimap<Key,T,Compare,Allocator>::end, std::multimap<Key,T,Compare,Allocator>::cend ========================================================================================= | | | | | --- | --- | --- | | ``` iterator end(); ``` | | (until C++11) | | ``` iterator end() noexcept; ``` | | (since C++11) | | ``` const_iterator end() const; ``` | | (until C++11) | | ``` const_iterator end() const noexcept; ``` | | (since C++11) | | ``` const_iterator cend() const noexcept; ``` | | (since C++11) | Returns an iterator to the element following the last element of the `multimap`. This element acts as a placeholder; attempting to access it results in undefined behavior. ![range-begin-end.svg]() ### Parameters (none). ### Return value Iterator to the element following the last element. ### Complexity Constant. ### Example ``` #include <algorithm> #include <cassert> #include <iostream> #include <map> #include <string> #include <cstddef> int main() { auto show_node = [](const auto& node, char ending = '\n') { std::cout << "{ " << node.first << ", " << node.second << " }" << ending; }; std::multimap<std::size_t, std::string> mmap; assert(mmap.begin() == mmap.end()); // OK assert(mmap.cbegin() == mmap.cend()); // OK mmap.insert({ sizeof(long), "LONG" }); show_node(*(mmap.cbegin())); assert(mmap.begin() != mmap.end()); // OK assert(mmap.cbegin() != mmap.cend()); // OK mmap.begin()->second = "long"; show_node(*(mmap.cbegin())); mmap.insert({ sizeof(int), "int" }); show_node(*mmap.cbegin()); mmap.insert({ sizeof(short), "short" }); show_node(*mmap.cbegin()); mmap.insert({ sizeof(char), "char" }); show_node(*mmap.cbegin()); mmap.insert({{ sizeof(float), "float" }, { sizeof(double), "double" }}); std::cout << "mmap = { "; std::for_each(mmap.cbegin(), mmap.cend(), [&](const auto& n) { show_node(n, ' '); }); std::cout << "};\n"; } ``` Possible output: ``` { 8, LONG } { 8, long } { 4, int } { 2, short } { 1, char } mmap = { { 1, char } { 2, short } { 4, int } { 4, float } { 8, long } { 8, double } }; ``` ### See also | | | | --- | --- | | [begin cbegin](begin "cpp/container/multimap/begin") (C++11) | returns an iterator to the beginning (public member function) | | [endcend](../../iterator/end "cpp/iterator/end") (C++11)(C++14) | returns an iterator to the end of a container or array (function template) | cpp std::list<T,Allocator>::sort std::list<T,Allocator>::sort ============================ | | | | | --- | --- | --- | | ``` void sort(); ``` | (1) | | | ``` template< class Compare > void sort( Compare comp ); ``` | (2) | | Sorts the elements in ascending order. The order of equal elements is preserved. The first version uses `operator<` to compare the elements, the second version uses the given comparison function `comp`. If an exception is thrown, the order of elements in `*this` is unspecified. ### Parameters | | | | | --- | --- | --- | | comp | - | comparison function object (i.e. an object that satisfies the requirements of [Compare](../../named_req/compare "cpp/named req/Compare")) which returns ​`true` if the first argument is *less* than (i.e. is ordered *before*) the second. The signature of the comparison function should be equivalent to the following: `bool cmp(const Type1 &a, const Type2 &b);` While the signature does not need to have `const &`, the function must not modify the objects passed to it and must be able to accept all values of type (possibly const) `Type1` and `Type2` regardless of [value category](../../language/value_category "cpp/language/value category") (thus, `Type1 &` is not allowed, nor is `Type1` unless for `Type1` a move is equivalent to a copy (since C++11)). The types `Type1` and `Type2` must be such that an object of type `list<T,Allocator>::const_iterator` can be dereferenced and then implicitly converted to both of them. ​ | ### Return value (none). ### Complexity Approximately `N log N` comparisons, where N is the number of elements in the list. ### Notes `[std::sort](../../algorithm/sort "cpp/algorithm/sort")` requires random access iterators and so cannot be used with `list` . This function also differs from `[std::sort](../../algorithm/sort "cpp/algorithm/sort")` in that it does not require the element type of the `list` to be swappable, preserves the values of all iterators, and performs a stable sort. ### Example ``` #include <iostream> #include <functional> #include <list> std::ostream& operator<<(std::ostream& ostr, const std::list<int>& list) { for (auto &i : list) { ostr << " " << i; } return ostr; } int main() { std::list<int> list = { 8,7,5,9,0,1,3,2,6,4 }; std::cout << "before: " << list << "\n"; list.sort(); std::cout << "ascending: " << list << "\n"; list.sort(std::greater<int>()); std::cout << "descending: " << list << "\n"; } ``` Output: ``` before: 8 7 5 9 0 1 3 2 6 4 ascending: 0 1 2 3 4 5 6 7 8 9 descending: 9 8 7 6 5 4 3 2 1 0 ```
programming_docs
cpp std::list<T,Allocator>::size std::list<T,Allocator>::size ============================ | | | | | --- | --- | --- | | ``` size_type size() const; ``` | | (until C++11) | | ``` size_type size() const noexcept; ``` | | (since C++11) | Returns the number of elements in the container, i.e. `[std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(begin(), end())`. ### Parameters (none). ### Return value The number of elements in the container. ### Complexity | | | | --- | --- | | Constant or linear. | (until C++11) | | Constant. | (since C++11) | ### Example The following code uses `size` to display the number of elements in a `[std::list](../list "cpp/container/list")`: ``` #include <list> #include <iostream> int main() { std::list<int> nums {1, 3, 5, 7}; std::cout << "nums contains " << nums.size() << " elements.\n"; } ``` Output: ``` nums contains 4 elements. ``` ### See also | | | | --- | --- | | [empty](empty "cpp/container/list/empty") | checks whether the container is empty (public member function) | | [max\_size](max_size "cpp/container/list/max size") | returns the maximum possible number of elements (public member function) | | [resize](resize "cpp/container/list/resize") | changes the number of elements stored (public member function) | cpp deduction guides for std::list deduction guides for `std::list` ================================ | Defined in header `[<list>](../../header/list "cpp/header/list")` | | | | --- | --- | --- | | ``` template< class InputIt, class Alloc = std::allocator<typename std::iterator_traits<InputIt>::value_type>> list(InputIt, InputIt, Alloc = Alloc()) -> list<typename std::iterator_traits<InputIt>::value_type, Alloc>; ``` | | (since C++17) | This [deduction guide](../../language/class_template_argument_deduction "cpp/language/class template argument deduction") is provided for list to allow deduction from an iterator range. This overload participates in overload resolution only if `InputIt` satisfies [LegacyInputIterator](../../named_req/inputiterator "cpp/named req/InputIterator") and `Alloc` satisfies [Allocator](../../named_req/allocator "cpp/named req/Allocator"). Note: the extent to which the library determines that a type does not satisfy [LegacyInputIterator](../../named_req/inputiterator "cpp/named req/InputIterator") is unspecified, except that as a minimum integral types do not qualify as input iterators. Likewise, the extent to which it determines that a type does not satisfy [Allocator](../../named_req/allocator "cpp/named req/Allocator") is unspecified, except that as a minimum the member type `Alloc::value_type` must exist and the expression `[std::declval](http://en.cppreference.com/w/cpp/utility/declval)<Alloc&>().allocate([std::size\_t](http://en.cppreference.com/w/cpp/types/size_t){})` must be well-formed when treated as an unevaluated operand. ### Example ``` #include <list> #include <vector> int main() { std::vector<int> v = {1, 2, 3, 4}; // uses explicit deduction guide to deduce std::list<int> std::list x(v.begin(), v.end()); // deduces std::list<std::vector<int>::iterator> // first phase of overload resolution for list-initialization selects the candidate // synthesized from the initializer-list constructor; second phase is not performed and // deduction guide has no effect std::list y{v.begin(), v.end()}; } ``` cpp std::list<T,Allocator>::emplace std::list<T,Allocator>::emplace =============================== | | | | | --- | --- | --- | | ``` template< class... Args > iterator emplace( const_iterator pos, Args&&... args ); ``` | | (since C++11) | Inserts a new element into the container directly before `pos`. The element is constructed through `[std::allocator\_traits::construct](../../memory/allocator_traits/construct "cpp/memory/allocator traits/construct")`, which uses placement-new to construct the element in-place at a location provided by the container. The arguments `args...` are forwarded to the constructor as `[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<Args>(args)...`. `args...` may directly or indirectly refer to a value in the container. No iterators or references are invalidated. ### Parameters | | | | | --- | --- | --- | | pos | - | iterator before which the new element will be constructed | | args | - | arguments to forward to the constructor of the element | | Type requirements | | -`T (the container's element type)` must meet the requirements of [EmplaceConstructible](../../named_req/emplaceconstructible "cpp/named req/EmplaceConstructible"). | ### Return value Iterator pointing to the emplaced element. ### Complexity Constant. ### Exceptions If an exception is thrown (e.g. by the constructor), the container is left unmodified, as if this function was never called (strong exception guarantee). ### Example ``` #include <iostream> #include <string> #include <list> struct A { std::string s; A(std::string str) : s(std::move(str)) { std::cout << " constructed\n"; } A(const A& o) : s(o.s) { std::cout << " copy constructed\n"; } A(A&& o) : s(std::move(o.s)) { std::cout << " move constructed\n"; } A& operator=(const A& other) { s = other.s; std::cout << " copy assigned\n"; return *this; } A& operator=(A&& other) { s = std::move(other.s); std::cout << " move assigned\n"; return *this; } }; int main() { std::list<A> container; std::cout << "construct 2 times A:\n"; A two { "two" }; A three { "three" }; std::cout << "emplace:\n"; container.emplace(container.end(), "one"); std::cout << "emplace with A&:\n"; container.emplace(container.end(), two); std::cout << "emplace with A&&:\n"; container.emplace(container.end(), std::move(three)); std::cout << "content:\n"; for (const auto& obj : container) std::cout << ' ' << obj.s; std::cout << '\n'; } ``` Output: ``` construct 2 times A: constructed constructed emplace: constructed emplace with A&: copy constructed emplace with A&&: move constructed content: one two three ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 2164](https://cplusplus.github.io/LWG/issue2164) | C++11 | it was not clear whether the arguments can refer to the container | clarified | ### See also | | | | --- | --- | | [insert](insert "cpp/container/list/insert") | inserts elements (public member function) | | [emplace\_back](emplace_back "cpp/container/list/emplace back") (C++11) | constructs an element in-place at the end (public member function) | cpp std::list<T,Allocator>::insert std::list<T,Allocator>::insert ============================== | | | | | --- | --- | --- | | | (1) | | | ``` iterator insert( iterator pos, const T& value ); ``` | (until C++11) | | ``` iterator insert( const_iterator pos, const T& value ); ``` | (since C++11) | | ``` iterator insert( const_iterator pos, T&& value ); ``` | (2) | (since C++11) | | | (3) | | | ``` void insert( iterator pos, size_type count, const T& value ); ``` | (until C++11) | | ``` iterator insert( const_iterator pos, size_type count, const T& value ); ``` | (since C++11) | | | (4) | | | ``` template< class InputIt > void insert( iterator pos, InputIt first, InputIt last ); ``` | (until C++11) | | ``` template< class InputIt > iterator insert( const_iterator pos, InputIt first, InputIt last ); ``` | (since C++11) | | ``` iterator insert( const_iterator pos, std::initializer_list<T> ilist ); ``` | (5) | (since C++11) | Inserts elements at the specified location in the container. 1-2) inserts `value` before `pos` 3) inserts `count` copies of the `value` before `pos` 4) inserts elements from range `[first, last)` before `pos`. | | | | --- | --- | | This overload has the same effect as overload (3) if `InputIt` is an integral type. | (until C++11) | | This overload participates in overload resolution only if `InputIt` qualifies as [LegacyInputIterator](../../named_req/inputiterator "cpp/named req/InputIterator"), to avoid ambiguity with the overload (3). | (since C++11) | The behavior is undefined if `first` and `last` are iterators into `*this`. 5) inserts elements from initializer list `ilist` before `pos`. No iterators or references are invalidated. ### Parameters | | | | | --- | --- | --- | | pos | - | iterator before which the content will be inserted. `pos` may be the `[end()](end "cpp/container/list/end")` iterator | | value | - | element value to insert | | count | - | number of elements to insert | | first, last | - | the range of elements to insert, can't be iterators into container for which insert is called | | ilist | - | initializer list to insert the values from | | Type requirements | | -`T` must meet the requirements of [CopyInsertable](../../named_req/copyinsertable "cpp/named req/CopyInsertable") in order to use overload (1). | | -`T` must meet the requirements of [MoveInsertable](../../named_req/moveinsertable "cpp/named req/MoveInsertable") in order to use overload (2). | | -`T` must meet the requirements of [CopyAssignable](../../named_req/copyassignable "cpp/named req/CopyAssignable") and [CopyInsertable](../../named_req/copyinsertable "cpp/named req/CopyInsertable") in order to use overload (3). | | -`T` must meet the requirements of [EmplaceConstructible](../../named_req/emplaceconstructible "cpp/named req/EmplaceConstructible") in order to use overload (4,5). | ### Return value 1-2) Iterator pointing to the inserted `value` 3) Iterator pointing to the first element inserted, or `pos` if `count==0`. 4) Iterator pointing to the first element inserted, or `pos` if `first==last`. 5) Iterator pointing to the first element inserted, or `pos` if `ilist` is empty. ### Complexity 1-2) Constant. 3) Linear in `count` 4) Linear in `[std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(first, last)` 5) Linear in `ilist.size()` ### Exceptions If an exception is thrown, there are no effects (strong exception guarantee). ### Example ``` #include <iostream> #include <iterator> #include <list> void print(int id, const std::list<int>& container) { std::cout << id << ". "; for (const int x: container) { std::cout << x << ' '; } std::cout << '\n'; } int main () { std::list<int> c1(3, 100); print(1, c1); auto it = c1.begin(); it = c1.insert(it, 200); print(2, c1); c1.insert(it, 2, 300); print(3, c1); // reset `it` to the begin: it = c1.begin(); std::list<int> c2(2, 400); c1.insert(std::next(it, 2), c2.begin(), c2.end()); print(4, c1); int arr[] = { 501,502,503 }; c1.insert(c1.begin(), arr, arr + std::size(arr)); print(5, c1); c1.insert(c1.end(), { 601,602,603 } ); print(6, c1); } ``` Output: ``` 1. 100 100 100 2. 200 100 100 100 3. 300 300 200 100 100 100 4. 300 300 400 400 200 100 100 100 5. 501 502 503 300 300 400 400 200 100 100 100 6. 501 502 503 300 300 400 400 200 100 100 100 601 602 603 ``` ### See also | | | | --- | --- | | [emplace](emplace "cpp/container/list/emplace") (C++11) | constructs element in-place (public member function) | | [push\_front](push_front "cpp/container/list/push front") | inserts an element to the beginning (public member function) | | [push\_back](push_back "cpp/container/list/push back") | adds an element to the end (public member function) | | [inserter](../../iterator/inserter "cpp/iterator/inserter") | creates a `[std::insert\_iterator](../../iterator/insert_iterator "cpp/iterator/insert iterator")` of type inferred from the argument (function template) | cpp std::list<T,Allocator>::get_allocator std::list<T,Allocator>::get\_allocator ====================================== | | | | | --- | --- | --- | | ``` allocator_type get_allocator() const; ``` | | (until C++11) | | ``` allocator_type get_allocator() const noexcept; ``` | | (since C++11) | Returns the allocator associated with the container. ### Parameters (none). ### Return value The associated allocator. ### Complexity Constant. cpp std::list<T,Allocator>::merge std::list<T,Allocator>::merge ============================= | | | | | --- | --- | --- | | ``` void merge( list& other ); ``` | (1) | | | ``` void merge( list&& other ); ``` | (1) | (since C++11) | | ``` template <class Compare> void merge( list& other, Compare comp ); ``` | (2) | | | ``` template <class Compare> void merge( list&& other, Compare comp ); ``` | (2) | (since C++11) | Merges two sorted lists into one. The lists should be sorted into ascending order. No elements are copied. The container `other` becomes empty after the operation. The function does nothing if `other` refers to the same object as `*this`. If `get_allocator() != other.get_allocator()`, the behavior is undefined. No iterators or references become invalidated, except that the iterators of moved elements now refer into `*this`, not into `other`. The first version uses `operator<` to compare the elements, the second version uses the given comparison function `comp`. This operation is stable: for equivalent elements in the two lists, the elements from `*this` shall always precede the elements from `other`, and the order of equivalent elements of `*this` and `other` does not change. ### Parameters | | | | | --- | --- | --- | | other | - | another container to merge | | comp | - | comparison function object (i.e. an object that satisfies the requirements of [Compare](../../named_req/compare "cpp/named req/Compare")) which returns ​`true` if the first argument is *less* than (i.e. is ordered *before*) the second. The signature of the comparison function should be equivalent to the following: `bool cmp(const Type1 &a, const Type2 &b);` While the signature does not need to have `const &`, the function must not modify the objects passed to it and must be able to accept all values of type (possibly const) `Type1` and `Type2` regardless of [value category](../../language/value_category "cpp/language/value category") (thus, `Type1 &` is not allowed, nor is `Type1` unless for `Type1` a move is equivalent to a copy (since C++11)). The types `Type1` and `Type2` must be such that an object of type `list<T,Allocator>::const_iterator` can be dereferenced and then implicitly converted to both of them. ​ | ### Return value (none). ### Exceptions If an exception is thrown, this function has no effect (strong exception guarantee), except if the exception comes from the comparison function. ### Complexity At most `[std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(begin(), end()) + [std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(other.begin(), other.end()) - 1` comparisons. ### Example ``` #include <iostream> #include <list> std::ostream& operator<<(std::ostream& ostr, const std::list<int>& list) { for (const auto &i : list) { ostr << ' ' << i; } return ostr; } int main() { std::list<int> list1 = { 5,9,1,3,3 }; std::list<int> list2 = { 8,7,2,3,4,4 }; list1.sort(); list2.sort(); std::cout << "list1: " << list1 << '\n'; std::cout << "list2: " << list2 << '\n'; list1.merge(list2); std::cout << "merged: " << list1 << '\n'; } ``` Output: ``` list1: 1 3 3 5 9 list2: 2 3 4 4 7 8 merged: 1 2 3 3 3 4 4 5 7 8 9 ``` ### See also | | | | --- | --- | | [splice](splice "cpp/container/list/splice") | moves elements from another `list` (public member function) | | [merge](../../algorithm/merge "cpp/algorithm/merge") | merges two sorted ranges (function template) | | [inplace\_merge](../../algorithm/inplace_merge "cpp/algorithm/inplace merge") | merges two ordered ranges in-place (function template) | | [ranges::merge](../../algorithm/ranges/merge "cpp/algorithm/ranges/merge") (C++20) | merges two sorted ranges (niebloid) | | [ranges::inplace\_merge](../../algorithm/ranges/inplace_merge "cpp/algorithm/ranges/inplace merge") (C++20) | merges two ordered ranges in-place (niebloid) | cpp std::list<T,Allocator>::rbegin, std::list<T,Allocator>::crbegin std::list<T,Allocator>::rbegin, std::list<T,Allocator>::crbegin =============================================================== | | | | | --- | --- | --- | | ``` reverse_iterator rbegin(); ``` | | (until C++11) | | ``` reverse_iterator rbegin() noexcept; ``` | | (since C++11) | | ``` const_reverse_iterator rbegin() const; ``` | | (until C++11) | | ``` const_reverse_iterator rbegin() const noexcept; ``` | | (since C++11) | | ``` const_reverse_iterator crbegin() const noexcept; ``` | | (since C++11) | Returns a reverse iterator to the first element of the reversed `list`. It corresponds to the last element of the non-reversed `list`. If the `list` is empty, the returned iterator is equal to `[rend()](rend "cpp/container/list/rend")`. ![range-rbegin-rend.svg]() ### Parameters (none). ### Return value Reverse iterator to the first element. ### Complexity Constant. ### Example ``` #include <algorithm> #include <iostream> #include <numeric> #include <string> #include <list> int main() { std::list<int> nums {1, 2, 4, 8, 16}; std::list<std::string> fruits {"orange", "apple", "raspberry"}; std::list<char> empty; // Print list. std::for_each(nums.rbegin(), nums.rend(), [](const int n) { std::cout << n << ' '; }); std::cout << '\n'; // Sums all integers in the list nums (if any), printing only the result. std::cout << "Sum of nums: " << std::accumulate(nums.rbegin(), nums.rend(), 0) << '\n'; // Prints the first fruit in the list fruits, checking if there is any. if (!fruits.empty()) std::cout << "First fruit: " << *fruits.rbegin() << '\n'; if (empty.rbegin() == empty.rend()) std::cout << "list 'empty' is indeed empty.\n"; } ``` Output: ``` 16 8 4 2 1 Sum of nums: 31 First fruit: raspberry list 'empty' is indeed empty. ``` ### See also | | | | --- | --- | | [rendcrend](rend "cpp/container/list/rend") (C++11) | returns a reverse iterator to the end (public member function) | | [rbegincrbegin](../../iterator/rbegin "cpp/iterator/rbegin") (C++14) | returns a reverse iterator to the beginning of a container or array (function template) | cpp std::list<T,Allocator>::list std::list<T,Allocator>::list ============================ | | | | | --- | --- | --- | | ``` list(); ``` | (1) | | | ``` explicit list( const Allocator& alloc ); ``` | (2) | | | | (3) | | | ``` explicit list( size_type count, const T& value = T(), const Allocator& alloc = Allocator()); ``` | (until C++11) | | ``` list( size_type count, const T& value, const Allocator& alloc = Allocator()); ``` | (since C++11) | | | (4) | | | ``` explicit list( size_type count ); ``` | (since C++11) (until C++14) | | ``` explicit list( size_type count, const Allocator& alloc = Allocator() ); ``` | (since C++14) | | ``` template< class InputIt > list( InputIt first, InputIt last, const Allocator& alloc = Allocator() ); ``` | (5) | | | ``` list( const list& other ); ``` | (6) | | | ``` list( const list& other, const Allocator& alloc ); ``` | (7) | (since C++11) | | ``` list( list&& other ); ``` | (8) | (since C++11) | | ``` list( list&& other, const Allocator& alloc ); ``` | (9) | (since C++11) | | ``` list( std::initializer_list<T> init, const Allocator& alloc = Allocator() ); ``` | (10) | (since C++11) | Constructs a new container from a variety of data sources, optionally using a user supplied allocator `alloc`. 1) Default constructor. Constructs an empty container with a default-constructed allocator. 2) Constructs an empty container with the given allocator `alloc`. 3) Constructs the container with `count` copies of elements with value `value`. 4) Constructs the container with `count` [default-inserted](../../named_req/defaultinsertable "cpp/named req/DefaultInsertable") instances of `T`. No copies are made. 5) Constructs the container with the contents of the range `[first, last)`. | | | | --- | --- | | This constructor has the same effect as `list(static_cast<size_type>(first), static_cast<value_type>(last), a)` if `InputIt` is an integral type. | (until C++11) | | This overload participates in overload resolution only if `InputIt` satisfies [LegacyInputIterator](../../named_req/inputiterator "cpp/named req/InputIterator"), to avoid ambiguity with the overload (3). | (since C++11) | 6) Copy constructor. Constructs the container with the copy of the contents of `other`. | | | | --- | --- | | The allocator is obtained as if by calling `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<allocator_type>::select\_on\_container\_copy\_construction( other.get\_allocator())`. | (since C++11) | 7) Constructs the container with the copy of the contents of `other`, using `alloc` as the allocator. | | | | --- | --- | | The template parameter `Allocator` is only deduced from the first argument while used in [class template argument deduction](../../language/class_template_argument_deduction "cpp/language/class template argument deduction"). | (since C++23) | 8) Move constructor. Constructs the container with the contents of `other` using move semantics. Allocator is obtained by move-construction from the allocator belonging to `other`. 9) Allocator-extended move constructor. Using `alloc` as the allocator for the new container, moving the contents from `other`; if `alloc != other.get_allocator()`, this results in an element-wise move. | | | | --- | --- | | The template parameter `Allocator` is only deduced from the first argument while used in [class template argument deduction](../../language/class_template_argument_deduction "cpp/language/class template argument deduction"). | (since C++23) | 10) Constructs the container with the contents of the initializer list `init`. ### Parameters | | | | | --- | --- | --- | | alloc | - | allocator to use for all memory allocations of this container | | count | - | the size of the container | | value | - | the value to initialize elements of the container with | | first, last | - | the range to copy the elements from | | other | - | another container to be used as source to initialize the elements of the container with | | init | - | initializer list to initialize the elements of the container with | ### Complexity 1-2) Constant 3-4) Linear in `count` 5) Linear in distance between `first` and `last` 6-7) Linear in size of `other` 8) Constant. 9) Linear if `alloc != other.get_allocator()`, otherwise constant. 10) Linear in size of `init`. ### Exceptions Calls to `Allocator::allocate` may throw. ### Notes After container move construction (overload (8)), references, pointers, and iterators (other than the end iterator) to `other` remain valid, but refer to elements that are now in `*this`. The current standard makes this guarantee via the blanket statement in [[container.requirements.general]/12](https://eel.is/c++draft/container.requirements.general#12), and a more direct guarantee is under consideration via [LWG 2321](https://cplusplus.github.io/LWG/issue2321). ### Example ``` #include <list> #include <string> #include <iostream> template<typename T> std::ostream& operator<<(std::ostream& s, const std::list<T>& v) { s.put('['); char comma[3] = {'\0', ' ', '\0'}; for (const auto& e : v) { s << comma << e; comma[0] = ','; } return s << ']'; } int main() { // c++11 initializer list syntax: std::list<std::string> words1 {"the", "frogurt", "is", "also", "cursed"}; std::cout << "words1: " << words1 << '\n'; // words2 == words1 std::list<std::string> words2(words1.begin(), words1.end()); std::cout << "words2: " << words2 << '\n'; // words3 == words1 std::list<std::string> words3(words1); std::cout << "words3: " << words3 << '\n'; // words4 is {"Mo", "Mo", "Mo", "Mo", "Mo"} std::list<std::string> words4(5, "Mo"); std::cout << "words4: " << words4 << '\n'; } ``` Output: ``` words1: [the, frogurt, is, also, cursed] words2: [the, frogurt, is, also, cursed] words3: [the, frogurt, is, also, cursed] words4: [Mo, Mo, Mo, Mo, Mo] ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 2193](https://cplusplus.github.io/LWG/issue2193) | C++11 | the default constructor is explicit | made non-explicit | ### See also | | | | --- | --- | | [assign](assign "cpp/container/list/assign") | assigns values to the container (public member function) | | [operator=](operator= "cpp/container/list/operator=") | assigns values to the container (public member function) |
programming_docs