code
stringlengths 2.5k
150k
| kind
stringclasses 1
value |
---|---|
cpp std::list<T,Allocator>::push_front std::list<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.
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 <list>
#include <iostream>
#include <iomanip>
#include <string>
int main()
{
std::list<std::string> letters;
letters.push_front("abc");
std::string s{"def"};
letters.push_front(std::move(s));
std::cout << "std::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::list `letters` holds: "def" "abc"
Moved-from string `s` holds: ""
```
### See also
| | |
| --- | --- |
| [emplace\_front](emplace_front "cpp/container/list/emplace front")
(C++11) | constructs an element in-place at the beginning (public member function) |
| [push\_back](push_back "cpp/container/list/push back") | adds an element to the end (public member function) |
| [pop\_front](pop_front "cpp/container/list/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) |
cpp std::list<T,Allocator>::reverse std::list<T,Allocator>::reverse
===============================
| | | |
| --- | --- | --- |
|
```
void reverse();
```
| | (until C++11) |
|
```
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 <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.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/list/sort") | sorts the elements (public member function) |
cpp std::list<T,Allocator>::swap std::list<T,Allocator>::swap
============================
| | | |
| --- | --- | --- |
|
```
void swap( list& other );
```
| | (until C++17) |
|
```
void swap( 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 <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::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::list)](swap2 "cpp/container/list/swap2") | specializes the `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) |
cpp std::list<T,Allocator>::max_size std::list<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 <list>
int main()
{
std::list<char> q;
std::cout.imbue(std::locale("en_US.UTF-8"));
std::cout << "Maximum size of a std::list is " << q.max_size() << '\n';
}
```
Possible output:
```
Maximum size of a std::list is 768,614,336,404,564,650
```
### See also
| | |
| --- | --- |
| [size](size "cpp/container/list/size") | returns the number of elements (public member function) |
cpp std::list<T,Allocator>::remove, remove_if std::list<T,Allocator>::remove, remove\_if
==========================================
| | | |
| --- | --- | --- |
| | (1) | |
|
```
void remove( const T& value );
```
| (until C++20) |
|
```
size_type remove( const T& value );
```
| (since C++20) |
| | (2) | |
|
```
template< class UnaryPredicate >
void remove_if( UnaryPredicate p );
```
| (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 <list>
#include <iostream>
int main()
{
std::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::list<T,Allocator>::back std::list<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::list](http://en.cppreference.com/w/cpp/container/list)<char>`:
```
#include <list>
#include <iostream>
int main()
{
std::list<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/list/front") | access the first element (public member function) |
cpp std::list<T,Allocator>::assign std::list<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.
### 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::list](http://en.cppreference.com/w/cpp/container/list)<char>`:
```
#include <list>
#include <iostream>
#include <string>
int main()
{
std::list<char> characters;
auto print_list = [&](){
for (char c : characters)
std::cout << c << ' ';
std::cout << '\n';
};
characters.assign(5, 'a');
print_list();
const std::string extra(6, 'b');
characters.assign(extra.begin(), extra.end());
print_list();
characters.assign({'C', '+', '+', '1', '1'});
print_list();
}
```
Output:
```
a a a a a
b b b b b b
C + + 1 1
```
### See also
| | |
| --- | --- |
| [(constructor)](list "cpp/container/list/list") | constructs the `list` (public member function) |
cpp std::list<T,Allocator>::pop_front std::list<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.
References and iterators to the erased element are invalidated.
### Parameters
(none).
### Return value
(none).
### Complexity
Constant.
### Exceptions
Does not throw.
### Example
```
#include <list>
#include <iostream>
int main()
{
std::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
| | |
| --- | --- |
| [pop\_back](pop_back "cpp/container/list/pop back") | removes the last element (public member function) |
| [push\_front](push_front "cpp/container/list/push front") | inserts an element to the beginning (public member function) |
| [front](front "cpp/container/list/front") | access the first element (public member function) |
cpp std::list<T,Allocator>::resize std::list<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 [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 <list>
int main()
{
std::list<int> c = {1, 2, 3};
std::cout << "The 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 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
| | |
| --- | --- |
| [size](size "cpp/container/list/size") | returns the number of elements (public member function) |
| [insert](insert "cpp/container/list/insert") | inserts elements (public member function) |
| [erase](erase "cpp/container/list/erase") | erases elements (public member function) |
cpp std::list<T,Allocator>::erase std::list<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)`. 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/list/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 |
### Return value
Iterator following the last removed element.
If `pos` refers to the last element, then the `[end()](end "cpp/container/list/end")` iterator is returned.
If `last==end()` prior to removal, then the updated `[end()](end "cpp/container/list/end")` iterator is returned.
If `[first, last)` is an empty range, then `last` is returned.
### Exceptions
(none).
### Complexity
1) Constant.
2) Linear in the distance between `first` and `last`. ### Example
```
#include <list>
#include <iostream>
#include <iterator>
void print_container(const std::list<int>& c)
{
for (int i : c) {
std::cout << i << " ";
}
std::cout << '\n';
}
int main( )
{
std::list<int> c{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
print_container(c);
c.erase(c.begin());
print_container(c);
std::list<int>::iterator range_begin = c.begin();
std::list<int>::iterator range_end = c.begin();
std::advance(range_begin,2);
std::advance(range_end,5);
c.erase(range_begin, range_end);
print_container(c);
// Erase all even numbers
for (std::list<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/list/clear") | clears the contents (public member function) |
cpp std::swap(std::list)
std::swap(std::list)
====================
| Defined in header `[<list>](../../header/list "cpp/header/list")` | | |
| --- | --- | --- |
|
```
template< class T, class Alloc >
void swap( std::list<T,Alloc>& lhs,
std::list<T,Alloc>& rhs );
```
| | (until C++17) |
|
```
template< class T, class Alloc >
void swap( std::list<T,Alloc>& lhs,
std::list<T,Alloc>& rhs ) noexcept(/* see below */);
```
| | (since C++17) |
Specializes the `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` algorithm for `[std::list](http://en.cppreference.com/w/cpp/container/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 <list>
int main()
{
std::list<int> alice{1, 2, 3};
std::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/list/swap") | swaps the contents (public member function) |
| programming_docs |
cpp std::list<T,Allocator>::front std::list<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::list](http://en.cppreference.com/w/cpp/container/list)<char>`:
```
#include <list>
#include <iostream>
int main()
{
std::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'.
```
### See also
| | |
| --- | --- |
| [back](back "cpp/container/list/back") | access the last element (public member function) |
cpp std::list<T,Allocator>::operator= std::list<T,Allocator>::operator=
=================================
| | | |
| --- | --- | --- |
|
```
list& operator=( const list& other );
```
| (1) | |
| | (2) | |
|
```
list& operator=( list&& other );
```
| (since C++11) (until C++17) |
|
```
list& operator=( list&& other ) noexcept(/* see below */);
```
| (since C++17) |
|
```
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. | (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::list](../list "cpp/container/list")` to another:
```
#include <list>
#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::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)](list "cpp/container/list/list") | constructs the `list` (public member function) |
| [assign](assign "cpp/container/list/assign") | assigns values to the container (public member function) |
cpp std::list<T,Allocator>::rend, std::list<T,Allocator>::crend std::list<T,Allocator>::rend, std::list<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 `list`. It corresponds to the element preceding the first element of the non-reversed `list`. 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 <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
| | |
| --- | --- |
| [rbegincrbegin](rbegin "cpp/container/list/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::list<T,Allocator>::clear std::list<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/list/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 <list>
int main()
{
std::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 << "\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/list/erase") | erases elements (public member function) |
cpp std::list<T,Allocator>::splice std::list<T,Allocator>::splice
==============================
| | | |
| --- | --- | --- |
|
```
void splice( const_iterator pos, list& other );
```
| (1) | |
|
```
void splice( const_iterator pos, list&& other );
```
| (1) | (since C++11) |
|
```
void splice( const_iterator pos, list& other, const_iterator it );
```
| (2) | |
|
```
void splice( const_iterator pos, list&& other, const_iterator it );
```
| (2) | (since C++11) |
|
```
void splice( const_iterator pos, list& other,
const_iterator first, const_iterator last);
```
| (3) | |
|
```
void splice( const_iterator pos, list&& other,
const_iterator first, const_iterator last );
```
| (3) | (since C++11) |
Transfers elements from one list to another.
No elements are copied or moved, only the internal pointers of the list nodes are re-pointed. The behavior is undefined if: `get_allocator() != other.get_allocator()`. No iterators or references become invalidated, the iterators to moved elements remain valid, but now refer into `*this`, not into `other`.
1) Transfers all elements from `other` into `*this`. The elements are inserted before 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) Transfers the element pointed to by `it` from `other` into `*this`. The element is inserted before the element pointed to by `pos`.
3) Transfers the elements in the range `[first, last)` from `other` into `*this`. The elements are inserted before the element pointed to by `pos`. The behavior is undefined if `pos` is an iterator in the range `[first,last)`. ### Parameters
| | | |
| --- | --- | --- |
| pos | - | element before which the content will be inserted |
| other | - | another container to transfer the content from |
| it | - | the element to transfer from `other` to `*this` |
| first, last | - | the range of elements to transfer from `other` to `*this` |
### Return value
(none).
### Exceptions
Throws nothing.
### Complexity
1-2) Constant.
3) Constant if `other` refers to the same object as `*this`, otherwise linear in `[std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(first, last)`.
### Example
```
#include <iostream>
#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> list1 = { 1, 2, 3, 4, 5 };
std::list<int> list2 = { 10, 20, 30, 40, 50 };
auto it = list1.begin();
std::advance(it, 2);
list1.splice(it, list2);
std::cout << "list1: " << list1 << "\n";
std::cout << "list2: " << list2 << "\n";
list2.splice(list2.begin(), list1, it, list1.end());
std::cout << "list1: " << list1 << "\n";
std::cout << "list2: " << list2 << "\n";
}
```
Output:
```
list1: 1 2 10 20 30 40 50 3 4 5
list2:
list1: 1 2 10 20 30 40 50
list2: 3 4 5
```
### See also
| | |
| --- | --- |
| [merge](merge "cpp/container/list/merge") | merges two sorted lists (public member function) |
| [removeremove\_if](remove "cpp/container/list/remove") | removes elements satisfying specific criteria (public member function) |
cpp std::list<T,Allocator>::emplace_front std::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/list/push front") | inserts an element to the beginning (public member function) |
cpp std::list<T,Allocator>::push_back std::list<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. No iterators or 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 <list>
#include <iostream>
#include <iomanip>
#include <string>
int main()
{
std::list<std::string> letters;
letters.push_back("abc");
std::string s{"def"};
letters.push_back(std::move(s));
std::cout << "std::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::list `letters` holds: "abc" "def"
Moved-from string `s` holds: ""
```
### See also
| | |
| --- | --- |
| [emplace\_back](emplace_back "cpp/container/list/emplace back")
(C++11) | constructs an element in-place at the end (public member function) |
| [push\_front](push_front "cpp/container/list/push front") | inserts an element to the beginning (public member function) |
| [pop\_back](pop_back "cpp/container/list/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) |
cpp std::list<T,Allocator>::empty std::list<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::list](http://en.cppreference.com/w/cpp/container/list)<int>` contains any elements:
```
#include <list>
#include <iostream>
int main()
{
std::list<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/list/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::list<T,Allocator>::begin, std::list<T,Allocator>::cbegin std::list<T,Allocator>::begin, std::list<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 `list`.
If the `list` is empty, the returned iterator will be equal to `[end()](end "cpp/container/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 <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.begin(), nums.end(), [](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.begin(), nums.end(), 0) << '\n';
// Prints the first fruit in the list fruits, checking if there is any.
if (!fruits.empty())
std::cout << "First fruit: " << *fruits.begin() << '\n';
if (empty.begin() == empty.end())
std::cout << "list 'empty' is indeed empty.\n";
}
```
Output:
```
1 2 4 8 16
Sum of nums: 31
First fruit: orange
list 'empty' is indeed empty.
```
### See also
| | |
| --- | --- |
| [end cend](end "cpp/container/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) |
| programming_docs |
cpp std::list<T,Allocator>::unique std::list<T,Allocator>::unique
==============================
| | | |
| --- | --- | --- |
| | (1) | |
|
```
void unique();
```
| (until C++20) |
|
```
size_type unique();
```
| (since C++20) |
| | (2) | |
|
```
template< class BinaryPredicate >
void unique( BinaryPredicate p );
```
| (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 `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 `size() - 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 <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::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::list<T,Allocator>::~list std::list<T,Allocator>::~list
=============================
| | | |
| --- | --- | --- |
|
```
~list();
```
| | |
Destructs the `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 `list`.
cpp std::list<T,Allocator>::emplace_back std::list<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)...`.
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).
### Example
The following code uses `emplace_back` to append an object of type `President` to a `[std::list](http://en.cppreference.com/w/cpp/container/list)`. 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 <list>
#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::list<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::list<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/list/push back") | adds an element to the end (public member function) |
| [emplace](emplace "cpp/container/list/emplace")
(C++11) | constructs element in-place (public member function) |
cpp std::list<T,Allocator>::end, std::list<T,Allocator>::cend std::list<T,Allocator>::end, std::list<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 `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 <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.begin(), nums.end(), [](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.begin(), nums.end(), 0) << '\n';
// Prints the first fruit in the list fruits, checking if there is any.
if (!fruits.empty())
std::cout << "First fruit: " << *fruits.begin() << '\n';
if (empty.begin() == empty.end())
std::cout << "list 'empty' is indeed empty.\n";
}
```
Output:
```
1 2 4 8 16
Sum of nums: 31
First fruit: orange
list 'empty' is indeed empty.
```
### See also
| | |
| --- | --- |
| [begin cbegin](begin "cpp/container/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::list<T,Allocator>::pop_back std::list<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.
References and iterators to the erased element are invalidated.
### Parameters
(none).
### Return value
(none).
### Complexity
Constant.
### Exceptions
Throws nothing.
### Example
```
#include <list>
#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::list<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/list/pop front") | removes the first element (public member function) |
| [push\_back](push_back "cpp/container/list/push back") | adds an element to the end (public member function) |
cpp std::queue<T,Container>::pop std::queue<T,Container>::pop
============================
| | | |
| --- | --- | --- |
|
```
void pop();
```
| | |
Removes an element from the front of the queue. Effectively calls `c.pop_front()`.
### Parameters
(none).
### Return value
(none).
### Complexity
Equal to the complexity of `Container::pop_front`.
### Example
### See also
| | |
| --- | --- |
| [emplace](emplace "cpp/container/queue/emplace")
(C++11) | constructs element in-place at the end (public member function) |
| [push](push "cpp/container/queue/push") | inserts element at the end (public member function) |
| [front](front "cpp/container/queue/front") | access the first element (public member function) |
cpp std::queue<T,Container>::size std::queue<T,Container>::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::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/queue/empty") | checks whether the underlying container is empty (public member function) |
cpp deduction guides for std::queue
deduction guides for `std::queue`
=================================
| Defined in header `[<queue>](../../header/queue "cpp/header/queue")` | | |
| --- | --- | --- |
|
```
template< class Container >
queue( Container )
-> queue<typename Container::value_type, Container>;
```
| (1) | (since C++17) |
|
```
template< class InputIt >
queue( InputIt, InputIt )
-> queue<typename std::iterator_traits<InputIt>::value_type>;
```
| (2) | (since C++23) |
|
```
template< class Container, class Alloc >
queue( Container, Alloc )
-> queue<typename Container::value_type, Container>;
```
| (3) | (since C++17) |
|
```
template< class InputIt, class Alloc >
queue( InputIt, InputIt, Alloc )
-> queue<typename std::iterator_traits<InputIt>::value_type,
std::deque<typename std::iterator_traits<InputIt>::value_type, Alloc>>;
```
| (4) | (since C++23) |
These [deduction guides](../../language/class_template_argument_deduction "cpp/language/class template argument deduction") are provided for `queue` to allow deduction from underlying container type.
1) Deduces underlying container type from the argument.
2) Deduces the element type from the iterator, using `[std::deque](http://en.cppreference.com/w/cpp/container/deque)<typename [std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<InputIt>::value\_type>` as the underlying container type.
3-4) Same as (1-2), except that the allocator is provided. These overloads participate in overload resolution only if.
* `InputIt` (if exists) satisfies [LegacyInputIterator](../../named_req/inputiterator "cpp/named req/InputIterator"),
* `Container` (if exists) does not satisfy [Allocator](../../named_req/allocator "cpp/named req/Allocator"),
* for (3) (until C++23)(4) (since C++23), `Alloc` satisfies [Allocator](../../named_req/allocator "cpp/named req/Allocator"), and
* `[std::uses\_allocator\_v](http://en.cppreference.com/w/cpp/memory/uses_allocator)<Container, Alloc>` is `true` if both `Container` and `Alloc` exist.
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 <vector>
#include <queue>
int main() {
std::vector<int> v = {1,2,3,4};
std::queue s{v}; // guide #1 deduces std::queue<int, vector<int>>
}
```
cpp std::queue<T,Container>::emplace std::queue<T,Container>::emplace
================================
| | | |
| --- | --- | --- |
|
```
template< class... Args >
void emplace( Args&&... args );
```
| | (since C++11) (until C++17) |
|
```
template< class... Args >
decltype(auto) emplace( Args&&... args );
```
| | (since C++17) |
Pushes a new element to the end of the 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)...);`
### Parameters
| | | |
| --- | --- | --- |
| args | - | arguments to forward to the constructor of the element |
### Return value
| | |
| --- | --- |
| (none) | (until C++17) |
| The value or reference, if any, returned by the above call to `Container::emplace_back`. | (since C++17) |
### Complexity
Identical to 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";
}
};
int main()
{
std::queue<S> adaptor;
const S& s = adaptor.emplace(42, 3.14, "C++"); // for return value C++17 required
std::cout << "id = " << s.id << '\n';
}
```
Output:
```
S::S(42, 3.14, "C++")
id = 42
```
### 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 2783](https://cplusplus.github.io/LWG/issue2783) | C++17 | `emplace` returned `reference`, breaking compatibility with pre-C++17 containers | returns `decltype(auto)` |
### See also
| | |
| --- | --- |
| [push](push "cpp/container/queue/push") | inserts element at the end (public member function) |
| [pop](pop "cpp/container/queue/pop") | removes the first element (public member function) |
cpp std::queue<T,Container>::swap std::queue<T,Container>::swap
=============================
| | | |
| --- | --- | --- |
|
```
void swap( 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);`
### 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)))` 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>)` | (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::queue)](swap2 "cpp/container/queue/swap2")
(C++11) | specializes the `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) |
cpp std::queue<T,Container>::queue std::queue<T,Container>::queue
==============================
| | | |
| --- | --- | --- |
|
```
queue() : queue(Container()) { }
```
| (1) | (since C++11) |
| | (2) | |
|
```
explicit queue( const Container& cont = Container() );
```
| (until C++11) |
|
```
explicit queue( const Container& cont );
```
| (since C++11) |
|
```
explicit queue( Container&& cont );
```
| (3) | (since C++11) |
|
```
queue( const queue& other );
```
| (4) | |
|
```
queue( queue&& other );
```
| (5) | (since C++11) |
|
```
template< class InputIt >
queue( InputIt first, InputIt last );
```
| (6) | (since C++23) |
|
```
template< class Alloc >
explicit queue( const Alloc& alloc );
```
| (7) | (since C++11) |
|
```
template< class Alloc >
queue( const Container& cont, const Alloc& alloc );
```
| (8) | (since C++11) |
|
```
template< class Alloc >
queue( Container&& cont, const Alloc& alloc );
```
| (9) | (since C++11) |
|
```
template< class Alloc >
queue( const queue& other, const Alloc& alloc );
```
| (10) | (since C++11) |
|
```
template< class Alloc >
queue( queue&& other, const Alloc& alloc );
```
| (11) | (since C++11) |
|
```
template< class InputIt, class Alloc >
queue( InputIt first, InputIt last, const Alloc& alloc );
```
| (12) | (since C++23) |
Constructs new underlying container of the container adaptor from a variety of data sources.
1) Default constructor. Value-initializes the container.
2) Copy-constructs the underlying container `c` with the contents of `cont`. This is also the default constructor. (until C++11)
3) Move-constructs the underlying container `c` with `std::move(cont)`.
4) Copy constructor. The adaptor is copy-constructed with the contents of `other.c`.
5) Move constructor. The adaptor is constructed with `std::move(other.c)`.
6) Constructs the underlying container `c` with the contents of the range `[first, last)`. This overload participates in overload resolution only if `InputIt` satisfies [LegacyInputIterator](../../named_req/inputiterator "cpp/named req/InputIterator").
7-12) These constructors participate in overload resolution only if `[std::uses\_allocator](http://en.cppreference.com/w/cpp/memory/uses_allocator)<Container, Alloc>::value` is `true`, that is, if the underlying container is an allocator-aware container (true for all standard library containers that can be used with `queue`).
7) Constructs the underlying container using `alloc` as allocator, as if by `c(alloc)`.
8) Constructs the underlying container with the contents of `cont` and using `alloc` as allocator, as if by `c(cont, alloc)`.
9) Constructs the underlying container with the contents of `cont` using move semantics while utilizing `alloc` as allocator, as if by `c(std::move(cont), alloc)`.
10) Constructs the adaptor with the contents of `other.c` and using `alloc` as allocator, as if by `c(other.c, alloc)`.
11) Constructs the adaptor with the contents of `other` using move semantics while utilizing `alloc` as allocator, as if by `c(std::move(other.c), alloc)`.
12) Constructs the underlying container with the contents of the range `[first, last)` using `alloc` as allocator, as if by `c(first, last, alloc)`. This overload participates in overload resolution only if `InputIt` satisfies [LegacyInputIterator](../../named_req/inputiterator "cpp/named req/InputIterator"). ### 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 |
| 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 constructors taking an allocator parameter participate in overload resolution only 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
Same as the corresponding operation on the wrapped container.
### Notes
| [Feature-test](../../utility/feature_test "cpp/utility/feature test") macro | Comment |
| --- | --- |
| [`__cpp_lib_adaptor_iterator_pair_constructor`](../../feature_test#Library_features "cpp/feature test") | for overloads (6) and (12) |
### Example
```
#include <queue>
#include <deque>
#include <iostream>
int main()
{
std::queue<int> c1;
c1.push(5);
std::cout << c1.size() << '\n';
std::queue<int> c2(c1);
std::cout << c2.size() << '\n';
std::deque<int> deq {3, 1, 4, 1, 5};
std::queue<int> c3(deq); // overload (2)
std::cout << c3.size() << '\n';
# ifdef __cpp_lib_adaptor_iterator_pair_constructor
const auto il = {2, 7, 1, 8, 2};
std::queue<int> c4 { il.begin(), il.end() }; // overload (6), C++23
std::cout << c4.size() << '\n';
# endif
}
```
Possible output:
```
1
1
5
5
```
### 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 |
### See also
| | |
| --- | --- |
| [operator=](operator= "cpp/container/queue/operator=") | assigns values to the container adaptor (public member function) |
| programming_docs |
cpp std::queue<T,Container>::back std::queue<T,Container>::back
=============================
| | | |
| --- | --- | --- |
|
```
reference back();
```
| | |
|
```
const_reference back() const;
```
| | |
Returns reference to the last element in the queue. This is the most recently pushed element. Effectively calls `c.back()`.
### Parameters
(none).
### Return value
reference to the last element.
### Complexity
Constant.
### See also
| | |
| --- | --- |
| [front](front "cpp/container/queue/front") | access the first element (public member function) |
| [push](push "cpp/container/queue/push") | inserts element at the end (public member function) |
cpp std::queue<T,Container>::push std::queue<T,Container>::push
=============================
| | | |
| --- | --- | --- |
|
```
void push( const value_type& value );
```
| | |
|
```
void push( value_type&& value );
```
| | (since C++11) |
Pushes the given element `value` to the end of the queue.
1) Effectively calls `c.push_back(value)`
2) Effectively calls `c.push_back(std::move(value))`
### Parameters
| | | |
| --- | --- | --- |
| value | - | the value of the element to push |
### Return value
(none).
### Complexity
Equal to the complexity of `Container::push_back`.
### Example
### See also
| | |
| --- | --- |
| [emplace](emplace "cpp/container/queue/emplace")
(C++11) | constructs element in-place at the end (public member function) |
| [pop](pop "cpp/container/queue/pop") | removes the first element (public member function) |
cpp std::swap(std::queue)
std::swap(std::queue)
=====================
| Defined in header `[<queue>](../../header/queue "cpp/header/queue")` | | |
| --- | --- | --- |
|
```
template< class T, class Container >
void swap( std::queue<T,Container>& lhs,
std::queue<T,Container>& rhs );
```
| | (since C++11) (until C++17) |
|
```
template< class T, class Container >
void swap( std::queue<T,Container>& lhs,
std::queue<T,Container>& rhs ) noexcept(/* see below */);
```
| | (since C++17) |
Specializes the `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` algorithm for `[std::queue](http://en.cppreference.com/w/cpp/container/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>` is `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::queue<int> alice;
std::queue<int> bob;
auto print = [](const auto & title, const auto &cont) {
std::cout << title << " size=" << cont.size();
std::cout << " front=" << cont.front();
std::cout << " back=" << cont.back() << '\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 front=1 back=3
bob : size=4 front=7 back=10
-- SWAP
alice: size=4 front=7 back=10
bob : size=3 front=1 back=3
```
### See also
| | |
| --- | --- |
| [swap](swap "cpp/container/queue/swap")
(C++11) | swaps the contents (public member function) |
cpp std::queue<T,Container>::front std::queue<T,Container>::front
==============================
| | | |
| --- | --- | --- |
|
```
reference front();
```
| | |
|
```
const_reference front() const;
```
| | |
Returns reference to the first element in the queue. This element will be the first element to be removed on a call to `[pop()](pop "cpp/container/queue/pop")`. Effectively calls `c.front()`.
### Parameters
(none).
### Return value
Reference to the first element.
### Complexity
Constant.
### See also
| | |
| --- | --- |
| [back](back "cpp/container/queue/back") | access the last element (public member function) |
| [pop](pop "cpp/container/queue/pop") | removes the first element (public member function) |
cpp std::queue<T,Container>::operator= std::queue<T,Container>::operator=
==================================
| | | |
| --- | --- | --- |
|
```
queue& operator=( const queue& other );
```
| (1) | |
|
```
queue& operator=( 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;`. (implicitly declared)
2) Move assignment operator. Replaces the contents with those of `other` using move semantics. Effectively calls `c = std::move(other.c);` (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)](queue "cpp/container/queue/queue") | constructs the `queue` (public member function) |
cpp operator==,!=,<,<=,>,>=,<=>(std::queue)
operator==,!=,<,<=,>,>=,<=>(std::queue)
=======================================
| | | |
| --- | --- | --- |
|
```
template< class T, class Container >
bool operator==( const std::queue<T,Container>& lhs, const std::queue<T,Container>& rhs );
```
| (1) | |
|
```
template< class T, class Container >
bool operator!=( const std::queue<T,Container>& lhs, const std::queue<T,Container>& rhs );
```
| (2) | |
|
```
template< class T, class Container >
bool operator<( const std::queue<T,Container>& lhs, const std::queue<T,Container>& rhs );
```
| (3) | |
|
```
template< class T, class Container >
bool operator<=( const std::queue<T,Container>& lhs, const std::queue<T,Container>& rhs );
```
| (4) | |
|
```
template< class T, class Container >
bool operator>( const std::queue<T,Container>& lhs, const std::queue<T,Container>& rhs );
```
| (5) | |
|
```
template< class T, class Container >
bool operator>=( const std::queue<T,Container>& lhs, const std::queue<T,Container>& rhs );
```
| (6) | |
|
```
template< class T, std::three_way_comparable Container >
std::compare_three_way_result_t<Container>
operator<=>( const std::queue<T,Container>& lhs, const std::queue<T,Container>& rhs );
```
| (7) | (since C++20) |
Compares the contents of the underlying containers of two container adaptors. The comparison is done by applying the corresponding operator to the underlying containers.
### Parameters
| | | |
| --- | --- | --- |
| lhs, rhs | - | container adaptors whose contents to compare |
| -`T` must meet the requirements of [EqualityComparable](../../named_req/equalitycomparable "cpp/named req/EqualityComparable"). |
### Return value
1-6) `true` if the corresponding comparison yields `true`, `false` otherwise.
7) Result of three-way comparison on underlying containers. ### Complexity
Linear in the size of the container.
cpp std::queue<T,Container>::~queue std::queue<T,Container>::~queue
===============================
| | | |
| --- | --- | --- |
|
```
~queue();
```
| | |
Destructs the `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 `queue`.
cpp std::queue<T,Container>::empty std::queue<T,Container>::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::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/queue/size") | returns the number of elements (public member function) |
cpp std::vector<bool,Allocator>::flip std::vector<bool,Allocator>::flip
=================================
| Defined in header `[<vector>](../../header/vector "cpp/header/vector")` | | |
| --- | --- | --- |
|
```
void flip();
```
| | (until C++20) |
|
```
constexpr void flip();
```
| | (since C++20) |
Toggles each `bool` in the vector (replaces with its opposite value).
### Parameters
(none).
### Return value
(none).
### Example
```
#include <iostream>
#include <vector>
void print(const std::vector<bool>& vb) {
for (const bool b : vb)
std::cout << b;
std::cout << '\n';
}
int main() {
std::vector<bool> v{0, 1, 0, 1};
print(v);
v.flip();
print(v);
}
```
Output:
```
0101
1010
```
### See also
| | |
| --- | --- |
| [operator[]](../vector/operator_at "cpp/container/vector/operator at") | access specified element (public member function of `std::vector<T,Allocator>`) |
| [flip](../../utility/bitset/flip "cpp/utility/bitset/flip") | toggles the values of bits (public member function of `std::bitset<N>`) |
cpp std::vector<bool>::reference std::vector<bool>::reference
============================
| | | |
| --- | --- | --- |
|
```
class reference;
```
| | |
The `[std::vector](http://en.cppreference.com/w/cpp/container/vector)<bool>` specialization defines `[std::vector](http://en.cppreference.com/w/cpp/container/vector)<bool>::reference` as a publicly-accessible nested class. `[std::vector](http://en.cppreference.com/w/cpp/container/vector)<bool>::reference` proxies the behavior of references to a single bit in `[std::vector](http://en.cppreference.com/w/cpp/container/vector)<bool>`.
The primary use of `[std::vector](http://en.cppreference.com/w/cpp/container/vector)<bool>::reference` is to provide an l-value that can be returned from `operator[]`.
Any reads or writes to a vector that happen via a `[std::vector](http://en.cppreference.com/w/cpp/container/vector)<bool>::reference` potentially read or write to the entire underlying vector.
### Member functions
| | |
| --- | --- |
| (constructor) | constructs the reference. Accessible only to `[std::vector](http://en.cppreference.com/w/cpp/container/vector)<bool>` itself (public member function) |
| (destructor) | destroys the reference (public member function) |
| operator= | assigns a `bool` to the referenced bit (public member function) |
| **operator bool** | returns the referenced bit (public member function) |
| flip | flips the referenced bit (public member function) |
std::vector<bool>::reference::~reference
-----------------------------------------
| | | |
| --- | --- | --- |
|
```
~reference();
```
| | (until C++20) |
|
```
constexpr ~reference();
```
| | (since C++20) |
Destroys the reference.
std::vector<bool>::reference::operator=
----------------------------------------
| | | |
| --- | --- | --- |
| | (1) | |
|
```
reference& operator=( bool x );
```
| (until C++11) |
|
```
reference& operator=( bool x ) noexcept;
```
| (since C++11) (until C++20) |
|
```
constexpr reference& operator=( bool x ) noexcept;
```
| (since C++20) |
| | (2) | |
|
```
reference& operator=( const reference& x );
```
| (until C++11) |
|
```
reference& operator=( const reference& x ) noexcept;
```
| (since C++11) (until C++20) |
|
```
constexpr reference& operator=( const reference& x ) noexcept;
```
| (since C++20) |
|
```
constexpr const reference& operator=( bool x ) const noexcept;
```
| (3) | (since C++23) |
Assigns a value to the referenced bit.
### Parameters
| | | |
| --- | --- | --- |
| x | - | value to assign |
### Return value
`*this`.
std::vector<bool>::reference::operator bool
--------------------------------------------
| | | |
| --- | --- | --- |
|
```
operator bool() const;
```
| | (until C++11) |
|
```
operator bool() const noexcept;
```
| | (since C++11) (until C++20) |
|
```
constexpr operator bool() const noexcept;
```
| | (since C++20) |
Returns the value of the referenced bit.
### Parameters
(none).
### Return value
The referenced bit.
std::vector<bool>::reference::flip
-----------------------------------
| | | |
| --- | --- | --- |
|
```
void flip();
```
| | (until C++11) |
|
```
void flip() noexcept;
```
| | (since C++11) (until C++20) |
|
```
constexpr void flip() noexcept;
```
| | (since C++20) |
Inverts the referenced bit.
### Parameters
(none).
### Return value
(none).
### Example
### See also
| | |
| --- | --- |
| [operator[]](../vector/operator_at "cpp/container/vector/operator at") | access specified element (public member function of `std::vector<T,Allocator>`) |
| [swap](swap "cpp/container/vector bool/swap")
[static] | swaps two `std::vector<bool>::reference`s (public static member function) |
cpp std::stack<T,Container>::pop std::stack<T,Container>::pop
============================
| | | |
| --- | --- | --- |
|
```
void pop();
```
| | |
Removes the top element from the stack. Effectively calls `c.pop_back()`.
### Parameters
(none).
### Return value
(none).
### Complexity
Equal to the complexity of `Container::pop_back`.
### Example
### See also
| | |
| --- | --- |
| [emplace](emplace "cpp/container/stack/emplace")
(C++11) | constructs element in-place at the top (public member function) |
| [push](push "cpp/container/stack/push") | inserts element at the top (public member function) |
| [top](top "cpp/container/stack/top") | accesses the top element (public member function) |
cpp std::stack<T,Container>::size std::stack<T,Container>::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 <stack>
int main()
{
std::stack<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/stack/empty") | checks whether the underlying container is empty (public member function) |
cpp deduction guides for std::stack
deduction guides for `std::stack`
=================================
| Defined in header `[<stack>](../../header/stack "cpp/header/stack")` | | |
| --- | --- | --- |
|
```
template< class Container >
stack( Container )
-> stack<typename Container::value_type, Container>;
```
| (1) | (since C++17) |
|
```
template< class InputIt >
stack( InputIt, InputIt )
-> stack<typename std::iterator_traits<InputIt>::value_type>;
```
| (2) | (since C++23) |
|
```
template< class Container, class Alloc >
stack( Container, Alloc )
-> stack<typename Container::value_type, Container>;
```
| (3) | (since C++17) |
|
```
template< class InputIt, class Alloc >
stack( InputIt, InputIt, Alloc )
-> stack<typename std::iterator_traits<InputIt>::value_type,
std::deque<typename std::iterator_traits<InputIt>::value_type, Alloc>>;
```
| (4) | (since C++23) |
These [deduction guides](../../language/class_template_argument_deduction "cpp/language/class template argument deduction") are provided for `stack` to allow deduction from underlying container type.
1) Deduces underlying container type from the argument.
2) Deduces the element type from the iterator, using `[std::deque](http://en.cppreference.com/w/cpp/container/deque)<typename [std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<InputIt>::value\_type>` as the underlying container type.
3-4) Same as (1-2), except that the allocator is provided. These overloads participate in overload resolution only if.
* `InputIt` (if exists) satisfies [LegacyInputIterator](../../named_req/inputiterator "cpp/named req/InputIterator"),
* `Container` (if exists) does not satisfy [Allocator](../../named_req/allocator "cpp/named req/Allocator"),
* for (3) (until C++23)(4) (since C++23), `Alloc` satisfies [Allocator](../../named_req/allocator "cpp/named req/Allocator"), and
* `[std::uses\_allocator\_v](http://en.cppreference.com/w/cpp/memory/uses_allocator)<Container, Alloc>` is `true` if both `Container` and `Alloc` exist.
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 <vector>
#include <stack>
int main() {
std::vector<int> v = {1,2,3,4};
std::stack s{v}; // guide #1 deduces std::stack<int, vector<int>>
}
```
cpp std::stack<T,Container>::emplace std::stack<T,Container>::emplace
================================
| | | |
| --- | --- | --- |
|
```
template< class... Args >
void emplace( Args&&... args );
```
| | (since C++11) (until C++17) |
|
```
template< class... Args >
decltype(auto) emplace( Args&&... args );
```
| | (since C++17) |
Pushes a new element on top of the stack. 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)...);`
### Parameters
| | | |
| --- | --- | --- |
| args | - | arguments to forward to the constructor of the element |
### Return value
| | |
| --- | --- |
| (none) | (until C++17) |
| The value or reference, if any, returned by the above call to `Container::emplace_back`. | (since C++17) |
### Complexity
Identical to the complexity of `Container::emplace_back`.
### Example
```
#include <iostream>
#include <stack>
struct S
{
int id;
S(int i, double d, std::string s) : id{i}
{
std::cout << "S::S(" << i << ", " << d << ", \"" << s << "\");\n";
}
};
int main()
{
std::stack<S> adaptor;
const S& s = adaptor.emplace(42, 3.14, "C++"); // for return value C++17 required
std::cout << "id = " << s.id << '\n';
}
```
Output:
```
S::S(42, 3.14, "C++")
id = 42
```
### 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 2783](https://cplusplus.github.io/LWG/issue2783) | C++17 | `emplace` returned `reference`, breaking compatibility with pre-C++17 containers | returns `decltype(auto)` |
### See also
| | |
| --- | --- |
| [push](push "cpp/container/stack/push") | inserts element at the top (public member function) |
| [pop](pop "cpp/container/stack/pop") | removes the top element (public member function) |
| programming_docs |
cpp std::stack<T,Container>::swap std::stack<T,Container>::swap
=============================
| | | |
| --- | --- | --- |
|
```
void swap( stack& 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);`
### 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)))` 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>)` | (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
```
#include <iostream>
#include <stack>
#include <string>
#include <vector>
template <typename Stack>
void print(Stack stack /* pass by value */, int id)
{
std::cout << "s" << id << " [" << stack.size() << "]: ";
for (; !stack.empty(); stack.pop())
std::cout << stack.top() << ' ';
std::cout << (id > 1 ? "\n\n" : "\n");
}
int main()
{
std::vector<std::string>
v1{"1","2","3","4"},
v2{"โฑฏ","B","ฦ","D","ฦ"};
std::stack s1{std::move(v1)};
std::stack s2{std::move(v2)};
print(s1, 1);
print(s2, 2);
s1.swap(s2);
print(s1, 1);
print(s2, 2);
}
```
Output:
```
s1 [4]: 4 3 2 1
s2 [5]: ฦ D ฦ B โฑฏ
s1 [5]: ฦ D ฦ B โฑฏ
s2 [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 2456](https://cplusplus.github.io/LWG/issue2456) | C++11 | the `noexcept` specification is ill-formed | made to work |
### See also
| | |
| --- | --- |
| [std::swap(std::stack)](swap2 "cpp/container/stack/swap2")
(C++11) | specializes the `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) |
cpp std::stack<T,Container>::top std::stack<T,Container>::top
============================
| | | |
| --- | --- | --- |
|
```
reference top();
```
| | |
|
```
const_reference top() const;
```
| | |
Returns reference to the top element in the stack. This is the most recently pushed element. This element will be removed on a call to `[pop()](pop "cpp/container/stack/pop")`. Effectively calls `c.back()`.
### Parameters
(none).
### Return value
Reference to the last element.
### Complexity
Constant.
### Example
```
#include <stack>
#include <iostream>
void reportStackSize(const std::stack<int>& s)
{
std::cout << s.size() << " elements on stack\n";
}
void reportStackTop(const std::stack<int>& s)
{
// Leaves element on stack
std::cout << "Top element: " << s.top() << '\n';
}
int main()
{
std::stack<int> s;
s.push(2);
s.push(6);
s.push(51);
reportStackSize(s);
reportStackTop(s);
reportStackSize(s);
s.pop();
reportStackSize(s);
reportStackTop(s);
}
```
Output:
```
3 elements on stack
Top element: 51
3 elements on stack
2 elements on stack
Top element: 6
```
### See also
| | |
| --- | --- |
| [push](push "cpp/container/stack/push") | inserts element at the top (public member function) |
| [pop](pop "cpp/container/stack/pop") | removes the top element (public member function) |
cpp std::stack<T,Container>::~stack std::stack<T,Container>::~stack
===============================
| | | |
| --- | --- | --- |
|
```
~stack();
```
| | |
Destructs the `stack`. 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 `stack`.
cpp std::stack<T,Container>::push std::stack<T,Container>::push
=============================
| | | |
| --- | --- | --- |
|
```
void push( const value_type& value );
```
| | |
|
```
void push( value_type&& value );
```
| | (since C++11) |
Pushes the given element `value` to the top of the stack.
1) Effectively calls `c.push_back(value)`
2) Effectively calls `c.push_back(std::move(value))`
### Parameters
| | | |
| --- | --- | --- |
| value | - | the value of the element to push |
### Return value
(none).
### Complexity
Equal to the complexity of `Container::push_back`.
### Example
This program implements the famous [DSL](https://en.wikipedia.org/wiki/Domain-specific_language "enwiki:Domain-specific language") [BrainHack](https://en.wikipedia.org/wiki/Brainfuck "enwiki:Brainfuck"), when `[std::stack](../stack "cpp/container/stack")` is especially convenient to collect paired brackets.
```
#include <map>
#include <stack>
#include <array>
#include <iostream>
#include <stdexcept>
#include <string_view>
class BrainHackInterpreter {
std::map<unsigned, unsigned> open_brackets, close_brackets;
unsigned program_pos_{0};
std::array<std::uint8_t, 32768> data_;
int data_pos_{0};
void collect_brackets_positions(const std::string_view program) {
std::stack<unsigned> brackets_stack;
for (auto pos{0U}; pos != program.length(); ++pos) {
const char c{program[pos]};
if ('[' == c) {
brackets_stack.push(pos);
} else if (']' == c) {
if (brackets_stack.empty()) {
throw std::runtime_error("brackets [] do not match!");
} else {
open_brackets[brackets_stack.top()] = pos;
close_brackets[pos] = brackets_stack.top();
brackets_stack.pop();
}
}
}
if (!brackets_stack.empty())
throw std::runtime_error("brackets [] do not match!");
}
void check_data_pos(int pos) {
if (pos < 0 or pos >= static_cast<int>(data_.size()))
throw std::out_of_range{"data pointer out of bound"};
}
public:
BrainHackInterpreter(const std::string_view program) {
collect_brackets_positions(program);
data_.fill(0);
for (; program_pos_ < program.length(); ++program_pos_) {
switch (program[program_pos_]) {
case '<': check_data_pos(--data_pos_); break;
case '>': check_data_pos(++data_pos_); break;
case '-': --data_[data_pos_]; break;
case '+': ++data_[data_pos_]; break;
case '.': std::cout << data_[data_pos_]; break;
case ',': std::cin >> data_[data_pos_]; break;
case '[':
if (data_[data_pos_] == 0)
program_pos_ = open_brackets[program_pos_];
break;
case ']':
if (data_[data_pos_] != 0)
program_pos_ = close_brackets[program_pos_];
break;
}
}
}
};
int main()
{
BrainHackInterpreter
{
"++++++++[>++>>++>++++>++++<<<<<-]>[<+++>>+++<-]>[<+"
"+>>>+<<-]<[>+>+<<-]>>>--------.<<+++++++++.<<----.>"
">>>>.<<<------.>..++.<++.+.-.>.<.>----.<--.++.>>>+."
};
}
```
Output:
```
Hi, cppreference!
```
### See also
| | |
| --- | --- |
| [emplace](emplace "cpp/container/stack/emplace")
(C++11) | constructs element in-place at the top (public member function) |
| [pop](pop "cpp/container/stack/pop") | removes the top element (public member function) |
cpp std::swap(std::stack)
std::swap(std::stack)
=====================
| Defined in header `[<stack>](../../header/stack "cpp/header/stack")` | | |
| --- | --- | --- |
|
```
template< class T, class Container >
void swap( std::stack<T,Container>& lhs,
std::stack<T,Container>& rhs );
```
| | (since C++11) (until C++17) |
|
```
template< class T, class Container >
void swap( std::stack<T,Container>& lhs,
std::stack<T,Container>& rhs ) noexcept(/* see below */);
```
| | (since C++17) |
Specializes the `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` algorithm for `[std::stack](http://en.cppreference.com/w/cpp/container/stack)`. 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>` is `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 <stack>
int main()
{
std::stack<int> alice;
std::stack<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/stack/swap")
(C++11) | swaps the contents (public member function) |
cpp std::stack<T,Container>::operator= std::stack<T,Container>::operator=
==================================
| | | |
| --- | --- | --- |
|
```
stack& operator=( const stack& other );
```
| (1) | |
|
```
stack& operator=( stack&& 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;`. (implicitly declared)
2) Move assignment operator. Replaces the contents with those of `other` using move semantics. Effectively calls `c = std::move(other.c);` (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)](stack "cpp/container/stack/stack") | constructs the `stack` (public member function) |
cpp operator==,!=,<,<=,>,>=,<=>(std::stack)
operator==,!=,<,<=,>,>=,<=>(std::stack)
=======================================
| | | |
| --- | --- | --- |
|
```
template< class T, class Container >
bool operator==( const std::stack<T,Container>& lhs, const std::stack<T,Container>& rhs );
```
| (1) | |
|
```
template< class T, class Container >
bool operator!=( const std::stack<T,Container>& lhs, const std::stack<T,Container>& rhs );
```
| (2) | |
|
```
template< class T, class Container >
bool operator<( const std::stack<T,Container>& lhs, const std::stack<T,Container>& rhs );
```
| (3) | |
|
```
template< class T, class Container >
bool operator<=( const std::stack<T,Container>& lhs, const std::stack<T,Container>& rhs );
```
| (4) | |
|
```
template< class T, class Container >
bool operator>( const std::stack<T,Container>& lhs, const std::stack<T,Container>& rhs );
```
| (5) | |
|
```
template< class T, class Container >
bool operator>=( const std::stack<T,Container>& lhs, const std::stack<T,Container>& rhs );
```
| (6) | |
|
```
template< class T, std::three_way_comparable Container >
std::compare_three_way_result_t<Container>
operator<=>( const std::stack<T,Container>& lhs, const std::stack<T,Container>& rhs );
```
| (7) | (since C++20) |
Compares the contents of the underlying containers of two container adaptors. The comparison is done by applying the corresponding operator to the underlying containers.
### Parameters
| | | |
| --- | --- | --- |
| lhs, rhs | - | container adaptors whose contents to compare |
| -`T` must meet the requirements of [EqualityComparable](../../named_req/equalitycomparable "cpp/named req/EqualityComparable"). |
### Return value
1-6) `true` if the corresponding comparison yields `true`, `false` otherwise.
7) Result of three-way comparison on underlying containers. ### Complexity
Linear in the size of the container.
cpp std::stack<T,Container>::empty std::stack<T,Container>::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 <stack>
int main()
{
std::cout << std::boolalpha;
std::stack<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/stack/size") | returns the number of elements (public member function) |
cpp std::stack<T,Container>::stack std::stack<T,Container>::stack
==============================
| | | |
| --- | --- | --- |
|
```
stack() : stack(Container()) { }
```
| (1) | (since C++11) |
| | (2) | |
|
```
explicit stack( const Container& cont = Container() );
```
| (until C++11) |
|
```
explicit stack( const Container& cont );
```
| (since C++11) |
|
```
explicit stack( Container&& cont );
```
| (3) | (since C++11) |
|
```
stack( const stack& other );
```
| (4) | |
|
```
stack( stack&& other );
```
| (5) | (since C++11) |
|
```
template< class InputIt >
stack( InputIt first, InputIt last );
```
| (6) | (since C++23) |
|
```
template< class Alloc >
explicit stack( const Alloc& alloc );
```
| (7) | (since C++11) |
|
```
template< class Alloc >
stack( const Container& cont, const Alloc& alloc );
```
| (8) | (since C++11) |
|
```
template< class Alloc >
stack( Container&& cont, const Alloc& alloc );
```
| (9) | (since C++11) |
|
```
template< class Alloc >
stack( const stack& other, const Alloc& alloc );
```
| (10) | (since C++11) |
|
```
template< class Alloc >
stack( stack&& other, const Alloc& alloc );
```
| (11) | (since C++11) |
|
```
template< class InputIt, class Alloc >
stack( InputIt first, InputIt last, const Alloc& alloc );
```
| (12) | (since C++23) |
Constructs new underlying container of the container adaptor from a variety of data sources.
1) Default constructor. Value-initializes the container.
2) Copy-constructs the underlying container `c` with the contents of `cont`. This is also the default constructor. (until C++11)
3) Move-constructs the underlying container `c` with `std::move(cont)`.
4) Copy constructor. The adaptor is copy-constructed with the contents of `other.c`.
5) Move constructor. The adaptor is constructed with `std::move(other.c)`.
6) Constructs the underlying container `c` with the contents of the range `[first, last)`. This overload participates in overload resolution only if `InputIt` satisfies [LegacyInputIterator](../../named_req/inputiterator "cpp/named req/InputIterator").
7-12) These constructors participate in overload resolution only if `[std::uses\_allocator](http://en.cppreference.com/w/cpp/memory/uses_allocator)<Container, Alloc>::value` is `true`, that is, if the underlying container is an allocator-aware container (true for all standard library containers that can be used with `stack`).
7) Constructs the underlying container using `alloc` as allocator, as if by `c(alloc)`.
8) Constructs the underlying container with the contents of `cont` and using `alloc` as allocator, as if by `c(cont, alloc)`.
9) Constructs the underlying container with the contents of `cont` using move semantics while utilizing `alloc` as allocator, as if by `c(std::move(cont), alloc)`.
10) Constructs the adaptor with the contents of `other.c` and using `alloc` as allocator, as if by `c(other.c, alloc)`.
11) Constructs the adaptor with the contents of `other` using move semantics while utilizing `alloc` as allocator, as if by `c(std::move(other.c), alloc)`.
12) Constructs the underlying container with the contents of the range `[first, last)` using `alloc` as allocator, as if by `c(first, last, alloc)`. This overload participates in overload resolution only if `InputIt` satisfies [LegacyInputIterator](../../named_req/inputiterator "cpp/named req/InputIterator"). ### 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 |
| 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 constructors taking an allocator parameter participate in overload resolution only 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
Same as the corresponding operation on the wrapped container.
### Notes
| [Feature-test](../../utility/feature_test "cpp/utility/feature test") macro | Comment |
| --- | --- |
| [`__cpp_lib_adaptor_iterator_pair_constructor`](../../feature_test#Library_features "cpp/feature test") | for overloads (6) and (12) |
### Example
```
#include <stack>
#include <deque>
#include <iostream>
int main()
{
std::stack<int> c1;
c1.push(5);
std::cout << c1.size() << '\n';
std::stack<int> c2(c1);
std::cout << c2.size() << '\n';
std::deque<int> deq {3, 1, 4, 1, 5};
std::stack<int> c3(deq); // overload (2)
std::cout << c3.size() << '\n';
# ifdef __cpp_lib_adaptor_iterator_pair_constructor
const auto il = {2, 7, 1, 8, 2};
std::stack<int> c4 { il.begin(), il.end() }; // overload (6), C++23
std::cout << c4.size() << '\n';
# endif
}
```
Possible output:
```
1
1
5
5
```
### 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 |
### See also
| | |
| --- | --- |
| [operator=](operator= "cpp/container/stack/operator=") | assigns values to the container adaptor (public member function) |
| programming_docs |
cpp std::set<Key,Compare,Allocator>::contains std::set<Key,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 <set>
int main()
{
std::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/set/find") | finds element with specific key (public member function) |
| [count](count "cpp/container/set/count") | returns the number of elements matching specific key (public member function) |
| [equal\_range](equal_range "cpp/container/set/equal range") | returns range of elements matching a specific key (public member function) |
cpp std::set<Key,Compare,Allocator>::size std::set<Key,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::set](http://en.cppreference.com/w/cpp/container/set)<int>`:
```
#include <set>
#include <iostream>
int main()
{
std::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/set/empty") | checks whether the container is empty (public member function) |
| [max\_size](max_size "cpp/container/set/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::set
deduction guides for `std::set`
===============================
| Defined in header `[<set>](../../header/set "cpp/header/set")` | | |
| --- | --- | --- |
|
```
template<class InputIt,
class Comp = std::less<typename std::iterator_traits<InputIt>::value_type>,
class Alloc = std::allocator<typename std::iterator_traits<InputIt>::value_type>>
set(InputIt, InputIt, Comp = Comp(), Alloc = Alloc())
-> set<typename std::iterator_traits<InputIt>::value_type, Comp, Alloc>;
```
| (1) | (since C++17) |
|
```
template<class Key, class Comp = std::less<Key>, class Alloc = std::allocator<Key>>
set(std::initializer_list<Key>, Comp = Comp(), Alloc = Alloc())
-> set<Key, Comp, Alloc>;
```
| (2) | (since C++17) |
|
```
template<class InputIt, class Alloc>
set(InputIt, InputIt, Alloc)
-> set<typename std::iterator_traits<InputIt>::value_type,
std::less<typename std::iterator_traits<InputIt>::value_type>, Alloc>;
```
| (3) | (since C++17) |
|
```
template<class Key, class Alloc>
set(std::initializer_list<Key>, Alloc)
-> set<Key, std::less<Key>, Alloc>;
```
| (4) | (since C++17) |
These [deduction guides](../../language/class_template_argument_deduction "cpp/language/class template argument deduction") are provided for set 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 <set>
int main() {
std::set s = {1,2,3,4}; // guide #2 deduces std::set<int>
std::set s2(s.begin(), s.end()); // guide #1 deduces std::set<int>
}
```
cpp std::set<Key,Compare,Allocator>::emplace std::set<Key,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 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 <chrono>
#include <functional>
#include <iomanip>
#include <iostream>
#include <set>
#include <string>
class Dew
{
private:
int a;
int b;
int c;
public:
Dew(int _a, int _b, int _c)
: a(_a), b(_b), c(_c)
{}
bool operator<(const Dew &other) const
{
if (a < other.a)
return true;
if (a == other.a && b < other.b)
return true;
return (a == other.a && b == other.b && c < other.c);
}
};
const int nof_operations = 120;
int set_emplace() {
std::set<Dew> set;
for(int i = 0; i < nof_operations; ++i)
for(int j = 0; j < nof_operations; ++j)
for(int k = 0; k < nof_operations; ++k)
set.emplace(i, j, k);
return set.size();
}
int set_insert() {
std::set<Dew> set;
for(int i = 0; i < nof_operations; ++i)
for(int j = 0; j < nof_operations; ++j)
for(int k = 0; k < nof_operations; ++k)
set.insert(Dew(i, j, k));
return set.size();
}
void timeit(std::function<int()> set_test, std::string what = "") {
auto start = std::chrono::system_clock::now();
int setsize = set_test();
auto stop = std::chrono::system_clock::now();
std::chrono::duration<double, std::milli> time = stop - start;
if (what.size() > 0 && setsize > 0) {
std::cout << std::fixed << std::setprecision(2)
<< time.count() << " ms for " << what << '\n';
}
}
int main()
{
set_insert();
timeit(set_insert, "insert");
timeit(set_emplace, "emplace");
timeit(set_insert, "insert");
timeit(set_emplace, "emplace");
}
```
Possible output:
```
638.45 ms for insert
619.44 ms for emplace
609.43 ms for insert
652.55 ms for emplace
```
### See also
| | |
| --- | --- |
| [emplace\_hint](emplace_hint "cpp/container/set/emplace hint")
(C++11) | constructs elements in-place using a hint (public member function) |
| [insert](insert "cpp/container/set/insert") | inserts elements or nodes (since C++17) (public member function) |
cpp std::set<Key,Compare,Allocator>::insert std::set<Key,Compare,Allocator>::insert
=======================================
| | | |
| --- | --- | --- |
|
```
std::pair<iterator,bool> insert( const value_type& value );
```
| (1) | |
|
```
std::pair<iterator,bool> insert( value_type&& 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 );
```
| (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) |
|
```
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` in the position as close as possible, just prior(since C++11), to `hint`.
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 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-2) Returns a pair consisting of an iterator to the inserted element (or to the element that prevented the insertion) and a `bool` value set to `true` if 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`](../set#Member_types "cpp/container/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-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. ### 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/set/size") before and after.
The overloads (5,6) are often implemented as a loop that calls the overload (3) with `[end()](end "cpp/container/set/end")` as the hint; they are optimized for appending a sorted sequence (such as another set) whose smallest element is greater than the last element in `*this`.
### Example
```
#include <set>
#include <cassert>
#include <iostream>
int main()
{
std::set<int> set;
auto result_1 = set.insert(3);
assert(result_1.first != set.end()); // it's a valid iterator
assert(*result_1.first == 3);
if (result_1.second)
std::cout << "insert done\n";
auto result_2 = set.insert(3);
assert(result_2.first == result_1.first); // same iterator
assert(*result_2.first == 3);
if (!result_2.second)
std::cout << "no insertion\n";
}
```
Output:
```
insert done
no insertion
```
### See also
| | |
| --- | --- |
| [emplace](emplace "cpp/container/set/emplace")
(C++11) | constructs element in-place (public member function) |
| [emplace\_hint](emplace_hint "cpp/container/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) |
cpp std::set<Key,Compare,Allocator>::merge std::set<Key,Compare,Allocator>::merge
======================================
| | | |
| --- | --- | --- |
|
```
template<class C2>
void merge( std::set<Key, C2, Allocator>& source );
```
| (1) | (since C++17) |
|
```
template<class C2>
void merge( std::set<Key, C2, Allocator>&& source );
```
| (2) | (since C++17) |
|
```
template<class C2>
void merge( std::multiset<Key, C2, Allocator>& source );
```
| (3) | (since C++17) |
|
```
template<class C2>
void merge( std::multiset<Key, 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 <iostream>
#include <set>
// print out a container
template <class Os, class K>
Os& operator<<(Os& os, const std::set<K>& v) {
os << '[' << v.size() << "] {";
bool o{};
for (const auto& e : v)
os << (o ? ", " : (o = 1, " ")) << e;
return os << " }\n";
}
int main()
{
std::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;
}
```
Output:
```
p: [3] { A, B, C }
q: [3] { C, D, E }
p.merge(q);
p: [5] { A, B, C, D, E }
q: [1] { C }
```
### See also
| | |
| --- | --- |
| [extract](extract "cpp/container/set/extract")
(C++17) | extracts nodes from the container (public member function) |
| [insert](insert "cpp/container/set/insert") | inserts elements or nodes (since C++17) (public member function) |
cpp std::set<Key,Compare,Allocator>::extract std::set<Key,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/set/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 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 <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::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);
}
```
Output:
```
Start: 1 2 3
After extract and before insert: 2 3
End: 2 3 4
```
### See also
| | |
| --- | --- |
| [merge](merge "cpp/container/set/merge")
(C++17) | splices nodes from another container (public member function) |
| [insert](insert "cpp/container/set/insert") | inserts elements or nodes (since C++17) (public member function) |
| [erase](erase "cpp/container/set/erase") | erases elements (public member function) |
| programming_docs |
cpp std::set<Key,Compare,Allocator>::lower_bound std::set<Key,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/set/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/set/equal range") | returns range of elements matching a specific key (public member function) |
| [upper\_bound](upper_bound "cpp/container/set/upper bound") | returns an iterator to the first element *greater* than the given key (public member function) |
cpp std::set<Key,Compare,Allocator>::emplace_hint std::set<Key,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 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 <set>
const int n_operations = 100500;
std::size_t set_emplace() {
std::set<int> set;
for(int i = 0; i < n_operations; ++i) {
set.emplace(i);
}
return set.size();
}
std::size_t set_emplace_hint() {
std::set<int> set;
auto it = set.begin();
for(int i = 0; i < n_operations; ++i) {
set.emplace_hint(it, i);
it = set.end();
}
return set.size();
}
std::size_t set_emplace_hint_wrong() {
std::set<int> set;
auto it = set.begin();
for(int i = n_operations; i > 0; --i) {
set.emplace_hint(it, i);
it = set.end();
}
return set.size();
}
std::size_t set_emplace_hint_corrected() {
std::set<int> set;
auto it = set.begin();
for(int i = n_operations; i > 0; --i) {
set.emplace_hint(it, i);
it = set.begin();
}
return set.size();
}
std::size_t set_emplace_hint_closest() {
std::set<int> set;
auto it = set.begin();
for(int i = 0; i < n_operations; ++i) {
it = set.emplace_hint(it, i);
}
return set.size();
}
void timeit(std::function<std::size_t()> set_test, const char* what = nullptr) {
const auto start = std::chrono::system_clock::now();
const std::size_t setsize = set_test();
const auto stop = std::chrono::system_clock::now();
const std::chrono::duration<double, std::milli> time = stop - start;
if (what != nullptr && setsize > 0) {
std::cout << std::setw(6) << time.count() << " ms for " << what << '\n';
}
}
int main() {
std::cout << std::fixed << std::setprecision(2);
timeit(set_emplace); // stack warmup
timeit(set_emplace, "plain emplace");
timeit(set_emplace_hint, "emplace with correct hint");
timeit(set_emplace_hint_wrong, "emplace with wrong hint");
timeit(set_emplace_hint_corrected, "corrected emplace");
timeit(set_emplace_hint_closest, "emplace using returned iterator");
}
```
Possible output:
```
25.50 ms for plain emplace
9.79 ms for emplace with correct hint
28.49 ms for emplace with wrong hint
8.01 ms for corrected emplace
8.13 ms for emplace using returned iterator
```
### See also
| | |
| --- | --- |
| [emplace](emplace "cpp/container/set/emplace")
(C++11) | constructs element in-place (public member function) |
| [insert](insert "cpp/container/set/insert") | inserts elements or nodes (since C++17) (public member function) |
cpp std::set<Key,Compare,Allocator>::rbegin, std::set<Key,Compare,Allocator>::crbegin std::set<Key,Compare,Allocator>::rbegin, std::set<Key,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 `set`. It corresponds to the last element of the non-reversed `set`. If the `set` is empty, the returned iterator is equal to `[rend()](rend "cpp/container/set/rend")`.
![range-rbegin-rend.svg]()
### Parameters
(none).
### Return value
Reverse 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 <set>
int main()
{
std::set<unsigned> rep{1, 2, 3, 4, 1, 2, 3, 4};
for (auto it = rep.crbegin(); it != rep.crend(); ++it) {
for (auto n = *it; n > 0; --n)
std::cout << "โผ" << ' ';
std::cout << '\n';
}
}
```
Output:
```
โผ โผ โผ โผ
โผ โผ โผ
โผ โผ
โผ
```
### See also
| | |
| --- | --- |
| [rendcrend](rend "cpp/container/set/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::set<Key,Compare,Allocator>::~set std::set<Key,Compare,Allocator>::~set
=====================================
| | | |
| --- | --- | --- |
|
```
~set();
```
| | |
Destructs the `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 `set`.
cpp std::set<Key,Compare,Allocator>::swap std::set<Key,Compare,Allocator>::swap
=====================================
| | | |
| --- | --- | --- |
|
```
void swap( set& other );
```
| | (until C++17) |
|
```
void swap( 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 `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 <functional>
#include <iostream>
#include <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::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.
struct Cmp : std::less<int> {
int id{};
Cmp(int i) : id{i} { }
};
std::set<int, Cmp> s1{ {2, 2, 1, 1}, Cmp{6} }, s2{ {4, 4, 3, 3}, Cmp{9} };
std::cout << s1 << s2 << s1.key_comp().id << ' ' << s2.key_comp().id << '\n';
s1.swap(s2);
std::cout << s1 << s2 << s1.key_comp().id << ' ' << s2.key_comp().id << '\n';
// So, comparator objects (Cmp) are also exchanged after the swap.
}
```
Output:
```
{ 1 2 3 } { 4 5 } 2 5 1 4
{ 4 5 } { 1 2 3 } 2 5 1 4
{ 1 2 } { 3 4 } 6 9
{ 3 4 } { 1 2 } 9 6
```
### See also
| | |
| --- | --- |
| [std::swap(std::set)](swap2 "cpp/container/set/swap2") | specializes the `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) |
cpp std::set<Key,Compare,Allocator>::max_size std::set<Key,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 <set>
int main()
{
std::set<char> q;
std::cout.imbue(std::locale("en_US.UTF-8"));
std::cout << "Maximum size of a std::set is " << q.max_size() << '\n';
}
```
Possible output:
```
Maximum size of a std::set is 576,460,752,303,423,487
```
### See also
| | |
| --- | --- |
| [size](size "cpp/container/set/size") | returns the number of elements (public member function) |
cpp std::set<Key,Compare,Allocator>::count std::set<Key,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
```
#include <set>
#include <iostream>
struct S {
int x;
S(int i) : x{i} { std::cout << "S{" << i << "} "; }
bool operator<(S const& s) const { return x < s.x; }
};
struct R {
int x;
R(int i) : x{i} { std::cout << "R{" << i << "} "; }
bool operator<(R const& r) const { return x < r.x; }
};
bool operator<(R const& r, int i) { return r.x < i; }
bool operator<(int i, R const& r) { return i < r.x; }
int main()
{
std::set<int> t{3, 1, 4, 1, 5};
std::cout << t.count(1) << ", " << t.count(2) << ".\n";
std::set<S> s{3, 1, 4, 1, 5};
std::cout << ": " << s.count(1) << ", " << s.count(2) << ".\n";
// Two temporary objects S{1} and S{2} were created.
// Comparison function object is defaulted std::less<S>,
// which is not transparent (has no is_transparent member type).
std::set<R, std::less<>> r{3, 1, 4, 1, 5};
std::cout << ": " << r.count(1) << ", " << r.count(2) << ".\n";
// C++14 heterogeneous lookup; temporary objects were not created.
// Comparator std::less<void> has predefined is_transparent.
}
```
Output:
```
1, 0.
S{3} S{1} S{4} S{1} S{5} : S{1} 1, S{2} 0.
R{3} R{1} R{4} R{1} R{5} : 1, 0.
```
### See also
| | |
| --- | --- |
| [find](find "cpp/container/set/find") | finds element with specific key (public member function) |
| [equal\_range](equal_range "cpp/container/set/equal range") | returns range of elements matching a specific key (public member function) |
cpp std::set<Key,Compare,Allocator>::value_comp std::set<Key,Compare,Allocator>::value\_comp
============================================
| | | |
| --- | --- | --- |
|
```
std::set::value_compare value_comp() const;
```
| | |
Returns the function object that compares the values. It is the same as `[key\_comp](key_comp "cpp/container/set/key comp")`.
### Parameters
(none).
### Return value
The value comparison function object.
### Complexity
Constant.
### Example
```
#include <cassert>
#include <iostream>
#include <set>
// 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::set<int, ModCmp> cont{1, 2, 3, 4, 5};
// Same behaviour as key_comp()
auto comp_func = cont.value_comp();
const int val = 100;
for (int key : cont) {
bool before = comp_func(key, val);
bool after = comp_func(val, key);
if (!before && !after)
std::cout << key << " equivalent to key " << val << '\n';
else if (before)
std::cout << key << " goes before key " << val << '\n';
else if (after)
std::cout << key << " goes after key " << val << '\n';
else
assert(0); // Cannot happen
}
}
```
Output:
```
1 goes before key 100
2 goes before key 100
3 equivalent to key 100
4 goes after key 100
5 goes after key 100
```
### See also
| | |
| --- | --- |
| [key\_comp](key_comp "cpp/container/set/key comp") | returns the function that compares keys (public member function) |
cpp std::set<Key,Compare,Allocator>::find std::set<Key,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/set/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 <set>
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::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";
}
// transparent comparison demo
std::set<FatKey, std::less<>> example2 = { {1, {} }, {2, {} }, {3, {} }, {4, {} } };
LightKey lk = {2};
auto search2 = example2.find(lk);
if (search2 != example2.end()) {
std::cout << "Found " << search2->x << '\n';
} else {
std::cout << "Not found\n";
}
}
```
Output:
```
Found 2
Found 2
```
### See also
| | |
| --- | --- |
| [count](count "cpp/container/set/count") | returns the number of elements matching specific key (public member function) |
| [equal\_range](equal_range "cpp/container/set/equal range") | returns range of elements matching a specific key (public member function) |
| programming_docs |
cpp std::set<Key,Compare,Allocator>::equal_range std::set<Key,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/set/lower bound")`, and the second with `[upper\_bound()](upper_bound "cpp/container/set/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/set/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 <set>
#include <iostream>
template <typename I>
void print_equal_range(I first, I lb, I ub, I last) {
for (I i{first}; i != lb; ++i)
std::cout << *i << " ";
std::cout << "[ ";
for (I i{lb}; i != ub; ++i)
std::cout << *i << " ";
std::cout << ") ";
for (I i{ub}; i != last; ++i)
std::cout << *i << " ";
std::cout << '\n';
}
int main()
{
std::set<int> c{4, 3, 2, 1, 3, 3};
std::cout << "c = ";
print_equal_range(begin(c), begin(c), end(c), end(c));
for (int key{}; key != 6; ++key) {
std::cout << "key = " << key << "; equal range = ";
const auto [lb, ub] = c.equal_range(key);
print_equal_range(begin(c), lb, ub, end(c));
}
}
```
Output:
```
c = [ 1 2 3 4 )
key = 0; equal range = [ ) 1 2 3 4
key = 1; equal range = [ 1 ) 2 3 4
key = 2; equal range = 1 [ 2 ) 3 4
key = 3; equal range = 1 2 [ 3 ) 4
key = 4; equal range = 1 2 3 [ 4 )
key = 5; equal range = 1 2 3 4 [ )
```
### See also
| | |
| --- | --- |
| [find](find "cpp/container/set/find") | finds element with specific key (public member function) |
| [contains](contains "cpp/container/set/contains")
(C++20) | checks if the container contains element with specific key (public member function) |
| [count](count "cpp/container/set/count") | returns the number of elements matching specific key (public member function) |
| [upper\_bound](upper_bound "cpp/container/set/upper bound") | returns an iterator to the first element *greater* than the given key (public member function) |
| [lower\_bound](lower_bound "cpp/container/set/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::set<Key,Compare,Allocator>::key_comp std::set<Key,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](set "cpp/container/set/set") argument `comp`. It is the same as `[value\_comp](value_comp "cpp/container/set/value comp")`.
### Parameters
(none).
### Return value
The key comparison function object.
### Complexity
Constant.
### Example
```
#include <cassert>
#include <iostream>
#include <set>
// 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::set<int, ModCmp> cont{1, 2, 3, 4, 5};
auto comp_func = cont.key_comp();
for (int key : cont) {
bool before = comp_func(key, 100);
bool after = comp_func(100, key);
if (!before && !after)
std::cout << key << " equivalent to key 100\n";
else if (before)
std::cout << key << " goes before key 100\n";
else if (after)
std::cout << key << " goes after key 100\n";
else
assert(0); // Cannot happen
}
}
```
Output:
```
1 goes before key 100
2 goes before key 100
3 equivalent to key 100
4 goes after key 100
5 goes after key 100
```
### See also
| | |
| --- | --- |
| [value\_comp](value_comp "cpp/container/set/value comp") | returns the function that compares keys in objects of type value\_type (public member function) |
cpp std::set<Key,Compare,Allocator>::erase std::set<Key,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`. Only one overload is provided if `iterator` and `const_iterator` are the same type. (since C++11)
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/set/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 `set`:
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 <set>
#include <iostream>
int main()
{
std::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();
}
```
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 |
### See also
| | |
| --- | --- |
| [clear](clear "cpp/container/set/clear") | clears the contents (public member function) |
cpp std::swap(std::set)
std::swap(std::set)
===================
| Defined in header `[<set>](../../header/set "cpp/header/set")` | | |
| --- | --- | --- |
|
```
template< class Key, class Compare, class Alloc >
void swap( std::set<Key,Compare,Alloc>& lhs,
std::set<Key,Compare,Alloc>& rhs );
```
| | (until C++17) |
|
```
template< class Key, class Compare, class Alloc >
void swap( std::set<Key,Compare,Alloc>& lhs,
std::set<Key,Compare,Alloc>& rhs ) noexcept(/* see below */);
```
| | (since C++17) |
Specializes the `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` algorithm for `[std::set](http://en.cppreference.com/w/cpp/container/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 <set>
int main()
{
std::set<int> alice{1, 2, 3};
std::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';
}
```
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/set/swap") | swaps the contents (public member function) |
cpp std::set<Key,Compare,Allocator>::operator= std::set<Key,Compare,Allocator>::operator=
==========================================
| | | |
| --- | --- | --- |
|
```
set& operator=( const set& other );
```
| (1) | |
| | (2) | |
|
```
set& operator=( set&& other );
```
| (since C++11) (until C++17) |
|
```
set& operator=( set&& other ) noexcept(/* see below */);
```
| (since C++17) |
|
```
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. | (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/set/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::set](../set "cpp/container/set")` to another:
```
#include <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::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);
}
```
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)](set "cpp/container/set/set") | constructs the `set` (public member function) |
cpp std::set<Key,Compare,Allocator>::rend, std::set<Key,Compare,Allocator>::crend std::set<Key,Compare,Allocator>::rend, std::set<Key,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 `set`. It corresponds to the element preceding the first element of the non-reversed `set`. 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.
### 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 <set>
int main()
{
std::set<unsigned> rep{1, 2, 3, 4, 1, 2, 3, 4};
for (auto it = rep.crbegin(); it != rep.crend(); ++it) {
for (auto n = *it; n > 0; --n)
std::cout << "โผ" << ' ';
std::cout << '\n';
}
}
```
Output:
```
โผ โผ โผ โผ
โผ โผ โผ
โผ โผ
โผ
```
### See also
| | |
| --- | --- |
| [rbegincrbegin](rbegin "cpp/container/set/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::set<Key,Compare,Allocator>::clear std::set<Key,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/set/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 <set>
int main()
{
std::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';
}
```
Output:
```
Before clear: 1 2 3
Size=3
Clear
After clear:
Size=0
```
### See also
| | |
| --- | --- |
| [erase](erase "cpp/container/set/erase") | erases elements (public member function) |
| programming_docs |
cpp std::set<Key,Compare,Allocator>::upper_bound std::set<Key,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/set/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/set/equal range") | returns range of elements matching a specific key (public member function) |
| [lower\_bound](lower_bound "cpp/container/set/lower bound") | returns an iterator to the first element *not less* than the given key (public member function) |
cpp std::set<Key,Compare,Allocator>::set std::set<Key,Compare,Allocator>::set
====================================
| | | |
| --- | --- | --- |
| | (1) | |
|
```
set();
explicit set( const Compare& comp,
const Allocator& alloc = Allocator() );
```
| |
|
```
explicit set( const Allocator& alloc );
```
| (since C++11) |
| | (2) | |
|
```
template< class InputIt >
set( InputIt first, InputIt last,
const Compare& comp = Compare(),
const Allocator& alloc = Allocator() );
```
| |
|
```
template< class InputIt >
set( InputIt first, InputIt last, const Allocator& alloc)
: set(first, last, Compare(), alloc) {}
```
| (since C++14) |
|
```
set( const set& other );
```
| (3) | |
|
```
set( const set& other, const Allocator& alloc );
```
| (3) | (since C++11) |
|
```
set( set&& other );
```
| (4) | (since C++11) |
|
```
set( set&& other, const Allocator& alloc );
```
| (4) | (since C++11) |
| | (5) | |
|
```
set( std::initializer_list<value_type> init,
const Compare& comp = Compare(),
const Allocator& alloc = Allocator() );
```
| (since C++11) |
|
```
set( std::initializer_list<value_type> init, const Allocator& alloc )
: set(init, Compare(), alloc) {}
```
| (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) [Default constructor](../../language/default_constructor "cpp/language/default constructor"). Constructs empty container.
2) Range constructor. 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)).
3) [Copy constructor](../../language/copy_constructor "cpp/language/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) |
4) [Move constructor](../../language/move_constructor "cpp/language/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) [Initializer-list constructor](../../language/list_initialization "cpp/language/list initialization"). 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) Constant
2) 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()`.
3) Linear in size of `other`
4) Constant. If `alloc` is given and `alloc != other.get_allocator()`, then linear.
5) 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 (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 <iostream>
#include <string>
#include <set>
#include <cmath>
struct Point { double x, y; };
struct PointCmp {
bool operator()(const Point& lhs, const Point& rhs) const {
return std::hypot(lhs.x, lhs.y) < std::hypot(rhs.x, rhs.y);
}
};
int main()
{
// (1) Default constructor
std::set<std::string> a;
a.insert("cat");
a.insert("dog");
a.insert("horse");
for(auto& str: a) std::cout << str << ' ';
std::cout << '\n';
// (2) Iterator constructor
std::set<std::string> b(a.find("dog"), a.end());
for(auto& str: b) std::cout << str << ' ';
std::cout << '\n';
// (3) Copy constructor
std::set<std::string> c(a);
c.insert("another horse");
for(auto& str: c) std::cout << str << ' ';
std::cout << '\n';
// (4) Move constructor
std::set<std::string> d(std::move(a));
for(auto& str: d) std::cout << str << ' ';
std::cout << '\n';
std::cout << "moved-from set is ";
for(auto& str: a) std::cout << str << ' ';
std::cout << '\n';
// (5) Initializer list constructor
std::set<std::string> e {"one", "two", "three", "five", "eight"};
for(auto& str: e) std::cout << str << ' ';
std::cout << '\n';
// custom comparison
std::set<Point, PointCmp> z = {{2, 5}, {3, 4}, {1, 1}};
z.insert({1, -1}); // this fails because the magnitude of 1,-1 equals 1,1
for(auto& p: z) std::cout << '(' << p.x << ',' << p.y << ") ";
std::cout << '\n';
}
```
Output:
```
cat dog horse
dog horse
another horse cat dog horse
cat dog horse
moved-from set is
eight five one three two
(1,1) (3,4) (2,5)
```
### 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/set/operator=") | assigns values to the container (public member function) |
cpp std::set<Key,Compare,Allocator>::empty std::set<Key,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::set](http://en.cppreference.com/w/cpp/container/set)<int>` contains any elements:
```
#include <set>
#include <iostream>
int main()
{
std::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/set/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::set<Key,Compare,Allocator>::begin, std::set<Key,Compare,Allocator>::cbegin std::set<Key,Compare,Allocator>::begin, std::set<Key,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 `set`.
If the `set` is empty, the returned iterator will be equal to `[end()](end "cpp/container/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 <algorithm>
#include <iostream>
#include <set>
int main() {
std::set<int> set = { 3, 1, 4, 1, 5, 9, 2, 6, 5 };
std::for_each(set.cbegin(), set.cend(), [](int x) {
std::cout << x << ' ';
});
std::cout << '\n';
}
```
Output:
```
1 2 3 4 5 6 9
```
### See also
| | |
| --- | --- |
| [end cend](end "cpp/container/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::set<Key,Compare,Allocator>::end, std::set<Key,Compare,Allocator>::cend std::set<Key,Compare,Allocator>::end, std::set<Key,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 `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 <algorithm>
#include <iostream>
#include <set>
int main() {
std::set<int> set = { 3, 1, 4, 1, 5, 9, 2, 6, 5 };
std::for_each(set.cbegin(), set.cend(), [](int x) {
std::cout << x << ' ';
});
std::cout << '\n';
}
```
Output:
```
1 2 3 4 5 6 9
```
### See also
| | |
| --- | --- |
| [begin cbegin](begin "cpp/container/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::multiset<Key,Compare,Allocator>::multiset std::multiset<Key,Compare,Allocator>::multiset
==============================================
| | | |
| --- | --- | --- |
|
```
multiset();
```
| (1) | |
|
```
explicit multiset( const Compare& comp,
const Allocator& alloc = Allocator() );
```
| (2) | |
|
```
explicit multiset( const Allocator& alloc );
```
| (3) | (since C++11) |
|
```
template< class InputIt >
multiset( InputIt first, InputIt last,
const Compare& comp = Compare(),
const Allocator& alloc = Allocator() );
```
| (4) | |
|
```
template< class InputIt >
multiset( InputIt first, InputIt last,
const Allocator& alloc );
```
| (5) | (since C++14) |
|
```
multiset( const multiset& other );
```
| (6) | |
|
```
multiset( const multiset& other, const Allocator& alloc );
```
| (7) | (since C++11) |
|
```
multiset( multiset&& other );
```
| (8) | (since C++11) |
|
```
multiset( multiset&& other, const Allocator& alloc );
```
| (9) | (since C++11) |
|
```
multiset( std::initializer_list<value_type> init,
const Compare& comp = Compare(),
const Allocator& alloc = Allocator() );
```
| (10) | (since C++11) |
|
```
multiset( 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 <string_view>
#include <set>
void print(const std::string_view name, const std::multiset<int>& ms)
{
std::cout << name << ": ";
for(auto element: ms)
std::cout << element << " ";
std::cout << '\n';
}
int main()
{
// (1) Default constructor
std::multiset<int> a;
a.insert(4);
a.insert(3);
a.insert(2);
a.insert(1);
print("a", a);
// (4) Iterator constructor
std::multiset<int> b(a.begin(), a.find(3));
print("b", b);
// (6) Copy constructor
std::multiset<int> c(a);
print("c", c);
// (8) Move constructor
std::multiset<int> d(std::move(a));
print("d", d);
// (10) Initializer list constructor
std::multiset<int> e {3,2,1,2,4,7,3};
print("e", e);
}
```
Output:
```
a: 1 2 3 4
b: 1 2
c: 1 2 3 4
d: 1 2 3 4
e: 1 2 2 3 3 4 7
```
### 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/multiset/operator=") | assigns values to the container (public member function) |
| programming_docs |
cpp std::multiset<Key,Compare,Allocator>::contains std::multiset<Key,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 <set>
int main()
{
std::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/multiset/find") | finds element with specific key (public member function) |
| [count](count "cpp/container/multiset/count") | returns the number of elements matching specific key (public member function) |
| [equal\_range](equal_range "cpp/container/multiset/equal range") | returns range of elements matching a specific key (public member function) |
cpp std::multiset<Key,Compare,Allocator>::size std::multiset<Key,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::multiset](../multiset "cpp/container/multiset")`:
```
#include <set>
#include <iostream>
int main()
{
std::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/multiset/empty") | checks whether the container is empty (public member function) |
| [max\_size](max_size "cpp/container/multiset/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::multiset
deduction guides for `std::multiset`
====================================
| Defined in header `[<set>](../../header/set "cpp/header/set")` | | |
| --- | --- | --- |
|
```
template<class InputIt,
class Comp = std::less<typename std::iterator_traits<InputIt>::value_type>,
class Alloc = std::allocator<typename std::iterator_traits<InputIt>::value_type>>
multiset(InputIt, InputIt, Comp = Comp(), Alloc = Alloc())
-> multiset<typename std::iterator_traits<InputIt>::value_type, Comp, Alloc>;
```
| (1) | (since C++17) |
|
```
template<class Key, class Comp = std::less<Key>, class Alloc = std::allocator<Key>>
multiset(std::initializer_list<Key>, Comp = Comp(), Alloc = Alloc())
-> multiset<Key, Comp, Alloc>;
```
| (2) | (since C++17) |
|
```
template<class InputIt, class Alloc>
multiset(InputIt, InputIt, Alloc)
-> multiset<typename std::iterator_traits<InputIt>::value_type,
std::less<typename std::iterator_traits<InputIt>::value_type>, Alloc>;
```
| (3) | (since C++17) |
|
```
template<class Key, class Alloc>
multiset(std::initializer_list<Key>, Alloc)
-> multiset<Key, std::less<Key>, Alloc>;
```
| (4) | (since C++17) |
These [deduction guides](../../language/class_template_argument_deduction "cpp/language/class template argument deduction") are provided for multiset 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 <set>
int main() {
std::multiset s = {1,2,3,4}; // guide #2 deduces std::multiset<int>
std::multiset s2(s.begin(), s.end()); // guide #1 deduces std::multiset<int>
}
```
cpp std::multiset<Key,Compare,Allocator>::emplace std::multiset<Key,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 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
### See also
| | |
| --- | --- |
| [emplace\_hint](emplace_hint "cpp/container/multiset/emplace hint")
(C++11) | constructs elements in-place using a hint (public member function) |
| [insert](insert "cpp/container/multiset/insert") | inserts elements or nodes (since C++17) (public member function) |
cpp std::multiset<Key,Compare,Allocator>::insert std::multiset<Key,Compare,Allocator>::insert
============================================
| | | |
| --- | --- | --- |
|
```
iterator insert( const value_type& value );
```
| (1) | |
|
```
iterator insert( value_type&& 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 );
```
| (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).
3-4) inserts `value` in the position as close as possible, just prior(since C++11), to `hint`.
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
### See also
| | |
| --- | --- |
| [emplace](emplace "cpp/container/multiset/emplace")
(C++11) | constructs element in-place (public member function) |
| [emplace\_hint](emplace_hint "cpp/container/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::multiset<Key,Compare,Allocator>::get_allocator std::multiset<Key,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::multiset<Key,Compare,Allocator>::merge std::multiset<Key,Compare,Allocator>::merge
===========================================
| | | |
| --- | --- | --- |
|
```
template<class C2>
void merge( std::set<Key, C2, Allocator>& source );
```
| (1) | (since C++17) |
|
```
template<class C2>
void merge( std::set<Key, C2, Allocator>&& source );
```
| (2) | (since C++17) |
|
```
template<class C2>
void merge( std::multiset<Key, C2, Allocator>& source );
```
| (3) | (since C++17) |
|
```
template<class C2>
void merge( std::multiset<Key, 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 <iostream>
#include <set>
// print out a container
template <class Os, class K>
Os& operator<<(Os& os, const std::multiset<K>& v) {
os << '[' << v.size() << "] {";
bool o{};
for (const auto& e : v)
os << (o ? ", " : (o = 1, " ")) << e;
return os << " }\n";
}
int main()
{
std::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;
}
```
Output:
```
p: [4] { A, B, B, C }
q: [4] { C, D, E, E }
p.merge(q);
p: [8] { A, B, B, C, C, D, E, E }
q: [0] { }
```
### See also
| | |
| --- | --- |
| [extract](extract "cpp/container/multiset/extract")
(C++17) | extracts nodes from the container (public member function) |
| [insert](insert "cpp/container/multiset/insert") | inserts elements or nodes (since C++17) (public member function) |
cpp std::multiset<Key,Compare,Allocator>::extract std::multiset<Key,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/multiset/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 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 <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::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);
}
```
Output:
```
Start: 1 2 3
After extract and before insert: 2 3
End: 2 3 4
```
### See also
| | |
| --- | --- |
| [merge](merge "cpp/container/multiset/merge")
(C++17) | splices nodes from another container (public member function) |
| [insert](insert "cpp/container/multiset/insert") | inserts elements or nodes (since C++17) (public member function) |
| [erase](erase "cpp/container/multiset/erase") | erases elements (public member function) |
cpp std::multiset<Key,Compare,Allocator>::lower_bound std::multiset<Key,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/multiset/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/multiset/equal range") | returns range of elements matching a specific key (public member function) |
| [upper\_bound](upper_bound "cpp/container/multiset/upper bound") | returns an iterator to the first element *greater* than the given key (public member function) |
| programming_docs |
cpp std::multiset<Key,Compare,Allocator>::emplace_hint std::multiset<Key,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 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/multiset/emplace")
(C++11) | constructs element in-place (public member function) |
| [insert](insert "cpp/container/multiset/insert") | inserts elements or nodes (since C++17) (public member function) |
cpp std::multiset<Key,Compare,Allocator>::rbegin, std::multiset<Key,Compare,Allocator>::crbegin std::multiset<Key,Compare,Allocator>::rbegin, std::multiset<Key,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 `multiset`. It corresponds to the last element of the non-reversed `multiset`. If the `multiset` is empty, the returned iterator is equal to `[rend()](rend "cpp/container/multiset/rend")`.
![range-rbegin-rend.svg]()
### Parameters
(none).
### Return value
Reverse 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 <set>
int main()
{
std::multiset<unsigned> rep{1, 2, 3, 4, 1, 2, 3, 4};
for (auto it = rep.crbegin(); it != rep.crend(); ++it) {
for (auto n = *it; n > 0; --n)
std::cout << "โผ" << ' ';
std::cout << '\n';
}
}
```
Output:
```
โผ โผ โผ โผ
โผ โผ โผ โผ
โผ โผ โผ
โผ โผ โผ
โผ โผ
โผ โผ
โผ
โผ
```
### See also
| | |
| --- | --- |
| [rendcrend](rend "cpp/container/multiset/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::multiset<Key,Compare,Allocator>::swap std::multiset<Key,Compare,Allocator>::swap
==========================================
| | | |
| --- | --- | --- |
|
```
void swap( multiset& other );
```
| | (until C++17) |
|
```
void swap( 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 `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 <functional>
#include <iostream>
#include <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::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.
struct Cmp : std::less<int> {
int id{};
Cmp(int i) : id{i} { }
};
std::multiset<int, Cmp> s1{ {2, 2, 1, 1}, Cmp{6} }, s2{ {4, 4, 3, 3}, Cmp{9} };
std::cout << s1 << s2 << s1.key_comp().id << ' ' << s2.key_comp().id << '\n';
s1.swap(s2);
std::cout << s1 << s2 << s1.key_comp().id << ' ' << s2.key_comp().id << '\n';
// So, comparator objects (Cmp) are also exchanged after the swap.
}
```
Output:
```
{ 1 2 3 3 } { 4 5 5 } 2 5 1 4
{ 4 5 5 } { 1 2 3 3 } 2 5 1 4
{ 1 1 2 2 } { 3 3 4 4 } 6 9
{ 3 3 4 4 } { 1 1 2 2 } 9 6
```
### See also
| | |
| --- | --- |
| [std::swap(std::multiset)](swap2 "cpp/container/multiset/swap2") | specializes the `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) |
cpp std::multiset<Key,Compare,Allocator>::max_size std::multiset<Key,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 <set>
int main()
{
std::multiset<char> q;
std::cout.imbue(std::locale("en_US.UTF-8"));
std::cout << "Maximum size of a std::multiset is " << q.max_size() << '\n';
}
```
Possible output:
```
Maximum size of a std::multiset is 576,460,752,303,423,487
```
### See also
| | |
| --- | --- |
| [size](size "cpp/container/multiset/size") | returns the number of elements (public member function) |
cpp std::multiset<Key,Compare,Allocator>::count std::multiset<Key,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/multiset/find") | finds element with specific key (public member function) |
| [equal\_range](equal_range "cpp/container/multiset/equal range") | returns range of elements matching a specific key (public member function) |
cpp std::multiset<Key,Compare,Allocator>::value_comp std::multiset<Key,Compare,Allocator>::value\_comp
=================================================
| | | |
| --- | --- | --- |
|
```
std::multiset::value_compare value_comp() const;
```
| | |
Returns the function object that compares the values. It is the same as `[key\_comp](key_comp "cpp/container/multiset/key comp")`.
### Parameters
(none).
### Return value
The value comparison function object.
### Complexity
Constant.
### Example
```
#include <cassert>
#include <iostream>
#include <set>
// 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::multiset<int, ModCmp> cont{1, 2, 3, 4, 5};
// Same behaviour as key_comp()
auto comp_func = cont.value_comp();
const int val = 100;
for (int key : cont) {
bool before = comp_func(key, val);
bool after = comp_func(val, key);
if (!before && !after)
std::cout << key << " equivalent to key " << val << '\n';
else if (before)
std::cout << key << " goes before key " << val << '\n';
else if (after)
std::cout << key << " goes after key " << val << '\n';
else
assert(0); // Cannot happen
}
}
```
Output:
```
1 goes before key 100
2 goes before key 100
3 equivalent to key 100
4 goes after key 100
5 goes after key 100
```
### See also
| | |
| --- | --- |
| [key\_comp](key_comp "cpp/container/multiset/key comp") | returns the function that compares keys (public member function) |
cpp std::multiset<Key,Compare,Allocator>::find std::multiset<Key,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/multiset/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 <set>
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::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";
}
// transparent comparison demo
std::multiset<FatKey, std::less<>> example2 = { {1, {} }, {2, {} }, {3, {} }, {4, {} } };
LightKey lk = {2};
auto search2 = example2.find(lk);
if (search2 != example2.end()) {
std::cout << "Found " << search2->x << '\n';
} else {
std::cout << "Not found\n";
}
}
```
Output:
```
Found 2
Found 2
```
### See also
| | |
| --- | --- |
| [count](count "cpp/container/multiset/count") | returns the number of elements matching specific key (public member function) |
| [equal\_range](equal_range "cpp/container/multiset/equal range") | returns range of elements matching a specific key (public member function) |
cpp std::multiset<Key,Compare,Allocator>::equal_range std::multiset<Key,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/multiset/lower bound")`, and the second with `[upper\_bound()](upper_bound "cpp/container/multiset/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/multiset/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/multiset/emplace") and unhinted [`insert`](insert "cpp/container/multiset/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/multiset/insert") or [`emplace_hint`](emplace_hint "cpp/container/multiset/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 <set>
#include <iostream>
template <typename I>
void print_equal_range(I first, I lb, I ub, I last) {
for (I i{first}; i != lb; ++i)
std::cout << *i << " ";
std::cout << "[ ";
for (I i{lb}; i != ub; ++i)
std::cout << *i << " ";
std::cout << ") ";
for (I i{ub}; i != last; ++i)
std::cout << *i << " ";
std::cout << '\n';
}
int main()
{
std::multiset<int> c{4, 3, 2, 1, 3, 3};
std::cout << "c = ";
print_equal_range(begin(c), begin(c), end(c), end(c));
for (int key{}; key != 6; ++key) {
std::cout << "key = " << key << "; equal range = ";
const auto [lb, ub] = c.equal_range(key);
print_equal_range(begin(c), lb, ub, end(c));
}
}
```
Output:
```
c = [ 1 2 3 3 3 4 )
key = 0; equal range = [ ) 1 2 3 3 3 4
key = 1; equal range = [ 1 ) 2 3 3 3 4
key = 2; equal range = 1 [ 2 ) 3 3 3 4
key = 3; equal range = 1 2 [ 3 3 3 ) 4
key = 4; equal range = 1 2 3 3 3 [ 4 )
key = 5; equal range = 1 2 3 3 3 4 [ )
```
### See also
| | |
| --- | --- |
| [find](find "cpp/container/multiset/find") | finds element with specific key (public member function) |
| [contains](contains "cpp/container/multiset/contains")
(C++20) | checks if the container contains element with specific key (public member function) |
| [count](count "cpp/container/multiset/count") | returns the number of elements matching specific key (public member function) |
| [upper\_bound](upper_bound "cpp/container/multiset/upper bound") | returns an iterator to the first element *greater* than the given key (public member function) |
| [lower\_bound](lower_bound "cpp/container/multiset/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::multiset<Key,Compare,Allocator>::key_comp std::multiset<Key,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](multiset "cpp/container/multiset/multiset") argument `comp`. It is the same as `[value\_comp](value_comp "cpp/container/multiset/value comp")`.
### Parameters
(none).
### Return value
The key comparison function object.
### Complexity
Constant.
### Example
```
#include <cassert>
#include <iostream>
#include <set>
// 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::multiset<int, ModCmp> cont{1, 2, 3, 4, 5};
auto comp_func = cont.key_comp();
for (int key : cont) {
bool before = comp_func(key, 100);
bool after = comp_func(100, key);
if (!before && !after)
std::cout << key << " equivalent to key 100\n";
else if (before)
std::cout << key << " goes before key 100\n";
else if (after)
std::cout << key << " goes after key 100\n";
else
assert(0); // Cannot happen
}
}
```
Output:
```
1 goes before key 100
2 goes before key 100
3 equivalent to key 100
4 goes after key 100
5 goes after key 100
```
### See also
| | |
| --- | --- |
| [value\_comp](value_comp "cpp/container/multiset/value comp") | returns the function that compares keys in objects of type value\_type (public member function) |
| programming_docs |
cpp std::multiset<Key,Compare,Allocator>::erase std::multiset<Key,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`. Only one overload is provided if `iterator` and `const_iterator` are the same type. (since C++11)
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/multiset/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 `multiset`:
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 <set>
#include <iostream>
int main()
{
std::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();
}
```
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 |
### See also
| | |
| --- | --- |
| [clear](clear "cpp/container/multiset/clear") | clears the contents (public member function) |
cpp std::swap(std::multiset)
std::swap(std::multiset)
========================
| Defined in header `[<set>](../../header/set "cpp/header/set")` | | |
| --- | --- | --- |
|
```
template< class Key, class Compare, class Alloc >
void swap( std::multiset<Key,Compare,Alloc>& lhs,
std::multiset<Key,Compare,Alloc>& rhs );
```
| | (until C++17) |
|
```
template< class Key, class Compare, class Alloc >
void swap( std::multiset<Key,Compare,Alloc>& lhs,
std::multiset<Key,Compare,Alloc>& rhs ) noexcept(/* see below */);
```
| | (since C++17) |
Specializes the `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` algorithm for `[std::multiset](http://en.cppreference.com/w/cpp/container/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 <set>
int main()
{
std::multiset<int> alice{1, 2, 3};
std::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';
}
```
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/multiset/swap") | swaps the contents (public member function) |
cpp std::multiset<Key,Compare,Allocator>::operator= std::multiset<Key,Compare,Allocator>::operator=
===============================================
| | | |
| --- | --- | --- |
|
```
multiset& operator=( const multiset& other );
```
| (1) | |
| | (2) | |
|
```
multiset& operator=( multiset&& other );
```
| (since C++11) (until C++17) |
|
```
multiset& operator=( multiset&& other ) noexcept(/* see below */);
```
| (since C++17) |
|
```
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. | (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/multiset/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::multiset](../multiset "cpp/container/multiset")` to another:
```
#include <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::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);
}
```
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)](multiset "cpp/container/multiset/multiset") | constructs the `multiset` (public member function) |
cpp std::multiset<Key,Compare,Allocator>::rend, std::multiset<Key,Compare,Allocator>::crend std::multiset<Key,Compare,Allocator>::rend, std::multiset<Key,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 `multiset`. It corresponds to the element preceding the first element of the non-reversed `multiset`. 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.
### 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 <set>
int main()
{
std::multiset<unsigned> rep{1, 2, 3, 4, 1, 2, 3, 4};
for (auto it = rep.crbegin(); it != rep.crend(); ++it) {
for (auto n = *it; n > 0; --n)
std::cout << "โผ" << ' ';
std::cout << '\n';
}
}
```
Output:
```
โผ โผ โผ โผ
โผ โผ โผ โผ
โผ โผ โผ
โผ โผ โผ
โผ โผ
โผ โผ
โผ
โผ
```
### See also
| | |
| --- | --- |
| [rbegincrbegin](rbegin "cpp/container/multiset/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::multiset<Key,Compare,Allocator>::clear std::multiset<Key,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/multiset/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 <set>
int main()
{
std::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';
}
```
Output:
```
Before clear: 1 2 3
Size=3
Clear
After clear:
Size=0
```
### See also
| | |
| --- | --- |
| [erase](erase "cpp/container/multiset/erase") | erases elements (public member function) |
cpp std::multiset<Key,Compare,Allocator>::upper_bound std::multiset<Key,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/multiset/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/multiset/equal range") | returns range of elements matching a specific key (public member function) |
| [lower\_bound](lower_bound "cpp/container/multiset/lower bound") | returns an iterator to the first element *not less* than the given key (public member function) |
cpp std::multiset<Key,Compare,Allocator>::~multiset std::multiset<Key,Compare,Allocator>::~multiset
===============================================
| | | |
| --- | --- | --- |
|
```
~multiset();
```
| | |
Destructs the `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 `multiset`.
cpp std::multiset<Key,Compare,Allocator>::empty std::multiset<Key,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::multiset](http://en.cppreference.com/w/cpp/container/multiset)<int>` contains any elements:
```
#include <set>
#include <iostream>
int main()
{
std::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/multiset/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::multiset<Key,Compare,Allocator>::begin, std::multiset<Key,Compare,Allocator>::cbegin std::multiset<Key,Compare,Allocator>::begin, std::multiset<Key,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 `multiset`.
If the `multiset` is empty, the returned iterator will be equal to `[end()](end "cpp/container/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 <set>
#include <string>
int main()
{
const std::multiset<std::string> words = {
"some", "not", "sorted", "words",
"will", "come", "out", "sorted",
};
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
}
}
```
Output:
```
come: 1
not: 1
out: 1
some: 1
sorted: 2
will: 1
words: 1
```
### See also
| | |
| --- | --- |
| [end cend](end "cpp/container/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) |
| programming_docs |
cpp std::multiset<Key,Compare,Allocator>::end, std::multiset<Key,Compare,Allocator>::cend std::multiset<Key,Compare,Allocator>::end, std::multiset<Key,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 `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 <set>
#include <string>
int main()
{
const std::multiset<std::string> words = {
"some", "not", "sorted", "words",
"will", "come", "out", "sorted",
};
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
}
}
```
Output:
```
come: 1
not: 1
out: 1
some: 1
sorted: 2
will: 1
words: 1
```
### See also
| | |
| --- | --- |
| [begin cbegin](begin "cpp/container/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::vector<T,Allocator>::vector std::vector<T,Allocator>::vector
================================
| | | |
| --- | --- | --- |
| | (1) | |
|
```
vector();
```
| (until C++17) |
|
```
vector() noexcept(noexcept(Allocator()));
```
| (since C++17) (until C++20) |
|
```
constexpr vector() noexcept(noexcept(Allocator()));
```
| (since C++20) |
| | (2) | |
|
```
explicit vector( const Allocator& alloc );
```
| (until C++17) |
|
```
explicit vector( const Allocator& alloc ) noexcept;
```
| (since C++17) (until C++20) |
|
```
constexpr explicit vector( const Allocator& alloc ) noexcept;
```
| (since C++20) |
| | (3) | |
|
```
explicit vector( size_type count,
const T& value = T(),
const Allocator& alloc = Allocator());
```
| (until C++11) |
|
```
vector( size_type count,
const T& value,
const Allocator& alloc = Allocator());
```
| (since C++11) (until C++20) |
|
```
constexpr vector( size_type count,
const T& value,
const Allocator& alloc = Allocator());
```
| (since C++20) |
| | (4) | |
|
```
explicit vector( size_type count );
```
| (since C++11) (until C++14) |
|
```
explicit vector( size_type count, const Allocator& alloc = Allocator() );
```
| (since C++14) (until C++20) |
|
```
constexpr explicit vector( size_type count,
const Allocator& alloc = Allocator() );
```
| (since C++20) |
| | (5) | |
|
```
template< class InputIt >
vector( InputIt first, InputIt last,
const Allocator& alloc = Allocator() );
```
| (until C++20) |
|
```
template< class InputIt >
constexpr vector( InputIt first, InputIt last,
const Allocator& alloc = Allocator() );
```
| (since C++20) |
| | (6) | |
|
```
vector( const vector& other );
```
| (until C++20) |
|
```
constexpr vector( const vector& other );
```
| (since C++20) |
| | (7) | |
|
```
vector( const vector& other, const Allocator& alloc );
```
| (since C++11) (until C++20) |
|
```
constexpr vector( const vector& other, const Allocator& alloc );
```
| (since C++20) |
| | (8) | |
|
```
vector( vector&& other );
```
| (since C++11) (until C++17) |
|
```
vector( vector&& other ) noexcept;
```
| (since C++17) (until C++20) |
|
```
constexpr vector( vector&& other ) noexcept;
```
| (since C++20) |
| | (9) | |
|
```
vector( vector&& other, const Allocator& alloc );
```
| (since C++11) (until C++20) |
|
```
constexpr vector( vector&& other, const Allocator& alloc );
```
| (since C++20) |
| | (10) | |
|
```
vector( std::initializer_list<T> init,
const Allocator& alloc = Allocator() );
```
| (since C++11) (until C++20) |
|
```
constexpr vector( std::initializer_list<T> init,
const Allocator& alloc = Allocator() );
```
| (since C++20) |
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 `vector(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`. After the move, `other` is guaranteed to be `[empty()](empty "cpp/container/vector/empty")`.
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. (In that case, `other` is not guaranteed to be empty after the 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).
The overload (4) zeroes out elements of non-class types such as `int`, which is different from the behavior of [`new[]`](../../language/new "cpp/language/new"), which leaves them uninitialized. To match the behavior of `new[]`, a [custom `Allocator::construct`](http://stackoverflow.com/a/21028912/273767) can be provided which leaves such elements uninitialized.
Note that the presence of list-initializing constructor (10) means [list initialization](../../language/list_initialization "cpp/language/list initialization") and [direct initialization](../../language/direct_initialization "cpp/language/direct initialization") do different things:
```
std::vector<int> b{3}; // creates a 1-element vector holding {3}
std::vector<int> a(3); // creates a 3-element vector holding {0, 0, 0}
std::vector<int> d{1, 2}; // creates a 2-element vector holding {1, 2}
std::vector<int> c(1, 2); // creates a 1-element vector holding {2}
```
### Example
```
#include <vector>
#include <string>
#include <iostream>
template<typename T>
std::ostream& operator<<(std::ostream& s, const std::vector<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::vector<std::string> words1 {"the", "frogurt", "is", "also", "cursed"};
std::cout << "words1: " << words1 << '\n';
// words2 == words1
std::vector<std::string> words2(words1.begin(), words1.end());
std::cout << "words2: " << words2 << '\n';
// words3 == words1
std::vector<std::string> words3(words1);
std::cout << "words3: " << words3 << '\n';
// words4 is {"Mo", "Mo", "Mo", "Mo", "Mo"}
std::vector<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/vector/assign") | assigns values to the container (public member function) |
| [operator=](operator= "cpp/container/vector/operator=") | assigns values to the container (public member function) |
cpp std::vector<T,Allocator>::size std::vector<T,Allocator>::size
==============================
| | | |
| --- | --- | --- |
|
```
size_type size() const;
```
| | (until C++11) |
|
```
size_type size() const noexcept;
```
| | (since C++11) (until C++20) |
|
```
constexpr size_type size() const noexcept;
```
| | (since C++20) |
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::vector](http://en.cppreference.com/w/cpp/container/vector)<int>`:
```
#include <vector>
#include <iostream>
int main()
{
std::vector<int> nums {1, 3, 5, 7};
std::cout << "nums contains " << nums.size() << " elements.\n";
}
```
Output:
```
nums contains 4 elements.
```
### See also
| | |
| --- | --- |
| [capacity](capacity "cpp/container/vector/capacity") | returns the number of elements that can be held in currently allocated storage (public member function) |
| [empty](empty "cpp/container/vector/empty") | checks whether the container is empty (public member function) |
| [max\_size](max_size "cpp/container/vector/max size") | returns the maximum possible number of elements (public member function) |
| [resize](resize "cpp/container/vector/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::vector
deduction guides for `std::vector`
==================================
| Defined in header `[<vector>](../../header/vector "cpp/header/vector")` | | |
| --- | --- | --- |
|
```
template< class InputIt,
class Alloc = std::allocator<typename std::iterator_traits<InputIt>::value_type>>
vector(InputIt, InputIt, Alloc = Alloc())
-> vector<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 vector 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 <vector>
int main() {
std::vector<int> v = {1, 2, 3, 4};
// uses explicit deduction guide to deduce std::vector<int>
std::vector x(v.begin(), v.end());
// deduces std::vector<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::vector y{v.begin(), v.end()};
}
```
cpp std::erase, std::erase_if (std::vector)
std::erase, std::erase\_if (std::vector)
========================================
| Defined in header `[<vector>](../../header/vector "cpp/header/vector")` | | |
| --- | --- | --- |
|
```
template< class T, class Alloc, class U >
constexpr typename std::vector<T,Alloc>::size_type
erase( std::vector<T,Alloc>& c, const U& value );
```
| (1) | (since C++20) |
|
```
template< class T, class Alloc, class Pred >
constexpr typename std::vector<T,Alloc>::size_type
erase_if( std::vector<T,Alloc>& c, Pred pred );
```
| (2) | (since C++20) |
1) Erases all elements that compare equal to `value` from the container. Equivalent to
```
auto it = std::remove(c.begin(), c.end(), value);
auto r = std::distance(it, c.end());
c.erase(it, c.end());
return r;
```
2) Erases all elements that satisfy the predicate `pred` from the container. Equivalent to
```
auto it = std::remove_if(c.begin(), c.end(), pred);
auto r = std::distance(it, c.end());
c.erase(it, c.end());
return r;
```
### Parameters
| | | |
| --- | --- | --- |
| c | - | container from which to erase |
| value | - | value to be removed |
| pred | - | unary predicate which returns โ`true` if the element should be erased. The expression `pred(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
The number of erased elements.
### Complexity
Linear.
### Example
```
#include <iostream>
#include <numeric>
#include <string_view>
#include <vector>
void print_container(std::string_view comment, const std::vector<char>& c)
{
std::cout << comment << "{ ";
for (auto x : c) {
std::cout << x << ' ';
}
std::cout << "}\n";
}
int main()
{
std::vector<char> cnt(10);
std::iota(cnt.begin(), cnt.end(), '0');
print_container("Initially, cnt = ", cnt);
std::erase(cnt, '3');
print_container("After erase '3', cnt = ", cnt);
auto erased = std::erase_if(cnt, [](char x) { return (x - '0') % 2 == 0; });
print_container("After erase all even numbers, cnt = ", cnt);
std::cout << "Erased even numbers: " << erased << '\n';
}
```
Output:
```
Initially, cnt = { 0 1 2 3 4 5 6 7 8 9 }
After erase '3', cnt = { 0 1 2 4 5 6 7 8 9 }
After erase all even numbers, cnt = { 1 5 7 9 }
Erased even numbers: 5
```
### See also
| | |
| --- | --- |
| [removeremove\_if](../../algorithm/remove "cpp/algorithm/remove") | removes elements satisfying specific criteria (function template) |
cpp std::vector<T,Allocator>::emplace std::vector<T,Allocator>::emplace
=================================
| | | |
| --- | --- | --- |
|
```
template< class... Args >
iterator emplace( const_iterator pos, Args&&... args );
```
| | (since C++11) (until C++20) |
|
```
template< class... Args >
constexpr iterator emplace( const_iterator pos, Args&&... args );
```
| | (since C++20) |
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.
If the new `[size()](size "cpp/container/vector/size")` is greater than `[capacity()](capacity "cpp/container/vector/capacity")`, all iterators and references are invalidated. Otherwise, only the iterators and references before the insertion point remain valid. The past-the-end iterator is also 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 distance between `pos` and end 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 end and the value type is either [CopyInsertable](../../named_req/copyinsertable "cpp/named req/CopyInsertable") or nothrow move constructible, there are no effects (strong exception guarantee).
Otherwise, the effects are unspecified.
### Example
```
#include <iostream>
#include <string>
#include <vector>
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::vector<A> container;
// reserve enough place so vector does not have to resize
container.reserve(10);
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/vector/insert") | inserts elements (public member function) |
| [emplace\_back](emplace_back "cpp/container/vector/emplace back")
(C++11) | constructs an element in-place at the end (public member function) |
| programming_docs |
cpp std::vector<T,Allocator>::insert std::vector<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) (until C++20) |
|
```
constexpr iterator insert( const_iterator pos, const T& value );
```
| (since C++20) |
| | (2) | |
|
```
iterator insert( const_iterator pos, T&& value );
```
| (since C++11) (until C++20) |
|
```
constexpr iterator insert( const_iterator pos, T&& value );
```
| (since C++20) |
| | (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) (until C++20) |
|
```
constexpr iterator insert( const_iterator pos, size_type count,
const T& value );
```
| (since C++20) |
| | (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) (until C++20) |
|
```
template< class InputIt >
constexpr iterator insert( const_iterator pos,
InputIt first, InputIt last );
```
| (since C++20) |
| | (5) | |
|
```
iterator insert( const_iterator pos, std::initializer_list<T> ilist );
```
| (since C++11) (until C++20) |
|
```
constexpr iterator insert( const_iterator pos,
std::initializer_list<T> ilist );
```
| (since C++20) |
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`. Causes reallocation if the new `[size()](size "cpp/container/vector/size")` is greater than the old `[capacity()](capacity "cpp/container/vector/capacity")`. If the new `[size()](size "cpp/container/vector/size")` is greater than `[capacity()](capacity "cpp/container/vector/capacity")`, all iterators and references are invalidated. Otherwise, only the iterators and references before the insertion point remain valid. The past-the-end iterator is also invalidated.
### Parameters
| | | |
| --- | --- | --- |
| pos | - | iterator before which the content will be inserted. `pos` may be the `[end()](end "cpp/container/vector/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 [MoveAssignable](../../named_req/moveassignable "cpp/named req/MoveAssignable") and [MoveInsertable](../../named_req/moveinsertable "cpp/named req/MoveInsertable") in order to use overload (4). required only if `InputIt` satisfies [LegacyInputIterator](../../named_req/inputiterator "cpp/named req/InputIterator") but not [LegacyForwardIterator](../../named_req/forwarditerator "cpp/named req/ForwardIterator"). (until C++17) |
| -`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 distance between `pos` and end of the container.
3) Linear in `count` plus linear in the distance between `pos` and end of the container.
4) Linear in `[std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(first, last)` plus linear in the distance between `pos` and end of the container.
5) Linear in `ilist.size()` plus linear in the distance between `pos` and end of the container. ### Exceptions
If an exception is thrown when inserting a single element at the end, and T is [CopyInsertable](../../named_req/copyinsertable "cpp/named req/CopyInsertable") or `[std::is\_nothrow\_move\_constructible](http://en.cppreference.com/w/cpp/types/is_move_constructible)<T>::value` is `true`, there are no effects (strong exception guarantee).
### Example
```
#include <iostream>
#include <iterator>
#include <vector>
void print(int id, const std::vector<int>& container)
{
std::cout << id << ". ";
for (const int x: container) {
std::cout << x << ' ';
}
std::cout << '\n';
}
int main ()
{
std::vector<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);
// `it` no longer valid, get a new one:
it = c1.begin();
std::vector<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/vector/emplace")
(C++11) | constructs element in-place (public member function) |
| [push\_back](push_back "cpp/container/vector/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::vector<T,Allocator>::get_allocator std::vector<T,Allocator>::get\_allocator
========================================
| | | |
| --- | --- | --- |
|
```
allocator_type get_allocator() const;
```
| | (until C++11) |
|
```
allocator_type get_allocator() const noexcept;
```
| | (since C++11) (until C++20) |
|
```
constexpr allocator_type get_allocator() const noexcept;
```
| | (since C++20) |
Returns the allocator associated with the container.
### Parameters
(none).
### Return value
The associated allocator.
### Complexity
Constant.
cpp std::vector<T,Allocator>::shrink_to_fit std::vector<T,Allocator>::shrink\_to\_fit
=========================================
| | | |
| --- | --- | --- |
|
```
void shrink_to_fit();
```
| | (since C++11) (until C++20) |
|
```
constexpr void shrink_to_fit();
```
| | (since C++20) |
Requests the removal of unused capacity.
It is a non-binding request to reduce `[capacity()](capacity "cpp/container/vector/capacity")` to `[size()](size "cpp/container/vector/size")`. It depends on the implementation whether the request is fulfilled.
If reallocation occurs, all iterators, including the past the end iterator, and all references to the elements are invalidated. If no reallocation takes place, no iterators or references are 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 <vector>
int main()
{
std::vector<int> v;
std::cout << "Default-constructed capacity is " << v.capacity() << '\n';
v.resize(100);
std::cout << "Capacity of a 100-element vector is " << v.capacity() << '\n';
v.resize(50);
std::cout << "Capacity after resize(50) is " << v.capacity() << '\n';
v.shrink_to_fit();
std::cout << "Capacity after shrink_to_fit() is " << v.capacity() << '\n';
v.clear();
std::cout << "Capacity after clear() is " << v.capacity() << '\n';
v.shrink_to_fit();
std::cout << "Capacity after shrink_to_fit() is " << v.capacity() << '\n';
for (int i = 1000; i < 1300; ++i)
v.push_back(i);
std::cout << "Capacity after adding 300 elements is " << v.capacity() << '\n';
v.shrink_to_fit();
std::cout << "Capacity after shrink_to_fit() is " << v.capacity() << '\n';
}
```
Possible output:
```
Default-constructed capacity is 0
Capacity of a 100-element vector is 100
Capacity after resize(50) is 100
Capacity after shrink_to_fit() is 50
Capacity after clear() is 50
Capacity after shrink_to_fit() is 0
Capacity after adding 300 elements is 512
Capacity after shrink_to_fit() is 300
```
### See also
| | |
| --- | --- |
| [size](size "cpp/container/vector/size") | returns the number of elements (public member function) |
| [capacity](capacity "cpp/container/vector/capacity") | returns the number of elements that can be held in currently allocated storage (public member function) |
cpp std::vector<T,Allocator>::rbegin, std::vector<T,Allocator>::crbegin std::vector<T,Allocator>::rbegin, std::vector<T,Allocator>::crbegin
===================================================================
| | | |
| --- | --- | --- |
|
```
reverse_iterator rbegin();
```
| | (until C++11) |
|
```
reverse_iterator rbegin() noexcept;
```
| | (since C++11) (until C++20) |
|
```
constexpr reverse_iterator rbegin() noexcept;
```
| | (since C++20) |
|
```
const_reverse_iterator rbegin() const;
```
| | (until C++11) |
|
```
const_reverse_iterator rbegin() const noexcept;
```
| | (since C++11) (until C++20) |
|
```
constexpr const_reverse_iterator rbegin() const noexcept;
```
| | (since C++20) |
|
```
const_reverse_iterator crbegin() const noexcept;
```
| | (since C++11) (until C++20) |
|
```
constexpr const_reverse_iterator crbegin() const noexcept;
```
| | (since C++20) |
Returns a reverse iterator to the first element of the reversed `vector`. It corresponds to the last element of the non-reversed `vector`. If the `vector` is empty, the returned iterator is equal to `[rend()](rend "cpp/container/vector/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 <vector>
int main()
{
std::vector<int> nums {1, 2, 4, 8, 16};
std::vector<std::string> fruits {"orange", "apple", "raspberry"};
std::vector<char> empty;
// Print vector.
std::for_each(nums.rbegin(), nums.rend(), [](const int n) { std::cout << n << ' '; });
std::cout << '\n';
// Sums all integers in the vector 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 vector fruits, checking if there is any.
if (!fruits.empty())
std::cout << "First fruit: " << *fruits.rbegin() << '\n';
if (empty.rbegin() == empty.rend())
std::cout << "vector 'empty' is indeed empty.\n";
}
```
Output:
```
16 8 4 2 1
Sum of nums: 31
First fruit: raspberry
vector 'empty' is indeed empty.
```
### See also
| | |
| --- | --- |
| [rendcrend](rend "cpp/container/vector/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::vector<T,Allocator>::at std::vector<T,Allocator>::at
============================
| | | |
| --- | --- | --- |
|
```
reference at( size_type pos );
```
| | (until C++20) |
|
```
constexpr reference at( size_type pos );
```
| | (since C++20) |
|
```
const_reference at( size_type pos ) const;
```
| | (until C++20) |
|
```
constexpr const_reference at( size_type pos ) const;
```
| | (since C++20) |
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 <vector>
int main()
{
std::vector<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
vector::_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/vector/operator at") | access specified element (public member function) |
cpp std::vector<T,Allocator>::operator[] std::vector<T,Allocator>::operator[]
====================================
| | | |
| --- | --- | --- |
|
```
reference operator[]( size_type pos );
```
| | (until C++20) |
|
```
constexpr reference operator[]( size_type pos );
```
| | (since C++20) |
|
```
const_reference operator[]( size_type pos ) const;
```
| | (until C++20) |
|
```
constexpr const_reference operator[]( size_type pos ) const;
```
| | (since C++20) |
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::vector](http://en.cppreference.com/w/cpp/container/vector)<int>`:
```
#include <vector>
#include <iostream>
int main()
{
std::vector<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';
}
// Since C++20 std::vector can be used in constexpr context:
#if defined(__cpp_lib_constexpr_vector) and defined(__cpp_consteval)
// Gets the sum of all primes in [0, N) using sieve of Eratosthenes
consteval auto sum_of_all_primes_up_to(unsigned N) {
if (N < 2) return 0ULL;
std::vector<bool> is_prime(N, true);
is_prime[0] = is_prime[1] = false;
auto propagate_non_primality = [&](decltype(N) n) {
for (decltype(N) m = n + n; m < is_prime.size(); m += n)
is_prime[m] = false;
};
auto sum{0ULL};
for (decltype(N) n{2}; n != N; ++n) {
if (is_prime[n]) {
sum += n;
propagate_non_primality(n);
}
}
return sum;
} //< vector's memory is released here
static_assert(sum_of_all_primes_up_to(42) == 0xEE);
static_assert(sum_of_all_primes_up_to(100) == 0x424);
static_assert(sum_of_all_primes_up_to(1001) == 76127);
#endif
```
Output:
```
Second element: 4
All numbers: 5 4 6 8
```
### See also
| | |
| --- | --- |
| [at](at "cpp/container/vector/at") | access specified element with bounds checking (public member function) |
cpp std::vector<T,Allocator>::swap std::vector<T,Allocator>::swap
==============================
| | | |
| --- | --- | --- |
|
```
void swap( vector& other );
```
| | (until C++17) |
|
```
void swap( vector& other ) noexcept(/* see below */);
```
| | (since C++17) (until C++20) |
|
```
constexpr void swap( vector& other ) noexcept(/* see below */);
```
| | (since C++20) |
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>::propagate\_on\_container\_swap::value || [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 <vector>
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::vector<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::vector)](swap2 "cpp/container/vector/swap2") | specializes the `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) |
| programming_docs |
cpp std::vector<T,Allocator>::max_size std::vector<T,Allocator>::max\_size
===================================
| | | |
| --- | --- | --- |
|
```
size_type max_size() const;
```
| | (until C++11) |
|
```
size_type max_size() const noexcept;
```
| | (since C++11) (until C++20) |
|
```
constexpr size_type max_size() const noexcept;
```
| | (since C++20) |
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 <vector>
int main()
{
std::vector<char> q;
std::cout.imbue(std::locale("en_US.UTF-8"));
std::cout << "Maximum size of a std::vector is " << q.max_size() << '\n';
}
```
Possible output:
```
Maximum size of a std::vector is 9,223,372,036,854,775,807
```
### See also
| | |
| --- | --- |
| [size](size "cpp/container/vector/size") | returns the number of elements (public member function) |
| [capacity](capacity "cpp/container/vector/capacity") | returns the number of elements that can be held in currently allocated storage (public member function) |
cpp std::vector<T,Allocator>::back std::vector<T,Allocator>::back
==============================
| | | |
| --- | --- | --- |
|
```
reference back();
```
| | (until C++20) |
|
```
constexpr reference back();
```
| | (since C++20) |
|
```
const_reference back() const;
```
| | (until C++20) |
|
```
constexpr const_reference back() const;
```
| | (since C++20) |
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::vector](http://en.cppreference.com/w/cpp/container/vector)<char>`:
```
#include <vector>
#include <iostream>
int main()
{
std::vector<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/vector/front") | access the first element (public member function) |
cpp std::vector<T,Allocator>::assign std::vector<T,Allocator>::assign
================================
| | | |
| --- | --- | --- |
| | (1) | |
|
```
void assign( size_type count, const T& value );
```
| (until C++20) |
|
```
constexpr void assign( size_type count, const T& value );
```
| (since C++20) |
| | (2) | |
|
```
template< class InputIt >
void assign( InputIt first, InputIt last );
```
| (until C++20) |
|
```
template< class InputIt >
constexpr void assign( InputIt first, InputIt last );
```
| (since C++20) |
| | (3) | |
|
```
void assign( std::initializer_list<T> ilist );
```
| (since C++11) (until C++20) |
|
```
constexpr void assign( std::initializer_list<T> ilist );
```
| (since C++20) |
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::vector](http://en.cppreference.com/w/cpp/container/vector)<char>`:
```
#include <vector>
#include <iostream>
#include <string>
int main()
{
std::vector<char> characters;
auto print_vector = [&](){
for (char c : characters)
std::cout << c << ' ';
std::cout << '\n';
};
characters.assign(5, 'a');
print_vector();
const std::string extra(6, 'b');
characters.assign(extra.begin(), extra.end());
print_vector();
characters.assign({'C', '+', '+', '1', '1'});
print_vector();
}
```
Output:
```
a a a a a
b b b b b b
C + + 1 1
```
### See also
| | |
| --- | --- |
| [(constructor)](vector "cpp/container/vector/vector") | constructs the `vector` (public member function) |
cpp std::vector<T,Allocator>::data std::vector<T,Allocator>::data
==============================
| | | |
| --- | --- | --- |
|
```
T* data();
```
| | (until C++11) |
|
```
T* data() noexcept;
```
| | (since C++11) (until C++20) |
|
```
constexpr T* data() noexcept;
```
| | (since C++20) |
|
```
const T* data() const;
```
| | (until C++11) |
|
```
const T* data() const noexcept;
```
| | (since C++11) (until C++20) |
|
```
constexpr const T* data() const noexcept;
```
| | (since C++20) |
Returns pointer to the underlying array serving as element storage. The pointer is such that range `[``data(); data()+``[size()](size "cpp/container/vector/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/vector/size")` is `โ0โ`, `data()` may or may not return a null pointer.
### Example
```
#include <cstddef>
#include <iostream>
#include <span>
#include <vector>
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::vector<int> 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
```
### 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 | `vector` did not have this member function | added |
### See also
| | |
| --- | --- |
| [front](front "cpp/container/vector/front") | access the first element (public member function) |
| [back](back "cpp/container/vector/back") | access the last element (public member function) |
| [size](size "cpp/container/vector/size") | 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::vector<T,Allocator>::resize std::vector<T,Allocator>::resize
================================
| | | |
| --- | --- | --- |
| | (1) | |
|
```
void resize( size_type count );
```
| (since C++11) (until C++20) |
|
```
constexpr void resize( size_type count );
```
| (since C++20) |
| | (2) | |
|
```
void resize( size_type count, T value = T() );
```
| (until C++11) |
|
```
void resize( size_type count, const value_type& value );
```
| (since C++11) (until C++20) |
|
```
constexpr void resize( size_type count, const value_type& value );
```
| (since C++20) |
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`. Additional complexity possible due to reallocation if capacity is less than `count`.
### Exceptions
If an exception is thrown, this function has no effect ([strong exception guarantee](../../language/exceptions "cpp/language/exceptions")). Although not explicitly specified, `[std::length\_error](../../error/length_error "cpp/error/length error")` is thrown if the capacity required by the new vector would exceed `[max\_size()](max_size "cpp/container/vector/max size")`.
| | |
| --- | --- |
| In overload (1), if `T`'s move constructor is not `noexcept` and T is not [CopyInsertable](../../named_req/copyinsertable "cpp/named req/CopyInsertable") into `*this`, vector will use the throwing move constructor. If it throws, the guarantee is waived and the effects are unspecified. | (since C++11) |
### 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).
Vector capacity is never reduced when resizing to smaller size because that would invalidate all iterators, rather than only the ones that would be invalidated by the equivalent sequence of `[pop\_back()](pop_back "cpp/container/vector/pop back")` calls.
### Example
```
#include <iostream>
#include <vector>
int main()
{
std::vector<int> c = {1, 2, 3};
std::cout << "The vector 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 vector 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/vector/size") | returns the number of elements (public member function) |
| [insert](insert "cpp/container/vector/insert") | inserts elements (public member function) |
| [erase](erase "cpp/container/vector/erase") | erases elements (public member function) |
cpp std::vector<T,Allocator>::erase std::vector<T,Allocator>::erase
===============================
| | | |
| --- | --- | --- |
| | (1) | |
|
```
iterator erase( iterator pos );
```
| (until C++11) |
|
```
iterator erase( const_iterator pos );
```
| (since C++11) (until C++20) |
|
```
constexpr iterator erase( const_iterator pos );
```
| (since C++20) |
| | (2) | |
|
```
iterator erase( iterator first, iterator last );
```
| (until C++11) |
|
```
iterator erase( const_iterator first, const_iterator last );
```
| (since C++11) (until C++20) |
|
```
constexpr iterator erase( const_iterator first, const_iterator last );
```
| (since C++20) |
Erases the specified elements from the container.
1) Removes the element at `pos`.
2) Removes the elements in the range `[first, last)`. Invalidates iterators and references at or after the point of the erase, including the `[end()](end "cpp/container/vector/end")` iterator.
The iterator `pos` must be valid and dereferenceable. Thus the `[end()](end "cpp/container/vector/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/vector/end")` iterator is returned.
If `last==end()` prior to removal, then the updated `[end()](end "cpp/container/vector/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 assignment operator of T is called the number of times equal to the number of elements in the vector after the erased elements.
### Example
```
#include <vector>
#include <iostream>
void print_container(const std::vector<int>& c)
{
for (int i : c) {
std::cout << i << " ";
}
std::cout << '\n';
}
int main( )
{
std::vector<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::vector<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/vector/clear") | clears the contents (public member function) |
cpp std::vector<T,Allocator>::capacity std::vector<T,Allocator>::capacity
==================================
| | | |
| --- | --- | --- |
|
```
size_type capacity() const;
```
| | (until C++11) |
|
```
size_type capacity() const noexcept;
```
| | (since C++11) (until C++20) |
|
```
constexpr size_type capacity() const noexcept;
```
| | (since C++20) |
Returns the number of elements that the container has currently allocated space for.
### Parameters
(none).
### Return value
Capacity of the currently allocated storage.
### Complexity
Constant.
### Example
```
#include <iomanip>
#include <iostream>
#include <vector>
int main()
{
int sz = 100;
std::vector<int> v;
auto cap = v.capacity();
std::cout << "Initial size: " << v.size() << ", capacity: " << cap << '\n';
std::cout << "\nDemonstrate the capacity's growth policy."
"\nSize: Capacity: Ratio:\n" << std::left;
while (sz-- > 0) {
v.push_back(sz);
if (cap != v.capacity()) {
std::cout << std::setw( 7) << v.size()
<< std::setw(11) << v.capacity()
<< std::setw(10) << v.capacity() / static_cast<float>(cap) << '\n';
cap = v.capacity();
}
}
std::cout << "\nFinal size: " << v.size() << ", capacity: " << v.capacity() << '\n';
}
```
Possible output:
```
Initial size: 0, capacity: 0
Demonstrate the capacity's growth policy.
Size: Capacity: Ratio:
1 1 inf
2 2 2
3 4 2
5 8 2
9 16 2
17 32 2
33 64 2
65 128 2
Final size: 100, capacity: 128
```
### See also
| | |
| --- | --- |
| [size](size "cpp/container/vector/size") | returns the number of elements (public member function) |
| [reserve](reserve "cpp/container/vector/reserve") | reserves storage (public member function) |
cpp std::swap(std::vector)
std::swap(std::vector)
======================
| Defined in header `[<vector>](../../header/vector "cpp/header/vector")` | | |
| --- | --- | --- |
|
```
template< class T, class Alloc >
void swap( std::vector<T,Alloc>& lhs,
std::vector<T,Alloc>& rhs );
```
| | (until C++17) |
|
```
template< class T, class Alloc >
void swap( std::vector<T,Alloc>& lhs,
std::vector<T,Alloc>& rhs ) noexcept(/* see below */);
```
| | (since C++17) (until C++20) |
|
```
template< class T, class Alloc >
constexpr void swap( std::vector<T,Alloc>& lhs,
std::vector<T,Alloc>& rhs ) noexcept(/* see below */);
```
| | (since C++20) |
Specializes the `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` algorithm for `[std::vector](http://en.cppreference.com/w/cpp/container/vector)`. 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 <vector>
int main()
{
std::vector<int> alice{1, 2, 3};
std::vector<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/vector/swap") | swaps the contents (public member function) |
| programming_docs |
cpp std::vector<T,Allocator>::front std::vector<T,Allocator>::front
===============================
| | | |
| --- | --- | --- |
|
```
reference front();
```
| | (until C++20) |
|
```
constexpr reference front();
```
| | (since C++20) |
|
```
const_reference front() const;
```
| | (until C++20) |
|
```
constexpr const_reference front() const;
```
| | (since C++20) |
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::vector](http://en.cppreference.com/w/cpp/container/vector)<char>`:
```
#include <vector>
#include <iostream>
int main()
{
std::vector<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/vector/back") | access the last element (public member function) |
cpp std::vector<T,Allocator>::operator= std::vector<T,Allocator>::operator=
===================================
| | | |
| --- | --- | --- |
| | (1) | |
|
```
vector& operator=( const vector& other );
```
| (until C++20) |
|
```
constexpr vector& operator=( const vector& other );
```
| (since C++20) |
| | (2) | |
|
```
vector& operator=( vector&& other );
```
| (since C++11) (until C++17) |
|
```
vector& operator=( vector&& other ) noexcept(/* see below */);
```
| (since C++17) (until C++20) |
|
```
constexpr vector& operator=( vector&& other ) noexcept(/* see below */);
```
| (since C++20) |
| | (3) | |
|
```
vector& operator=( std::initializer_list<T> ilist );
```
| (since C++11) (until C++20) |
|
```
constexpr vector& operator=( std::initializer_list<T> ilist );
```
| (since C++20) |
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>::propagate\_on\_container\_move\_assignment::value || [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::vector](../vector "cpp/container/vector")` to another:
```
#include <vector>
#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::vector<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)](vector "cpp/container/vector/vector") | constructs the `vector` (public member function) |
| [assign](assign "cpp/container/vector/assign") | assigns values to the container (public member function) |
cpp std::vector<T,Allocator>::rend, std::vector<T,Allocator>::crend std::vector<T,Allocator>::rend, std::vector<T,Allocator>::crend
===============================================================
| | | |
| --- | --- | --- |
|
```
reverse_iterator rend();
```
| | (until C++11) |
|
```
reverse_iterator rend() noexcept;
```
| | (since C++11) (until C++20) |
|
```
constexpr reverse_iterator rend() noexcept;
```
| | (since C++20) |
|
```
const_reverse_iterator rend() const;
```
| | (until C++11) |
|
```
const_reverse_iterator rend() const noexcept;
```
| | (since C++11) (until C++20) |
|
```
constexpr const_reverse_iterator rend() const noexcept;
```
| | (since C++20) |
|
```
const_reverse_iterator crend() const noexcept;
```
| | (since C++11) (until C++20) |
|
```
constexpr const_reverse_iterator crend() const noexcept;
```
| | (since C++20) |
Returns a reverse iterator to the element following the last element of the reversed `vector`. It corresponds to the element preceding the first element of the non-reversed `vector`. 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 <vector>
int main()
{
std::vector<int> nums {1, 2, 4, 8, 16};
std::vector<std::string> fruits {"orange", "apple", "raspberry"};
std::vector<char> empty;
// Print vector.
std::for_each(nums.rbegin(), nums.rend(), [](const int n) { std::cout << n << ' '; });
std::cout << '\n';
// Sums all integers in the vector 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 vector fruits, checking if there is any.
if (!fruits.empty())
std::cout << "First fruit: " << *fruits.rbegin() << '\n';
if (empty.rbegin() == empty.rend())
std::cout << "vector 'empty' is indeed empty.\n";
}
```
Output:
```
16 8 4 2 1
Sum of nums: 31
First fruit: raspberry
vector 'empty' is indeed empty.
```
### See also
| | |
| --- | --- |
| [rbegincrbegin](rbegin "cpp/container/vector/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::vector<T,Allocator>::clear std::vector<T,Allocator>::clear
===============================
| | | |
| --- | --- | --- |
|
```
void clear();
```
| | (until C++11) |
|
```
void clear() noexcept;
```
| | (since C++11) (until C++20) |
|
```
constexpr void clear() noexcept;
```
| | (since C++20) |
Erases all elements from the container. After this call, `[size()](size "cpp/container/vector/size")` returns zero.
Invalidates any references, pointers, or iterators referring to contained elements. Any past-the-end iterators are also invalidated.
Leaves the `[capacity()](capacity "cpp/container/vector/capacity")` of the vector unchanged (note: the standard's restriction on the changes to capacity is in the specification of `vector::reserve`, see [[1]](http://stackoverflow.com/a/18467916)).
### 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 <vector>
int main()
{
std::vector<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() << ", Capacity=" << container.capacity() << '\n';
std::cout << "Clear\n";
container.clear();
std::cout << "After clear:";
std::for_each(container.begin(), container.end(), print);
std::cout << "\nSize=" << container.size() << ", Capacity=" << container.capacity() << '\n';
}
```
Output:
```
Before clear: 1 2 3
Size=3, Capacity=3
Clear
After clear:
Size=0, Capacity=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 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/vector/erase") | erases elements (public member function) |
cpp std::vector<T,Allocator>::push_back std::vector<T,Allocator>::push\_back
====================================
| | | |
| --- | --- | --- |
| | (1) | |
|
```
void push_back( const T& value );
```
| (until C++20) |
|
```
constexpr void push_back( const T& value );
```
| (since C++20) |
| | (2) | |
|
```
void push_back( T&& value );
```
| (since C++11) (until C++20) |
|
```
constexpr void push_back( T&& value );
```
| (since C++20) |
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. If the new `[size()](size "cpp/container/vector/size")` is greater than `[capacity()](capacity "cpp/container/vector/capacity")` then all iterators and references (including the past-the-end iterator) are invalidated. Otherwise only the past-the-end iterator is 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
Amortized 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")).
| | |
| --- | --- |
| If `T`'s move constructor is not `noexcept` and T is not [CopyInsertable](../../named_req/copyinsertable "cpp/named req/CopyInsertable") into `*this`, vector will use the throwing move constructor. If it throws, the guarantee is waived and the effects are unspecified. | (since C++11) |
### Notes
Calling `push_back` will cause reallocation (when `[size](size "cpp/container/vector/size")``()+1 >` `[capacity](capacity "cpp/container/vector/capacity")``()`), so some implementations also throw `[std::length\_error](../../error/length_error "cpp/error/length error")` when `push_back` causes a reallocation that would exceed `[max\_size](max_size "cpp/container/vector/max size")` (due to implicitly calling an equivalent of `[reserve](reserve "cpp/container/vector/reserve")``(``[size](size "cpp/container/vector/size")``()+1))`.
### Example
```
#include <vector>
#include <iostream>
#include <iomanip>
#include <string>
int main()
{
std::vector<std::string> letters;
letters.push_back("abc");
std::string s{"def"};
letters.push_back(std::move(s));
std::cout << "std::vector `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::vector `letters` holds: "abc" "def"
Moved-from string `s` holds: ""
```
### See also
| | |
| --- | --- |
| [emplace\_back](emplace_back "cpp/container/vector/emplace back")
(C++11) | constructs an element in-place at the end (public member function) |
| [pop\_back](pop_back "cpp/container/vector/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) |
cpp std::vector<T,Allocator>::~vector std::vector<T,Allocator>::~vector
=================================
| | | |
| --- | --- | --- |
|
```
~vector();
```
| | (until C++20) |
|
```
constexpr ~vector();
```
| | (since C++20) |
Destructs the `vector`. 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 `vector`.
cpp std::vector<T,Allocator>::reserve std::vector<T,Allocator>::reserve
=================================
| | | |
| --- | --- | --- |
|
```
void reserve( size_type new_cap );
```
| | (until C++20) |
|
```
constexpr void reserve( size_type new_cap );
```
| | (since C++20) |
Increase the capacity of the vector (the total number of elements that the vector can hold without requiring reallocation) to a value that's greater or equal to `new_cap`. If `new_cap` is greater than the current `[capacity()](capacity "cpp/container/vector/capacity")`, new storage is allocated, otherwise the function does nothing.
`reserve()` does not change the size of the vector.
If `new_cap` is greater than `[capacity()](capacity "cpp/container/vector/capacity")`, all iterators, including the past-the-end iterator, and all references to the elements are invalidated. Otherwise, no iterators or references are invalidated.
### Parameters
| | | |
| --- | --- | --- |
| new\_cap | - | new capacity of the vector, in number of elements |
| Type requirements |
| -`T` must meet the requirements of [MoveInsertable](../../named_req/moveinsertable "cpp/named req/MoveInsertable"). |
### Return value
(none).
### Exceptions
* `[std::length\_error](../../error/length_error "cpp/error/length error")` if `new_cap > max_size()`.
* any exception thrown by `Allocator::allocate()` (typically `[std::bad\_alloc](../../memory/new/bad_alloc "cpp/memory/new/bad alloc")`)
If an exception is thrown, this function has no effect ([strong exception guarantee](../../language/exceptions#Exception_safety "cpp/language/exceptions")).
| | |
| --- | --- |
| If `T`'s move constructor is not `noexcept` and T is not [CopyInsertable](../../named_req/copyinsertable "cpp/named req/CopyInsertable") into `*this`, vector will use the throwing move constructor. If it throws, the guarantee is waived and the effects are unspecified. | (since C++11) |
### Complexity
At most linear in the `[size()](size "cpp/container/vector/size")` of the container.
### Notes
Correctly using `reserve()` can prevent unnecessary reallocations, but inappropriate uses of `reserve()` (for instance, calling it before every `[push\_back()](push_back "cpp/container/vector/push back")` call) may actually increase the number of reallocations (by causing the capacity to grow linearly rather than exponentially) and result in increased computational complexity and decreased performance. For example, a function that receives an arbitrary vector by reference and appends elements to it should usually *not* call `reserve()` on the vector, since it does not know of the vector's usage characteristics.
When inserting a range, the range version of `[insert()](insert "cpp/container/vector/insert")` is generally preferable as it preserves the correct capacity growth behavior, unlike `reserve()` followed by a series of `[push\_back()](push_back "cpp/container/vector/push back")`s.
`reserve()` cannot be used to reduce the capacity of the container; to that end `[shrink\_to\_fit()](shrink_to_fit "cpp/container/vector/shrink to fit")` is provided.
### Example
```
#include <cstddef>
#include <iostream>
#include <new>
#include <vector>
// 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);
Tp* p = static_cast<Tp*>(::operator new(n));
std::cout << "allocating " << n << " bytes @ " << p << '\n';
return p;
}
void deallocate(Tp* p, std::size_t n)
{
std::cout << "deallocating " << n*sizeof*p << " bytes @ " << p << "\n\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()
{
constexpr int max_elements = 32;
std::cout << "using reserve: \n";
{
std::vector<int, NAlloc<int>> v1;
v1.reserve( max_elements ); // reserves at least max_elements * sizeof(int) bytes
for(int n = 0; n < max_elements; ++n)
v1.push_back(n);
}
std::cout << "not using reserve: \n";
{
std::vector<int, NAlloc<int>> v1;
for(int n = 0; n < max_elements; ++n) {
if(v1.size() == v1.capacity()) {
std::cout << "size() == capacity() == " << v1.size() << '\n';
}
v1.push_back(n);
}
}
}
```
Possible output:
```
using reserve:
allocating 128 bytes @ 0xa6f840
deallocating 128 bytes @ 0xa6f840
not using reserve:
size() == capacity() == 0
allocating 4 bytes @ 0xa6f840
size() == capacity() == 1
allocating 8 bytes @ 0xa6f860
deallocating 4 bytes @ 0xa6f840
size() == capacity() == 2
allocating 16 bytes @ 0xa6f840
deallocating 8 bytes @ 0xa6f860
size() == capacity() == 4
allocating 32 bytes @ 0xa6f880
deallocating 16 bytes @ 0xa6f840
size() == capacity() == 8
allocating 64 bytes @ 0xa6f8b0
deallocating 32 bytes @ 0xa6f880
size() == capacity() == 16
allocating 128 bytes @ 0xa6f900
deallocating 64 bytes @ 0xa6f8b0
deallocating 128 bytes @ 0xa6f900
```
### See also
| | |
| --- | --- |
| [capacity](capacity "cpp/container/vector/capacity") | returns the number of elements that can be held in currently allocated storage (public member function) |
| [max\_size](max_size "cpp/container/vector/max size") | returns the maximum possible number of elements (public member function) |
| [resize](resize "cpp/container/vector/resize") | changes the number of elements stored (public member function) |
| [shrink\_to\_fit](shrink_to_fit "cpp/container/vector/shrink to fit")
(C++11) | reduces memory usage by freeing unused memory (public member function) |
| programming_docs |
cpp std::vector<T,Allocator>::empty std::vector<T,Allocator>::empty
===============================
| | | |
| --- | --- | --- |
|
```
bool empty() const;
```
| | (until C++11) |
|
```
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
```
#include <vector>
#include <iostream>
int main()
{
std::cout << std::boolalpha;
std::vector<int> numbers;
std::cout << "Initially, numbers.empty(): " << numbers.empty() << '\n';
numbers.push_back(42);
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/vector/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::vector<T,Allocator>::begin, std::vector<T,Allocator>::cbegin std::vector<T,Allocator>::begin, std::vector<T,Allocator>::cbegin
=================================================================
| | | |
| --- | --- | --- |
|
```
iterator begin();
```
| | (until C++11) |
|
```
iterator begin() noexcept;
```
| | (since C++11) (until C++20) |
|
```
constexpr iterator begin() noexcept;
```
| | (since C++20) |
|
```
const_iterator begin() const;
```
| | (until C++11) |
|
```
const_iterator begin() const noexcept;
```
| | (since C++11) (until C++20) |
|
```
constexpr const_iterator begin() const noexcept;
```
| | (since C++20) |
|
```
const_iterator cbegin() const noexcept;
```
| | (since C++11) (until C++20) |
|
```
constexpr const_iterator cbegin() const noexcept;
```
| | (since C++20) |
Returns an iterator to the first element of the `vector`.
If the `vector` is empty, the returned iterator will be equal to `[end()](end "cpp/container/vector/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 <vector>
int main()
{
std::vector<int> nums {1, 2, 4, 8, 16};
std::vector<std::string> fruits {"orange", "apple", "raspberry"};
std::vector<char> empty;
// Print vector.
std::for_each(nums.begin(), nums.end(), [](const int n) { std::cout << n << ' '; });
std::cout << '\n';
// Sums all integers in the vector 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 vector fruits, checking if there is any.
if (!fruits.empty())
std::cout << "First fruit: " << *fruits.begin() << '\n';
if (empty.begin() == empty.end())
std::cout << "vector 'empty' is indeed empty.\n";
}
```
Output:
```
1 2 4 8 16
Sum of nums: 31
First fruit: orange
vector 'empty' is indeed empty.
```
### See also
| | |
| --- | --- |
| [end cend](end "cpp/container/vector/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::vector<T,Allocator>::emplace_back std::vector<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) (until C++20) |
|
```
template< class... Args >
constexpr reference emplace_back( Args&&... args );
```
| | (since C++20) |
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)...`.
If the new `[size()](size "cpp/container/vector/size")` is greater than `[capacity()](capacity "cpp/container/vector/capacity")` then all iterators and references (including the past-the-end iterator) are invalidated. Otherwise only the past-the-end iterator is 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 [MoveInsertable](../../named_req/moveinsertable "cpp/named req/MoveInsertable") and [EmplaceConstructible](../../named_req/emplaceconstructible "cpp/named req/EmplaceConstructible"). |
### Return value
| | |
| --- | --- |
| (none). | (until C++17) |
| A reference to the inserted element. | (since C++17) |
### Complexity
Amortized constant.
### Exceptions
If an exception is thrown, this function has no effect (strong exception guarantee). If `T`'s move constructor is not `noexcept` and is not [CopyInsertable](../../named_req/copyinsertable "cpp/named req/CopyInsertable") into `*this`, vector will use the throwing move constructor. If it throws, the guarantee is waived and the effects are unspecified.
### Notes
Since reallocation may take place, `emplace_back` requires the element type to be [MoveInsertable](../../named_req/moveinsertable "cpp/named req/MoveInsertable") for vectors.
### Example
The following code uses `emplace_back` to append an object of type `President` to a `[std::vector](http://en.cppreference.com/w/cpp/container/vector)`. 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 <vector>
#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::vector<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::vector<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/vector/push back") | adds an element to the end (public member function) |
| [emplace](emplace "cpp/container/vector/emplace")
(C++11) | constructs element in-place (public member function) |
cpp std::vector<T,Allocator>::end, std::vector<T,Allocator>::cend std::vector<T,Allocator>::end, std::vector<T,Allocator>::cend
=============================================================
| | | |
| --- | --- | --- |
|
```
iterator end();
```
| | (until C++11) |
|
```
iterator end() noexcept;
```
| | (since C++11) (until C++20) |
|
```
constexpr iterator end() noexcept;
```
| | (since C++20) |
|
```
const_iterator end() const;
```
| | (until C++11) |
|
```
const_iterator end() const noexcept;
```
| | (since C++11) (until C++20) |
|
```
constexpr const_iterator end() const noexcept;
```
| | (since C++20) |
|
```
const_iterator cend() const noexcept;
```
| | (since C++11) (until C++20) |
|
```
constexpr const_iterator cend() const noexcept;
```
| | (since C++20) |
Returns an iterator to the element following the last element of the `vector`.
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 <vector>
int main()
{
std::vector<int> nums {1, 2, 4, 8, 16};
std::vector<std::string> fruits {"orange", "apple", "raspberry"};
std::vector<char> empty;
// Print vector.
std::for_each(nums.begin(), nums.end(), [](const int n) { std::cout << n << ' '; });
std::cout << '\n';
// Sums all integers in the vector 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 vector fruits, checking if there is any.
if (!fruits.empty())
std::cout << "First fruit: " << *fruits.begin() << '\n';
if (empty.begin() == empty.end())
std::cout << "vector 'empty' is indeed empty.\n";
}
```
Output:
```
1 2 4 8 16
Sum of nums: 31
First fruit: orange
vector 'empty' is indeed empty.
```
### See also
| | |
| --- | --- |
| [begin cbegin](begin "cpp/container/vector/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::vector<T,Allocator>::pop_back std::vector<T,Allocator>::pop\_back
===================================
| | | |
| --- | --- | --- |
|
```
void pop_back();
```
| | (until C++20) |
|
```
constexpr void pop_back();
```
| | (since C++20) |
Removes the last element of the container.
Calling `pop_back` on an empty container results in undefined behavior.
Iterators and references to the last element, as well as the `[end()](end "cpp/container/vector/end")` iterator, are invalidated.
### Parameters
(none).
### Return value
(none).
### Complexity
Constant.
### Exceptions
Throws nothing.
### Example
```
#include <vector>
#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::vector<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
| | |
| --- | --- |
| [push\_back](push_back "cpp/container/vector/push back") | adds an element to the end (public member function) |
cpp std::indirectly_writable std::indirectly\_writable
=========================
| Defined in header `[<iterator>](../header/iterator "cpp/header/iterator")` | | |
| --- | --- | --- |
|
```
template<class Out, class T>
concept indirectly_writable =
requires(Out&& o, T&& t) {
*o = std::forward<T>(t);
*std::forward<Out>(o) = std::forward<T>(t);
const_cast<const std::iter_reference_t<Out>&&>(*o) = std::forward<T>(t);
const_cast<const std::iter_reference_t<Out>&&>(*std::forward<Out>(o)) =
std::forward<T>(t);
};
// none of the four expressions above are required to be equality-preserving
```
| | (since C++20) |
The concept `indirectly_writable<Out, T>` specifies the requirements for writing a value whose type and value category are encoded by `T` into an iterator `Out`'s referenced object.
### Semantic requirements
Let `e` be an expression such that `decltype((e))` is `T`, and `o` be a dereferenceable object of type `Out`, then `indirectly_writable<Out, T>` is modeled only if:
* If `[std::indirectly\_readable](http://en.cppreference.com/w/cpp/iterator/indirectly_readable)<Out>` is modeled and `[std::iter\_value\_t](http://en.cppreference.com/w/cpp/iterator/iter_t)<Out>` is the same type as `[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<T>`, then `*o` after any above assignment is equal to the value of `e` before the assignment.
`o` is not required to be dereferenceable after evaluating any of the assignment expressions above. If `e` is an xvalue, the resulting state of the object it denotes is valid but unspecified.
### Equality preservation
An expression is *equality preserving* if it results in equal outputs given equal inputs.
* The inputs to an expression consist of its operands.
* The outputs of an expression consist of its result and all operands modified by the expression (if any).
In specification of standard concepts, operands are defined as the largest subexpressions that include only:
* an [id-expression](../language/expressions#Primary_expressions "cpp/language/expressions"), and
* invocations of [`std::move`](../utility/move "cpp/utility/move"), `[std::forward](../utility/forward "cpp/utility/forward")`, and `[std::declval](../utility/declval "cpp/utility/declval")`.
The cv-qualification and value category of each operand is determined by assuming that each template type parameter denotes a cv-unqualified complete non-array object type.
Every expression required to be equality preserving is further required to be *stable*: two evaluations of such an expression with the same input objects must have equal outputs absent any explicit intervening modification of those input objects.
### Notes
The only valid use of `operator*` is on the left side of an assignment expression. Assignment through the same value of an indirectly writable type may happen only once.
The required expressions with `const_cast` prevent [`indirectly_readable`](indirectly_readable "cpp/iterator/indirectly readable") objects with prvalue `reference` types from satisfying the syntactic requirements of `indirectly_writable` by accident, while permitting proxy references to continue to work as long as their constness is shallow. See [Ranges TS issue 381](https://github.com/ericniebler/stl2/issues/381).
cpp std::iterator_traits std::iterator\_traits
=====================
| Defined in header `[<iterator>](../header/iterator "cpp/header/iterator")` | | |
| --- | --- | --- |
|
```
template< class Iter >
struct iterator_traits;
```
| | |
|
```
template< class T >
struct iterator_traits<T*>;
```
| | |
|
```
template< class T >
struct iterator_traits<const T*>;
```
| | (removed in C++20) |
`std::iterator_traits` is the type trait class that provides uniform interface to the properties of [LegacyIterator](../named_req/iterator "cpp/named req/Iterator") types. This makes it possible to implement algorithms only in terms of iterators.
The template can be specialized for user-defined iterators so that the information about the iterator can be retrieved even if the type does not provide the usual typedefs.
| | |
| --- | --- |
| User specializations may define the member type `iterator_concept` to one of [iterator category tags](iterator_tags "cpp/iterator/iterator tags"), to indicate conformance to the iterator concepts. | (since C++20) |
### Template parameters
| | | |
| --- | --- | --- |
| Iter | - | the iterator type to retrieve properties for |
### Member types
| Member type | Definition |
| --- | --- |
| `difference_type` | `Iter::difference_type` |
| `value_type` | `Iter::value_type` |
| `pointer` | `Iter::pointer` |
| `reference` | `Iter::reference` |
| `iterator_category` | `Iter::iterator_category` |
| | |
| --- | --- |
| If `Iter` does not have all five member types `difference_type`, `value_type`, `pointer`, `reference`, and `iterator_category`, then this template has no members by any of those names (`std::iterator_traits` is SFINAE-friendly). | (since C++17)(until C++20) |
| If `Iter` does not have `pointer`, but has all four remaining member types, then the member types are declared as follows:
| Member type | Definition |
| --- | --- |
| `difference_type` | `Iter::difference_type` |
| `value_type` | `Iter::value_type` |
| `pointer` | `void` |
| `reference` | `Iter::reference` |
| `iterator_category` | `Iter::iterator_category` |
Otherwise, if `Iter` satisfies the exposition-only concept [`__LegacyInputIterator`](../named_req/inputiterator#Concept "cpp/named req/InputIterator"), the member types are declared as follows:
| Member type | Definition |
| --- | --- |
| `difference_type` | `[std::incrementable\_traits](http://en.cppreference.com/w/cpp/iterator/incrementable_traits)<Iter>::difference\_type` |
| `value_type` | `[std::indirectly\_readable\_traits](http://en.cppreference.com/w/cpp/iterator/indirectly_readable_traits)<Iter>::value\_type` |
| `pointer` | `Iter::pointer` if valid, otherwise `decltype([std::declval](http://en.cppreference.com/w/cpp/utility/declval)<Iter&>().operator->())` if valid, otherwise `void` |
| `reference` | `Iter::reference` if valid, otherwise `[std::iter\_reference\_t](http://en.cppreference.com/w/cpp/iterator/iter_t)<Iter>` |
| `iterator_category` | `Iter::iterator_category` if valid, otherwise, `[std::random\_access\_iterator\_tag](iterator_tags "cpp/iterator/iterator tags")` if `Iter` satisfies [`__LegacyRandomAccessIterator`](../named_req/randomaccessiterator#Concept "cpp/named req/RandomAccessIterator"), otherwise, `[std::bidirectional\_iterator\_tag](iterator_tags "cpp/iterator/iterator tags")` if `Iter` satisfies [`__LegacyBidirectionalIterator`](../named_req/bidirectionaliterator#Concept "cpp/named req/BidirectionalIterator"), otherwise, `[std::forward\_iterator\_tag](iterator_tags "cpp/iterator/iterator tags")` if `Iter` satisfies [`__LegacyForwardIterator`](../named_req/forwarditerator#Concept "cpp/named req/ForwardIterator"), otherwise, `[std::input\_iterator\_tag](iterator_tags "cpp/iterator/iterator tags")`. |
Otherwise, if `Iter` satisfies the exposition-only concept [`__LegacyIterator`](../named_req/iterator#Concept "cpp/named req/Iterator"), the member types are declared as follows:
| Member type | Definition |
| --- | --- |
| `difference_type` | `[std::incrementable\_traits](http://en.cppreference.com/w/cpp/iterator/incrementable_traits)<Iter>::difference\_type` if valid, otherwise `void` |
| `value_type` | `void` |
| `pointer` | `void` |
| `reference` | `void` |
| `iterator_category` | `std::output_iterator_tag` |
Otherwise, this template has no members by any of those names (`std::iterator_traits` is SFINAE-friendly). | (since C++20) |
### Specializations
This type trait may be specialized for user-provided types that may be used as iterators. The standard library provides partial specializations for pointer types `T*`, which makes it possible to use all iterator-based algorithms with raw pointers.
| | |
| --- | --- |
| The standard library also provides partial specializations for some standard iterator adaptors. | (since C++20) |
#### `T*` specialization member types
| | |
| --- | --- |
| Only specialized if `[std::is\_object\_v](http://en.cppreference.com/w/cpp/types/is_object)<T>` is true. | (since C++20) |
| Member type | Definition |
| --- | --- |
| `difference_type` | `[std::ptrdiff\_t](../types/ptrdiff_t "cpp/types/ptrdiff t")` |
| `value_type` | `T` (until C++20)`[std::remove\_cv\_t](http://en.cppreference.com/w/cpp/types/remove_cv)<T>` (since C++20) |
| `pointer` | `T*` |
| `reference` | `T&` |
| `iterator_category` | `[std::random\_access\_iterator\_tag](iterator_tags "cpp/iterator/iterator tags")` |
| `iterator_concept`(C++20) | `[std::contiguous\_iterator\_tag](iterator_tags "cpp/iterator/iterator tags")` |
| | | | | | | | | | | | | | |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| `const T*` specialization member types
| Member type | Definition |
| --- | --- |
| `difference_type` | `[std::ptrdiff\_t](../types/ptrdiff_t "cpp/types/ptrdiff t")` |
| `value_type` | `T` |
| `pointer` | `const T*` |
| `reference` | `const T&` |
| `iterator_category` | `[std::random\_access\_iterator\_tag](iterator_tags "cpp/iterator/iterator tags")` |
| (until C++20) |
#### Specializations for library types
| | |
| --- | --- |
| [std::iterator\_traits<std::common\_iterator>](common_iterator/iterator_traits "cpp/iterator/common iterator/iterator traits")
(C++20) | provides uniform interface to the properties of the `[std::common\_iterator](common_iterator "cpp/iterator/common iterator")` type (class template specialization) |
| [std::iterator\_traits<std::counted\_iterator>](counted_iterator/iterator_traits "cpp/iterator/counted iterator/iterator traits")
(C++20) | provides uniform interface to the properties of the `[std::counted\_iterator](counted_iterator "cpp/iterator/counted iterator")` type (class template specialization) |
### Example
Shows a general-purpose `[std::reverse](http://en.cppreference.com/w/cpp/algorithm/reverse)()` implementation for bidirectional iterators.
```
#include <iostream>
#include <iterator>
#include <vector>
#include <list>
template<class BidirIt>
void my_reverse(BidirIt first, BidirIt last)
{
typename std::iterator_traits<BidirIt>::difference_type n = std::distance(first, last);
for (--n; n > 0; n -= 2) {
typename std::iterator_traits<BidirIt>::value_type tmp = *first;
*first++ = *--last;
*last = tmp;
}
}
int main()
{
std::vector<int> v{1, 2, 3, 4, 5};
my_reverse(v.begin(), v.end());
for (int n : v) {
std::cout << n << ' ';
}
std::cout << '\n';
std::list<int> l{1, 2, 3, 4, 5};
my_reverse(l.begin(), l.end());
for (int n : l) {
std::cout << n << ' ';
}
std::cout << '\n';
int a[] = {1, 2, 3, 4, 5};
my_reverse(a, a + std::size(a));
for (int n : a) {
std::cout << n << ' ';
}
std::cout << '\n';
// std::istreambuf_iterator<char> i1(std::cin), i2;
// my_reverse(i1, i2); // compilation error
}
```
Output:
```
5 4 3 2 1
5 4 3 2 1
5 4 3 2 1
```
### See also
| | |
| --- | --- |
| [iterator](iterator "cpp/iterator/iterator")
(deprecated in C++17) | base class to ease the definition of required types for simple iterators (class template) |
| [input\_iterator\_tagoutput\_iterator\_tagforward\_iterator\_tagbidirectional\_iterator\_tagrandom\_access\_iterator\_tagcontiguous\_iterator\_tag](iterator_tags "cpp/iterator/iterator tags")
(C++20) | empty class types used to indicate iterator categories (class) |
| [iter\_value\_titer\_reference\_titer\_const\_reference\_titer\_difference\_titer\_rvalue\_reference\_titer\_common\_reference\_t](iter_t "cpp/iterator/iter t")
(C++20)(C++20)(C++23)(C++20)(C++20)(C++20) | computes the associated types of an iterator (alias template) |
| programming_docs |
cpp std::size, std::ssize std::size, std::ssize
=====================
| Defined in header `[<array>](../header/array "cpp/header/array")` | | |
| --- | --- | --- |
| Defined in header `[<deque>](../header/deque "cpp/header/deque")` | | |
| Defined in header `[<forward\_list>](../header/forward_list "cpp/header/forward list")` | | |
| Defined in header `[<iterator>](../header/iterator "cpp/header/iterator")` | | |
| Defined in header `[<list>](../header/list "cpp/header/list")` | | |
| Defined in header `[<map>](../header/map "cpp/header/map")` | | |
| Defined in header `[<regex>](../header/regex "cpp/header/regex")` | | |
| Defined in header `[<set>](../header/set "cpp/header/set")` | | |
| Defined in header `[<span>](../header/span "cpp/header/span")` | | (since C++20) |
| Defined in header `[<string>](../header/string "cpp/header/string")` | | |
| Defined in header `[<string\_view>](../header/string_view "cpp/header/string view")` | | |
| Defined in header `[<unordered\_map>](../header/unordered_map "cpp/header/unordered map")` | | |
| Defined in header `[<unordered\_set>](../header/unordered_set "cpp/header/unordered set")` | | |
| Defined in header `[<vector>](../header/vector "cpp/header/vector")` | | |
|
```
template< class C >
constexpr auto size( const C& c ) -> decltype(c.size());
```
| (1) | (since C++17) |
|
```
template< class C >
constexpr auto ssize( const C& c )
-> std::common_type_t<std::ptrdiff_t,
std::make_signed_t<decltype(c.size())>>;
```
| (2) | (since C++20) |
|
```
template< class T, std::size_t N >
constexpr std::size_t size( const T (&array)[N] ) noexcept;
```
| (3) | (since C++17) |
|
```
template< class T, std::ptrdiff_t N >
constexpr std::ptrdiff_t ssize( const T (&array)[N] ) noexcept;
```
| (4) | (since C++20) |
Returns the size of the given range.
1-2) Returns `c.size()`, converted to the return type if necessary.
3-4) Returns `N`. ### Parameters
| | | |
| --- | --- | --- |
| c | - | a container or view with a `size` member function |
| array | - | an array of arbitrary type |
### Return value
The size of `c` or `array`.
### Exceptions
1-2) May throw implementation-defined exceptions. ### Overloads
Custom overloads of `size` may be provided for classes and enumerations that do not expose a suitable `size()` member function, yet can be detected.
| | |
| --- | --- |
| Overloads of `size` found by [argument-dependent lookup](../language/adl "cpp/language/adl") can be used to customize the behavior of `std::[ranges::size](http://en.cppreference.com/w/cpp/ranges/size)`, `std::[ranges::ssize](http://en.cppreference.com/w/cpp/ranges/ssize)`, and `std::[ranges::empty](http://en.cppreference.com/w/cpp/ranges/empty)`. | (since C++20) |
### Possible implementation
| First version |
| --- |
|
```
template <class C>
constexpr auto size(const C& c) -> decltype(c.size())
{
return c.size();
}
```
|
| Second version |
|
```
template <class C>
constexpr auto ssize(const C& c)
-> std::common_type_t<std::ptrdiff_t,
std::make_signed_t<decltype(c.size())>>
{
using R = std::common_type_t<std::ptrdiff_t,
std::make_signed_t<decltype(c.size())>>;
return static_cast<R>(c.size());
}
```
|
| Third version |
|
```
template <class T, std::size_t N>
constexpr std::size_t size(const T (&array)[N]) noexcept
{
return N;
}
```
|
| Fourth version |
|
```
template <class T, std::ptrdiff_t N>
constexpr std::ptrdiff_t ssize(const T (&array)[N]) noexcept
{
return N;
}
```
|
### Notes
| [Feature-test](../utility/feature_test "cpp/utility/feature test") macro | Value | Std | Comment |
| --- | --- | --- | --- |
| [`__cpp_lib_nonmember_container_access`](../feature_test#Library_features "cpp/feature test") | `201411L` | (C++17) | for `std::size()` |
| [`__cpp_lib_ssize`](../feature_test#Library_features "cpp/feature test") | `201902L` | (C++20) | for `std::ssize()` |
### Example
```
#include <iostream>
#include <vector>
int main()
{
std::vector<int> v = { 3, 1, 4 };
std::cout << std::size(v) << '\n';
int a[] = { -5, 10, 15 };
std::cout << std::size(a) << '\n';
// since C++20 the signed size (ssize) is available
auto i = std::ssize(v);
for (--i; i != -1; --i) {
std::cout << v[i] << (i ? ' ' : '\n');
}
std::cout << "i = " << i << '\n';
}
```
Output:
```
3
3
4 1 3
i = -1
```
### See also
| | |
| --- | --- |
| [ptrdiff\_t](../types/ptrdiff_t "cpp/types/ptrdiff t") | signed integer type returned when subtracting two pointers (typedef) |
| [size\_t](../types/size_t "cpp/types/size t") | unsigned integer type returned by the [`sizeof`](../language/sizeof "cpp/language/sizeof") operator (typedef) |
| [ranges::size](../ranges/size "cpp/ranges/size")
(C++20) | returns an integer equal to the size of a range (customization point object) |
| [ranges::ssize](../ranges/ssize "cpp/ranges/ssize")
(C++20) | returns a signed integer equal to the size of a range (customization point object) |
cpp std::counted_iterator std::counted\_iterator
======================
| Defined in header `[<iterator>](../header/iterator "cpp/header/iterator")` | | |
| --- | --- | --- |
|
```
template< std::input_or_output_iterator I >
class counted_iterator;
```
| | (since C++20) |
`std::counted_iterator` is an iterator adaptor which behaves exactly like the underlying iterator, except that it keeps track of the distance to the end of its range. This iterator is equal to `[std::default\_sentinel](default_sentinel_t "cpp/iterator/default sentinel t")` if and only if its count reaches zero.
### Member types
| Member type | Definition |
| --- | --- |
| `iterator_type` | `I` |
| `value_type` | `[std::iter\_value\_t](http://en.cppreference.com/w/cpp/iterator/iter_t)<I>` If `I` models [`indirectly_readable`](indirectly_readable "cpp/iterator/indirectly readable"); otherwise, not defined |
| `difference_type` | `[std::iter\_difference\_t](http://en.cppreference.com/w/cpp/iterator/iter_t)<I>` |
| `iterator_concept` | `I::iterator_concept` if present; otherwise, not defined |
| `iterator_category` | `I::iterator_category` if present; otherwise, not defined |
### Member functions
| | |
| --- | --- |
| [(constructor)](counted_iterator/counted_iterator "cpp/iterator/counted iterator/counted iterator")
(C++20) | constructs a new iterator adaptor (public member function) |
| [operator=](counted_iterator/operator= "cpp/iterator/counted iterator/operator=")
(C++20) | assigns another iterator adaptor (public member function) |
| [base](counted_iterator/base "cpp/iterator/counted iterator/base")
(C++20) | accesses the underlying iterator (public member function) |
| [count](counted_iterator/count "cpp/iterator/counted iterator/count")
(C++20) | returns the distance to the end (public member function) |
| [operator\*operator->](counted_iterator/operator* "cpp/iterator/counted iterator/operator*")
(C++20) | accesses the pointed-to element (public member function) |
| [operator[]](counted_iterator/operator_at "cpp/iterator/counted iterator/operator at")
(C++20) | accesses an element by index (public member function) |
| [operator++operator++(int)operator+=operator+operator--operator--(int)operator-=operator-](counted_iterator/operator_arith "cpp/iterator/counted iterator/operator arith")
(C++20) | advances or decrements the iterator (public member function) |
### Member objects
| Member name | Definition |
| --- | --- |
| `*current*` (private) | the underlying iterator which [`base()`](counted_iterator/base "cpp/iterator/counted iterator/base") accesses, the name is for exposition only |
| `*length*` (private) | the distance between the underlying iterator and the end of its range, the name is for exposition only |
### Non-member functions
| | |
| --- | --- |
| [operator==operator<=>](counted_iterator/operator_cmp "cpp/iterator/counted iterator/operator cmp")
(C++20) | compares the distances to the end (function template) |
| [operator==(std::default\_sentinel)](counted_iterator/operator_cmp2 "cpp/iterator/counted iterator/operator cmp2")
(C++20) | checks if the distance to the end is equal to `โ0โ` (function template) |
| [operator+](counted_iterator/operator_plus_ "cpp/iterator/counted iterator/operator+")
(C++20) | advances the iterator (function template) |
| [operator-](counted_iterator/operator- "cpp/iterator/counted iterator/operator-")
(C++20) | computes the distance between two iterator adaptors (function template) |
| [operator-(std::default\_sentinel\_t)](counted_iterator/operator-2 "cpp/iterator/counted iterator/operator-2")
(C++20) | computes the signed distance to the end (function template) |
| [iter\_move](counted_iterator/iter_move "cpp/iterator/counted iterator/iter move")
(C++20) | casts the result of dereferencing the underlying iterator to its associated rvalue reference type (function) |
| [iter\_swap](counted_iterator/iter_swap "cpp/iterator/counted iterator/iter swap")
(C++20) | swaps the objects pointed to by two underlying iterators (function template) |
### Helper classes
| | |
| --- | --- |
| [std::iterator\_traits<std::counted\_iterator>](counted_iterator/iterator_traits "cpp/iterator/counted iterator/iterator traits")
(C++20) | provides uniform interface to the properties of the `std::counted_iterator` type (class template specialization) |
### Example
```
#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>
#include <vector>
using std::operator""s;
void print(auto const remark, auto const& v) {
const auto size = std::ssize(v);
std::cout << remark << "[" << size << "] { ";
for (auto it = std::counted_iterator{std::cbegin(v), size};
it != std::default_sentinel; ++it) {
std::cout << *it << ", ";
}
std::cout << "}\n";
}
int main() {
const auto src = {"Arcturus"s, "Betelgeuse"s, "Canopus"s, "Deneb"s, "Elnath"s };
print("src", src);
std::vector<decltype(src)::value_type> dst;
std::ranges::copy(std::counted_iterator{src.begin(), 3},
std::default_sentinel,
std::back_inserter(dst));
print("dst", dst);
}
```
Output:
```
src[5] { Arcturus, Betelgeuse, Canopus, Deneb, Elnath, }
dst[3] { Arcturus, Betelgeuse, Canopus, }
```
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [P2259R1](https://wg21.link/P2259R1) | C++20 | member typedefs are not provided`[std::incrementable\_traits](incrementable_traits "cpp/iterator/incrementable traits")` is specialized for `counted_iterator` | member typedefs are added to account for [`iterator_traits`](counted_iterator/iterator_traits "cpp/iterator/counted iterator/iterator traits") fixredundant `[std::incrementable\_traits](incrementable_traits "cpp/iterator/incrementable traits")` specialization is removed |
### See also
| | |
| --- | --- |
| [default\_sentinel\_t](default_sentinel_t "cpp/iterator/default sentinel t")
(C++20) | default sentinel for use with iterators that know the bound of their range (class) |
| [views::counted](../ranges/view_counted "cpp/ranges/view counted")
(C++20) | creates a subrange from an iterator and a count (customization point object) |
| [ranges::take\_viewviews::take](../ranges/take_view "cpp/ranges/take view")
(C++20) | a [`view`](../ranges/view "cpp/ranges/view") consisting of the first N elements of another [`view`](../ranges/view "cpp/ranges/view") (class template) (range adaptor object) |
cpp std::indirectly_copyable std::indirectly\_copyable
=========================
| Defined in header `[<iterator>](../header/iterator "cpp/header/iterator")` | | |
| --- | --- | --- |
|
```
template<class In, class Out>
concept indirectly_copyable =
std::indirectly_readable<In> &&
std::indirectly_writable<Out, std::iter_reference_t<In>>;
```
| | (since C++20) |
The `indirectly_copyable` concept specifies the relationship between an [`indirectly_readable`](indirectly_readable "cpp/iterator/indirectly readable") type and a type that is [`indirectly_writable`](indirectly_writable "cpp/iterator/indirectly writable"). The `indirectly_writable` type must be able to directly copy the object that the `indirectly_readable` type references.
### See also
| | |
| --- | --- |
| [indirectly\_movable](indirectly_movable "cpp/iterator/indirectly movable")
(C++20) | specifies that values may be moved from an [`indirectly_readable`](indirectly_readable "cpp/iterator/indirectly readable") type to an [`indirectly_writable`](indirectly_writable "cpp/iterator/indirectly writable") type (concept) |
| [indirectly\_copyable\_storable](indirectly_copyable_storable "cpp/iterator/indirectly copyable storable")
(C++20) | specifies that values may be copied from an [`indirectly_readable`](indirectly_readable "cpp/iterator/indirectly readable") type to an [`indirectly_writable`](indirectly_writable "cpp/iterator/indirectly writable") type and that the copy may be performed via an intermediate object (concept) |
cpp std::permutable std::permutable
===============
| Defined in header `[<iterator>](../header/iterator "cpp/header/iterator")` | | |
| --- | --- | --- |
|
```
template< class I >
concept permutable =
std::forward_iterator<I> &&
std::indirectly_movable_storable<I, I> &&
std::indirectly_swappable<I, I>;
```
| | (since C++20) |
The concept `permutable` refines `[std::forward\_iterator](forward_iterator "cpp/iterator/forward iterator")` by adding requirements for reordering through moves and swaps.
### Semantic requirements
`I` models `permutable` only if all concepts it subsumes are modeled.
### See also
| | |
| --- | --- |
| [sortable](sortable "cpp/iterator/sortable")
(C++20) | specifies the common requirements of algorithms that permute sequences into ordered sequences (concept) |
| [ranges::removeranges::remove\_if](../algorithm/ranges/remove "cpp/algorithm/ranges/remove")
(C++20)(C++20) | removes elements satisfying specific criteria (niebloid) |
| [ranges::unique](../algorithm/ranges/unique "cpp/algorithm/ranges/unique")
(C++20) | removes consecutive duplicate elements in a range (niebloid) |
| [ranges::reverse](../algorithm/ranges/reverse "cpp/algorithm/ranges/reverse")
(C++20) | reverses the order of elements in a range (niebloid) |
| [ranges::rotate](../algorithm/ranges/rotate "cpp/algorithm/ranges/rotate")
(C++20) | rotates the order of elements in a range (niebloid) |
| [ranges::shuffle](../algorithm/ranges/shuffle "cpp/algorithm/ranges/shuffle")
(C++20) | randomly re-orders elements in a range (niebloid) |
| [ranges::partition](../algorithm/ranges/partition "cpp/algorithm/ranges/partition")
(C++20) | divides a range of elements into two groups (niebloid) |
| [ranges::stable\_partition](../algorithm/ranges/stable_partition "cpp/algorithm/ranges/stable partition")
(C++20) | divides elements into two groups while preserving their relative order (niebloid) |
cpp std::indirectly_comparable std::indirectly\_comparable
===========================
| Defined in header `[<iterator>](../header/iterator "cpp/header/iterator")` | | |
| --- | --- | --- |
|
```
template< class I1, class I2, class Comp,
class Proj1 = std::identity, class Proj2 = std::identity >
concept indirectly_comparable =
std::indirect_binary_predicate<Comp, std::projected<I1, Proj1>, std::projected<I2, Proj2>>;
```
| | (since C++20) |
The concept `indirectly_comparable` specifies the fundamental algorithm requirement for comparing values across two independent ranges.
### Semantic requirements
`indirectly_comparable` is modeled only if all concepts it subsumes are modeled.
### See also
| | |
| --- | --- |
| [indirect\_binary\_predicate](indirect_binary_predicate "cpp/iterator/indirect binary predicate")
(C++20) | specifies that a callable type, when invoked with the result of dereferencing two [`indirectly_readable`](indirectly_readable "cpp/iterator/indirectly readable") types, satisfies [`predicate`](../concepts/predicate "cpp/concepts/predicate") (concept) |
cpp std::indirectly_swappable std::indirectly\_swappable
==========================
| Defined in header `[<iterator>](../header/iterator "cpp/header/iterator")` | | |
| --- | --- | --- |
|
```
template< class I1, class I2 >
concept indirectly_swappable =
std::indirectly_readable<I1> &&
std::indirectly_readable<I2> &&
requires( const I1 i1, const I2 i2 ) {
ranges::iter_swap(i1, i1);
ranges::iter_swap(i1, i2);
ranges::iter_swap(i2, i1);
ranges::iter_swap(i2, i2);
};
```
| | (since C++20) |
The concept `indirectly_swappable` specifies a relationship between two types respectively modelling `[std::indirectly\_readable](indirectly_readable "cpp/iterator/indirectly readable")`, where their referenced types can be swapped.
### Semantic requirements
`I1` and `I2` model `indirectly_swappable` only if all concepts it subsumes are modeled.
### Equality preservation
An expression is *equality preserving* if it results in equal outputs given equal inputs.
* The inputs to an expression consist of its operands.
* The outputs of an expression consist of its result and all operands modified by the expression (if any).
In specification of standard concepts, operands are defined as the largest subexpressions that include only:
* an [id-expression](../language/expressions#Primary_expressions "cpp/language/expressions"), and
* invocations of [`std::move`](../utility/move "cpp/utility/move"), `[std::forward](../utility/forward "cpp/utility/forward")`, and `[std::declval](../utility/declval "cpp/utility/declval")`.
The cv-qualification and value category of each operand is determined by assuming that each template type parameter denotes a cv-unqualified complete non-array object type.
Every expression required to be equality preserving is further required to be *stable*: two evaluations of such an expression with the same input objects must have equal outputs absent any explicit intervening modification of those input objects.
Unless noted otherwise, every expression used in a *requires-expression* is required to be equality preserving and stable, and the evaluation of the expression may modify only its non-constant operands. Operands that are constant must not be modified.
### See also
| | |
| --- | --- |
| [indirectly\_readable](indirectly_readable "cpp/iterator/indirectly readable")
(C++20) | specifies that a type is indirectly readable by applying operator `*` (concept) |
| [iter\_swap](ranges/iter_swap "cpp/iterator/ranges/iter swap")
(C++20) | swaps the values referenced by two dereferenceable objects (customization point object) |
cpp std::indirect_result_t std::indirect\_result\_t
========================
| Defined in header `[<iterator>](../header/iterator "cpp/header/iterator")` | | |
| --- | --- | --- |
|
```
template< class F, class... Is >
requires (std::indirectly_readable<Is> && ...) &&
std::invocable<F, std::iter_reference_t<Is>...>
using indirect_result_t = std::invoke_result_t<F, std::iter_reference_t<Is>...>;
```
| | (since C++20) |
The alias template `indirect_result_t` obtains the result type of invoking an [`invocable`](../concepts/invocable "cpp/concepts/invocable") type `F` on the result of dereferencing [`indirectly_readable`](indirectly_readable "cpp/iterator/indirectly readable") types `Is...`.
### Template parameters
| | | |
| --- | --- | --- |
| F | - | an invocable type |
| Is | - | indirectly readable types that are dereferenced to arguments |
### See also
| | |
| --- | --- |
| [result\_ofinvoke\_result](../types/result_of "cpp/types/result of")
(C++11)(removed in C++20)(C++17) | deduces the result type of invoking a callable object with a set of arguments (class template) |
| programming_docs |
cpp std::inserter std::inserter
=============
| Defined in header `[<iterator>](../header/iterator "cpp/header/iterator")` | | |
| --- | --- | --- |
|
```
template< class Container >
std::insert_iterator<Container> inserter( Container& c, typename Container::iterator i );
```
| | (until C++20) |
|
```
template< class Container >
constexpr std::insert_iterator<Container> inserter( Container& c, ranges::iterator_t<Container> i );
```
| | (since C++20) |
`inserter` is a convenience function template that constructs a `[std::insert\_iterator](insert_iterator "cpp/iterator/insert iterator")` for the container `c` and its iterator `i` with the type deduced from the type of the argument.
### Parameters
| | | |
| --- | --- | --- |
| c | - | container that supports an `insert` operation |
| i | - | iterator in `c` indicating the insertion position |
### Return value
A `[std::insert\_iterator](insert_iterator "cpp/iterator/insert iterator")` which can be used to insert elements into the container `c` at the position indicated by `i`.
### Possible implementation
| |
| --- |
|
```
template< class Container >
std::insert_iterator<Container> inserter( Container& c, typename Container::iterator i )
{
return std::insert_iterator<Container>(c, i);
}
```
|
### Example
```
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
#include <set>
int main()
{
std::multiset<int> s {1, 2, 3};
// std::inserter is commonly used with multi-sets
std::fill_n(std::inserter(s, s.end()), 5, 2);
for (int n : s)
std::cout << n << ' ';
std::cout << '\n';
std::vector<int> d {100, 200, 300};
std::vector<int> v {1, 2, 3, 4, 5};
// when inserting in a sequence container, insertion point advances
// because each std::insert_iterator::operator= updates the target iterator
std::copy(d.begin(), d.end(), std::inserter(v, std::next(v.begin())));
for (int n : v)
std::cout << n << ' ';
std::cout << '\n';
}
```
Output:
```
1 2 2 2 2 2 2 3
1 100 200 300 2 3 4 5
```
### See also
| | |
| --- | --- |
| [insert\_iterator](insert_iterator "cpp/iterator/insert iterator") | iterator adaptor for insertion into a container (class template) |
| [back\_inserter](back_inserter "cpp/iterator/back inserter") | creates a `[std::back\_insert\_iterator](back_insert_iterator "cpp/iterator/back insert iterator")` of type inferred from the argument (function template) |
| [front\_inserter](front_inserter "cpp/iterator/front inserter") | creates a `[std::front\_insert\_iterator](front_insert_iterator "cpp/iterator/front insert iterator")` of type inferred from the argument (function template) |
cpp std::indirect_equivalence_relation std::indirect\_equivalence\_relation
====================================
| Defined in header `[<iterator>](../header/iterator "cpp/header/iterator")` | | |
| --- | --- | --- |
|
```
template<class F, class I1, class I2 = I1>
concept indirect_equivalence_relation =
std::indirectly_readable<I1> &&
std::indirectly_readable<I2> &&
std::copy_constructible<F> &&
std::equivalence_relation<F&, std::iter_value_t<I1>&, std::iter_value_t<I2>&> &&
std::equivalence_relation<F&, std::iter_value_t<I1>&, std::iter_reference_t<I2>> &&
std::equivalence_relation<F&, std::iter_reference_t<I1>, std::iter_value_t<I2>&> &&
std::equivalence_relation<F&, std::iter_reference_t<I1>, std::iter_reference_t<I2>> &&
std::equivalence_relation<F&, std::iter_common_reference_t<I1>, std::iter_common_reference_t<I2>>;
```
| | (since C++20) |
The concept `indirect_equivalence_relation` specifies requirements for algorithms that call equivalence relations as their arguments. The key difference between this concept and `[std::equivalence\_relation](../concepts/equivalence_relation "cpp/concepts/equivalence relation")` is that it is applied to the types that `I1` and `I2` references, rather than `I1` and `I2` themselves.
### Semantic requirements
`F`, `I1`, and `I2` model `indirect_equivalence_relation` only if all concepts it subsumes are modeled.
cpp std::incrementable_traits std::incrementable\_traits
==========================
| Defined in header `[<iterator>](../header/iterator "cpp/header/iterator")` | | |
| --- | --- | --- |
|
```
template< class I >
struct incrementable_traits { };
```
| (1) | (since C++20) |
|
```
template< class T >
requires std::is_object_v<T>
struct incrementable_traits<T*>;
```
| (2) | (since C++20) |
|
```
template< class T >
struct incrementable_traits<const T> : incrementable_traits<T> { };
```
| (3) | (since C++20) |
|
```
template< class T >
requires requires { typename T::difference_type; }
struct incrementable_traits<T>;
```
| (4) | (since C++20) |
|
```
template< class T >
requires (!requires { typename T::difference_type; }) &&
requires(const T& a, const T& b) { { a - b } -> std::integral; }
struct incrementable_traits<T>;
```
| (5) | (since C++20) |
Computes the associated difference type of the type `I`, if any. Users may specialize `incrementable_traits` for a program-defined type.
1) Primary template is an empty struct.
2) Specialization for pointers. Provides a member type `difference_type` equal to `[std::ptrdiff\_t](../types/ptrdiff_t "cpp/types/ptrdiff t")`.
3) Specialization for const-qualified types.
4) Specialization for types that define a public and accessible member type `difference_type`. Provides a member type `difference_type` equal to `T::difference_type`.
5) Specialization for types that do not define a public and accessible member type `difference_type` but do support subtraction. Provides a member type `difference_type` equal to `[std::make\_signed\_t](http://en.cppreference.com/w/cpp/types/make_signed)<decltype([std::declval](http://en.cppreference.com/w/cpp/utility/declval)<T>() - [std::declval](http://en.cppreference.com/w/cpp/utility/declval)<T>())>`. The implicit expression variations rule (see below) applies to the expression `a - b`. ### Implicit expression variations
A *requires-expression* that uses an expression that is non-modifying for some constant lvalue operand also implicitly requires additional variations of that expression that accept a non-constant lvalue or (possibly constant) rvalue for the given operand unless such an expression variation is explicitly required with differing semantics. These *implicit expression variations* must meet the same semantic requirements of the declared expression. The extent to which an implementation validates the syntax of the variations is unspecified.
### Example
### See also
| | |
| --- | --- |
| [weakly\_incrementable](weakly_incrementable "cpp/iterator/weakly incrementable")
(C++20) | specifies that a [`semiregular`](../concepts/semiregular "cpp/concepts/semiregular") type can be incremented with pre- and post-increment operators (concept) |
| [iter\_value\_titer\_reference\_titer\_const\_reference\_titer\_difference\_titer\_rvalue\_reference\_titer\_common\_reference\_t](iter_t "cpp/iterator/iter t")
(C++20)(C++20)(C++23)(C++20)(C++20)(C++20) | computes the associated types of an iterator (alias template) |
| [iterator\_traits](iterator_traits "cpp/iterator/iterator traits") | provides uniform interface to the properties of an iterator (class template) |
cpp std::advance std::advance
============
| Defined in header `[<iterator>](../header/iterator "cpp/header/iterator")` | | |
| --- | --- | --- |
|
```
template< class InputIt, class Distance >
void advance( InputIt& it, Distance n );
```
| | (until C++17) |
|
```
template< class InputIt, class Distance >
constexpr void advance( InputIt& it, Distance n );
```
| | (since C++17) |
Increments given iterator `it` by `n` elements.
If `n` is negative, the iterator is decremented. In this case, `InputIt` must meet the requirements of [LegacyBidirectionalIterator](../named_req/bidirectionaliterator "cpp/named req/BidirectionalIterator"), otherwise the behavior is undefined.
### Parameters
| | | |
| --- | --- | --- |
| it | - | iterator to be advanced |
| n | - | number of elements `it` should be advanced |
| Type requirements |
| -`InputIt` must meet the requirements of [LegacyInputIterator](../named_req/inputiterator "cpp/named req/InputIterator"). |
### Return value
(none).
### Complexity
Linear.
However, if `InputIt` additionally meets the requirements of [LegacyRandomAccessIterator](../named_req/randomaccessiterator "cpp/named req/RandomAccessIterator"), complexity is constant.
### Notes
The behavior is undefined if the specified sequence of increments or decrements would require that a non-incrementable iterator (such as the past-the-end iterator) is incremented, or that a non-decrementable iterator (such as the front iterator or the singular iterator) is decremented.
### Possible implementation
See also the implementations in [libstdc++](https://github.com/gcc-mirror/gcc/blob/d9375e490072d1aae73a93949aa158fcd2a27018/libstdc%2B%2B-v3/include/bits/stl_iterator_base_funcs.h#L200) and [libc++](https://github.com/llvm-mirror/libcxx/blob/a12cb9d211019d99b5875b6d8034617cbc24c2cc/include/iterator#L582).
| First version |
| --- |
|
```
// implementation via tag dispatch, available in C++98 with constexpr removed
namespace detail {
template<class It>
constexpr // required since C++17
void do_advance(It& it, typename std::iterator_traits<It>::difference_type n,
std::input_iterator_tag)
{
while (n > 0) {
--n;
++it;
}
}
template<class It>
constexpr // required since C++17
void do_advance(It& it, typename std::iterator_traits<It>::difference_type n,
std::bidirectional_iterator_tag)
{
while (n > 0) {
--n;
++it;
}
while (n < 0) {
++n;
--it;
}
}
template<class It>
constexpr // required since C++17
void do_advance(It& it, typename std::iterator_traits<It>::difference_type n,
std::random_access_iterator_tag)
{
it += n;
}
} // namespace detail
template<class It, class Distance>
constexpr // since C++17
void advance(It& it, Distance n)
{
detail::do_advance(it, typename std::iterator_traits<It>::difference_type(n),
typename std::iterator_traits<It>::iterator_category());
}
```
|
| Second version |
|
```
// implementation via constexpr if, available in C++17
template<class It, class Distance>
constexpr void advance(It& it, Distance n)
{
using category = typename std::iterator_traits<It>::iterator_category;
static_assert(std::is_base_of_v<std::input_iterator_tag, category>);
auto dist = typename std::iterator_traits<It>::difference_type(n);
if constexpr (std::is_base_of_v<std::random_access_iterator_tag, category>)
it += dist;
else {
while (dist > 0) {
--dist;
++it;
}
if constexpr (std::is_base_of_v<std::bidirectional_iterator_tag, category>) {
while (dist < 0) {
++dist;
--it;
}
}
}
}
```
|
### Example
```
#include <iostream>
#include <iterator>
#include <vector>
int main()
{
std::vector<int> v{ 3, 1, 4 };
auto vi = v.begin();
std::advance(vi, 2);
std::cout << *vi << ' ';
vi = v.end();
std::advance(vi, -2);
std::cout << *vi << '\n';
}
```
Output:
```
4 1
```
### See also
| | |
| --- | --- |
| [next](next "cpp/iterator/next")
(C++11) | increment an iterator (function template) |
| [prev](prev "cpp/iterator/prev")
(C++11) | decrement an iterator (function template) |
| [distance](distance "cpp/iterator/distance") | returns the distance between two iterators (function template) |
| [ranges::advance](ranges/advance "cpp/iterator/ranges/advance")
(C++20) | advances an iterator by given distance or to a given bound (niebloid) |
cpp std::input_iterator std::input\_iterator
====================
| Defined in header `[<iterator>](../header/iterator "cpp/header/iterator")` | | |
| --- | --- | --- |
|
```
template<class I>
concept input_iterator =
std::input_or_output_iterator<I> &&
std::indirectly_readable<I> &&
requires { typename /*ITER_CONCEPT*/<I>; } &&
std::derived_from</*ITER_CONCEPT*/<I>, std::input_iterator_tag>;
```
| | (since C++20) |
The `input_iterator` concept is a refinement of [`input_or_output_iterator`](input_or_output_iterator "cpp/iterator/input or output iterator"), adding the requirement that the referenced values can be read (via [`indirectly_readable`](indirectly_readable "cpp/iterator/indirectly readable")) and the requirement that the iterator concept tag be present.
### Iterator concept determination
Definition of this concept is specified via an exposition-only alias template `/*ITER_CONCEPT*/`.
In order to determine `/*ITER_CONCEPT*/<I>`, let `ITER_TRAITS<I>` denote `I` if the specialization `[std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<I>` is generated from the primary template, or `[std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<I>` otherwise:
* If `ITER_TRAITS<I>::iterator_concept` is valid and names a type, `/*ITER_CONCEPT*/<I>` denotes the type.
* Otherwise, if `ITER_TRAITS<I>::iterator_category` is valid and names a type, `/*ITER_CONCEPT*/<I>` denotes the type.
* Otherwise, if `[std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<I>` is generated from the primary template, `/*ITER_CONCEPT*/<I>` denotes `[std::random\_access\_iterator\_tag](iterator_tags "cpp/iterator/iterator tags")`.
* Otherwise, `/*ITER_CONCEPT*/<I>` does not denote a type and results in a substitution failure.
### Notes
Unlike the [LegacyInputIterator](../named_req/inputiterator "cpp/named req/InputIterator") requirements, the `input_iterator` concept does not require [`equality_comparable`](../concepts/equality_comparable "cpp/concepts/equality comparable"), since input iterators are typically compared with sentinels.
### See also
| | |
| --- | --- |
| [input\_or\_output\_iterator](input_or_output_iterator "cpp/iterator/input or output iterator")
(C++20) | specifies that objects of a type can be incremented and dereferenced (concept) |
cpp std::projected std::projected
==============
| Defined in header `[<iterator>](../header/iterator "cpp/header/iterator")` | | |
| --- | --- | --- |
|
```
template< std::indirectly_readable I,
std::indirectly_regular_unary_invocable<I> Proj >
struct projected {
using value_type = std::remove_cvref_t<std::indirect_result_t<Proj&, I>>;
std::indirect_result_t<Proj&, I> operator*() const; // not defined
};
```
| (1) | (since C++20) |
|
```
template< std::weakly_incrementable I, class Proj >
struct incrementable_traits<std::projected<I, Proj>> {
using difference_type = std::iter_difference_t<I>;
};
```
| (2) | (since C++20) |
1) Class template `projected` combines an [`indirectly_readable`](indirectly_readable "cpp/iterator/indirectly readable") type `I` and a callable object type `Proj` into a new `indirectly_readable` type whose reference type is the result of applying `Proj` to the `[std::iter\_reference\_t](http://en.cppreference.com/w/cpp/iterator/iter_t)<I>`.
2) This specialization of `[std::incrementable\_traits](incrementable_traits "cpp/iterator/incrementable traits")` makes `std::[projected](http://en.cppreference.com/w/cpp/ranges-placeholder/iterator/projected)<I, Proj>` a [`weakly_incrementable`](weakly_incrementable "cpp/iterator/weakly incrementable") type when `I` is also a `weakly_incrementable` type. `projected` is used only to constrain algorithms that accept callable objects and projections, and hence its `operator*()` is not defined.
### Template parameters
| | | |
| --- | --- | --- |
| I | - | an indirectly readable type |
| Proj | - | projection applied to a dereferenced `I` |
cpp std::rbegin, std::crbegin std::rbegin, std::crbegin
=========================
| Defined in header `[<array>](../header/array "cpp/header/array")` | | |
| --- | --- | --- |
| Defined in header `[<deque>](../header/deque "cpp/header/deque")` | | |
| Defined in header `[<forward\_list>](../header/forward_list "cpp/header/forward list")` | | |
| Defined in header `[<iterator>](../header/iterator "cpp/header/iterator")` | | |
| Defined in header `[<list>](../header/list "cpp/header/list")` | | |
| Defined in header `[<map>](../header/map "cpp/header/map")` | | |
| Defined in header `[<regex>](../header/regex "cpp/header/regex")` | | |
| Defined in header `[<set>](../header/set "cpp/header/set")` | | |
| Defined in header `[<span>](../header/span "cpp/header/span")` | | (since C++20) |
| Defined in header `[<string>](../header/string "cpp/header/string")` | | |
| Defined in header `[<string\_view>](../header/string_view "cpp/header/string view")` | | (since C++17) |
| Defined in header `[<unordered\_map>](../header/unordered_map "cpp/header/unordered map")` | | |
| Defined in header `[<unordered\_set>](../header/unordered_set "cpp/header/unordered set")` | | |
| Defined in header `[<vector>](../header/vector "cpp/header/vector")` | | |
| | (1) | |
|
```
template< class C >
auto rbegin( C& c ) -> decltype(c.rbegin());
```
| (since C++14) (until C++17) |
|
```
template< class C >
constexpr auto rbegin( C& c ) -> decltype(c.rbegin());
```
| (since C++17) |
| | (1) | |
|
```
template< class C >
auto rbegin( const C& c ) -> decltype(c.rbegin());
```
| (since C++14) (until C++17) |
|
```
template< class C >
constexpr auto rbegin( const C& c ) -> decltype(c.rbegin());
```
| (since C++17) |
| | (2) | |
|
```
template< class T, std::size_t N >
std::reverse_iterator<T*> rbegin( T (&array)[N] );
```
| (since C++14) (until C++17) |
|
```
template< class T, std::size_t N >
constexpr std::reverse_iterator<T*> rbegin( T (&array)[N] );
```
| (since C++17) |
| | (3) | |
|
```
template< class T >
std::reverse_iterator<const T*> rbegin( std::initializer_list<T> il );
```
| (since C++14) (until C++17) |
|
```
template< class T >
constexpr std::reverse_iterator<const T*> rbegin(std::initializer_list<T> il);
```
| (since C++17) |
| | (4) | |
|
```
template< class C >
auto crbegin( const C& c ) -> decltype(std::rbegin(c));
```
| (since C++14) (until C++17) |
|
```
template< class C >
constexpr auto crbegin( const C& c ) -> decltype(std::rbegin(c));
```
| (since C++17) |
Returns an iterator to the reverse-beginning of the given range.
1) Returns an iterator to the reverse-beginning of the possibly const-qualified container or view `c`.
2) Returns `[std::reverse\_iterator](http://en.cppreference.com/w/cpp/iterator/reverse_iterator)<T\*>` to the reverse-beginning of the array `array`.
3) Returns `[std::reverse\_iterator](http://en.cppreference.com/w/cpp/iterator/reverse_iterator)<const T\*>` to the reverse-beginning of the `[std::initializer\_list](../utility/initializer_list "cpp/utility/initializer list")` `il`.
4) Returns an iterator to the reverse-beginning of the const-qualified container or view `c`. ![range-rbegin-rend.svg]()
### Parameters
| | | |
| --- | --- | --- |
| c | - | a container or view with a `rbegin` member function |
| array | - | an array of arbitrary type |
| il | - | an `initializer_list` |
### Return value
1) `c.rbegin()`
2) `[std::reverse\_iterator](http://en.cppreference.com/w/cpp/iterator/reverse_iterator)<T\*>(array + N)`
3) `[std::reverse\_iterator](http://en.cppreference.com/w/cpp/iterator/reverse_iterator)<const T\*>(il.end())`
4) `c.rbegin()`
### Exceptions
May throw implementation-defined exceptions.
### Overloads
Custom overloads of `rbegin` may be provided for classes and enumerations that do not expose a suitable `rbegin()` member function, yet can be iterated.
| | |
| --- | --- |
| Overloads of `rbegin` found by [argument-dependent lookup](../language/adl "cpp/language/adl") can be used to customize the behavior of `std::[ranges::rbegin](http://en.cppreference.com/w/cpp/ranges/rbegin)` and `std::[ranges::crbegin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/crbegin)`. | (since C++20) |
### Notes
The overload for `[std::initializer\_list](../utility/initializer_list "cpp/utility/initializer list")` is necessary because it does not have a member function `rbegin`.
### Example
```
#include <iostream>
#include <vector>
#include <iterator>
int main()
{
std::vector<int> v = { 3, 1, 4 };
auto vi = std::rbegin(v); // the type of `vi` is std::vector<int>::reverse_iterator
std::cout << "*vi = " << *vi << '\n';
*std::rbegin(v) = 42; // OK: after assignment v[2] == 42
// *std::crbegin(v) = 13; // error: the location is read-only
int a[] = { -5, 10, 15 };
auto ai = std::rbegin(a); // the type of `ai` is std::reverse_iterator<int*>
std::cout << "*ai = " << *ai << '\n';
auto il = { 3, 1, 4 };
// the type of `it` below is std::reverse_iterator<int const*>:
for (auto it = std::rbegin(il); it != std::rend(il); ++it)
std::cout << *it << ' ';
}
```
Output:
```
*vi = 4
*ai = 15
4 1 3
```
### See also
| | |
| --- | --- |
| [begincbegin](begin "cpp/iterator/begin")
(C++11)(C++14) | returns an iterator to the beginning of a container or array (function template) |
| [endcend](end "cpp/iterator/end")
(C++11)(C++14) | returns an iterator to the end of a container or array (function template) |
| [rendcrend](rend "cpp/iterator/rend")
(C++14) | returns a reverse end iterator for a container or array (function template) |
| [ranges::rbegin](../ranges/rbegin "cpp/ranges/rbegin")
(C++20) | returns a reverse iterator to a range (customization point object) |
| [ranges::crbegin](../ranges/crbegin "cpp/ranges/crbegin")
(C++20) | returns a reverse iterator to a read-only range (customization point object) |
| programming_docs |
cpp std::back_inserter std::back\_inserter
===================
| Defined in header `[<iterator>](../header/iterator "cpp/header/iterator")` | | |
| --- | --- | --- |
|
```
template< class Container >
std::back_insert_iterator<Container> back_inserter( Container& c );
```
| | (until C++20) |
|
```
template< class Container >
constexpr std::back_insert_iterator<Container> back_inserter( Container& c );
```
| | (since C++20) |
`back_inserter` is a convenient function template that constructs a `[std::back\_insert\_iterator](back_insert_iterator "cpp/iterator/back insert iterator")` for the container `c` with the type deduced from the type of the argument.
### Parameters
| | | |
| --- | --- | --- |
| c | - | container that supports a push\_back operation |
### Return value
A `[std::back\_insert\_iterator](back_insert_iterator "cpp/iterator/back insert iterator")` which can be used to add elements to the end of the container `c`.
### Possible implementation
| |
| --- |
|
```
template< class Container >
std::back_insert_iterator<Container> back_inserter( Container& c )
{
return std::back_insert_iterator<Container>(c);
}
```
|
### Example
```
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
int main()
{
std::vector<int> v{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
std::fill_n(std::back_inserter(v), 3, -1);
for (int n : v)
std::cout << n << ' ';
}
```
Output:
```
1 2 3 4 5 6 7 8 9 10 -1 -1 -1
```
### See also
| | |
| --- | --- |
| [back\_insert\_iterator](back_insert_iterator "cpp/iterator/back insert iterator") | iterator adaptor for insertion at the end of a container (class template) |
| [front\_inserter](front_inserter "cpp/iterator/front inserter") | creates a `[std::front\_insert\_iterator](front_insert_iterator "cpp/iterator/front insert iterator")` of type inferred from the argument (function template) |
| [inserter](inserter "cpp/iterator/inserter") | creates a `[std::insert\_iterator](insert_iterator "cpp/iterator/insert iterator")` of type inferred from the argument (function template) |
cpp std::indirect_binary_predicate std::indirect\_binary\_predicate
================================
| Defined in header `[<iterator>](../header/iterator "cpp/header/iterator")` | | |
| --- | --- | --- |
|
```
template< class F, class I1, class I2 >
concept indirect_binary_predicate =
std::indirectly_readable<I1> &&
std::indirectly_readable<I2> &&
std::copy_constructible<F> &&
std::predicate<F&, std::iter_value_t<I1>&, std::iter_value_t<I2>&> &&
std::predicate<F&, std::iter_value_t<I1>&, std::iter_reference_t<I2>> &&
std::predicate<F&, std::iter_reference_t<I1>, std::iter_value_t<I2>&> &&
std::predicate<F&, std::iter_reference_t<I1>, std::iter_reference_t<I2>> &&
std::predicate<F&, std::iter_common_reference_t<I1>, std::iter_common_reference_t<I2>>;
```
| | (since C++20) |
The concept `indirect_binary_predicate` specifies requirements for algorithms that call binary predicates as their arguments. The key difference between this concept and `[std::predicate](../concepts/predicate "cpp/concepts/predicate")` is that it is applied to the types that `I1` and `I2` references, rather than `I1` and `I2` themselves.
### Semantic requirements
`F`, `I1`, and `I2` model `indirect_binary_predicate` only if all concepts it subsumes are modeled.
cpp std::distance std::distance
=============
| Defined in header `[<iterator>](../header/iterator "cpp/header/iterator")` | | |
| --- | --- | --- |
|
```
template< class InputIt >
typename std::iterator_traits<InputIt>::difference_type
distance( InputIt first, InputIt last );
```
| | (constexpr since C++17) |
Returns the number of hops from `first` to `last`.
| | |
| --- | --- |
| The behavior is undefined if `last` is not reachable from `first` by (possibly repeatedly) incrementing `first`. | (until C++11) |
| If `InputIt` is not [LegacyRandomAccessIterator](../named_req/randomaccessiterator "cpp/named req/RandomAccessIterator"), the behavior is undefined if `last` is not reachable from `first` by (possibly repeatedly) incrementing `first`. If `InputIt` is [LegacyRandomAccessIterator](../named_req/randomaccessiterator "cpp/named req/RandomAccessIterator"), the behavior is undefined if `last` is not reachable from `first` and `first` is not reachable from `last`. | (since C++11) |
### Parameters
| | | |
| --- | --- | --- |
| first | - | iterator pointing to the first element |
| last | - | iterator pointing to the end of the range |
| Type requirements |
| -`InputIt` must meet the requirements of [LegacyInputIterator](../named_req/inputiterator "cpp/named req/InputIterator"). The operation is more efficient if `InputIt` additionally meets the requirements of [LegacyRandomAccessIterator](../named_req/randomaccessiterator "cpp/named req/RandomAccessIterator") |
### Return value
The number of increments needed to go from `first` to `last`. The value may be negative if random-access iterators are used and `first` is reachable from `last` (since C++11).
### Complexity
Linear.
However, if `InputIt` additionally meets the requirements of [LegacyRandomAccessIterator](../named_req/randomaccessiterator "cpp/named req/RandomAccessIterator"), complexity is constant.
### Possible implementation
See also the implementations in [libstdc++](https://github.com/gcc-mirror/gcc/blob/d9375e490072d1aae73a93949aa158fcd2a27018/libstdc%2B%2B-v3/include/bits/stl_iterator_base_funcs.h#L135) and [libc++](https://github.com/llvm-mirror/libcxx/blob/a12cb9d211019d99b5875b6d8034617cbc24c2cc/include/iterator#L611).
| First version |
| --- |
|
```
// implementation via tag dispatch, available in C++98 with constexpr removed
namespace detail {
template<class It>
constexpr // required since C++17
typename std::iterator_traits<It>::difference_type
do_distance(It first, It last, std::input_iterator_tag)
{
typename std::iterator_traits<It>::difference_type result = 0;
while (first != last) {
++first;
++result;
}
return result;
}
template<class It>
constexpr // required since C++17
typename std::iterator_traits<It>::difference_type
do_distance(It first, It last, std::random_access_iterator_tag)
{
return last - first;
}
} // namespace detail
template<class It>
constexpr // since C++17
typename std::iterator_traits<It>::difference_type
distance(It first, It last)
{
return detail::do_distance(first, last,
typename std::iterator_traits<It>::iterator_category());
}
```
|
| Second version |
|
```
// implementation via constexpr if, available in C++17
template<class It>
constexpr typename std::iterator_traits<It>::difference_type
distance(It first, It last)
{
using category = typename std::iterator_traits<It>::iterator_category;
static_assert(std::is_base_of_v<std::input_iterator_tag, category>);
if constexpr (std::is_base_of_v<std::random_access_iterator_tag, category>)
return last - first;
else {
typename std::iterator_traits<It>::difference_type result = 0;
while (first != last) {
++first;
++result;
}
return result;
}
}
```
|
### Example
```
#include <iostream>
#include <iterator>
#include <vector>
int main()
{
std::vector<int> v{ 3, 1, 4 };
std::cout << "distance(first, last) = "
<< std::distance(v.begin(), v.end()) << '\n'
<< "distance(last, first) = "
<< std::distance(v.end(), v.begin()) << '\n';
//the behavior is undefined (until C++11)
static constexpr auto il = { 3, 1, 4 };
// Since C++17 `distance` can be used in constexpr context.
static_assert(std::distance(il.begin(), il.end()) == 3);
static_assert(std::distance(il.end(), il.begin()) == -3);
}
```
Output:
```
distance(first, last) = 3
distance(last, first) = -3
```
### See also
| | |
| --- | --- |
| [advance](advance "cpp/iterator/advance") | advances an iterator by given distance (function template) |
| [countcount\_if](../algorithm/count "cpp/algorithm/count") | returns the number of elements satisfying specific criteria (function template) |
| [ranges::distance](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) |
cpp std::output_iterator std::output\_iterator
=====================
| Defined in header `[<iterator>](../header/iterator "cpp/header/iterator")` | | |
| --- | --- | --- |
|
```
template <class I, class T>
concept output_iterator =
std::input_or_output_iterator<I> &&
std::indirectly_writable<I, T> &&
requires(I i, T&& t) {
*i++ = std::forward<T>(t); // not required to be equality-preserving
};
```
| | (since C++20) |
The `output_iterator` concept is a refinement of [`input_or_output_iterator`](input_or_output_iterator "cpp/iterator/input or output iterator"), adding the requirement that it can be used to write values of type and value category encoded by `T` (via [`indirectly_writable`](indirectly_writable "cpp/iterator/indirectly writable")). [`equality_comparable`](../concepts/equality_comparable "cpp/concepts/equality comparable") is not required.
### Semantic requirements
Let `E` be an expression such that `decltype((E))` is `T`, and `i` be a dereferenceable object of type `I`. `output_iterator<I, T>` is modeled only if all the concepts it subsumes are modeled, and `*i++ = E;` has effects equivalent to `*i = E; ++i;`.
### Equality preservation
An expression is *equality preserving* if it results in equal outputs given equal inputs.
* The inputs to an expression consist of its operands.
* The outputs of an expression consist of its result and all operands modified by the expression (if any).
In specification of standard concepts, operands are defined as the largest subexpressions that include only:
* an [id-expression](../language/expressions#Primary_expressions "cpp/language/expressions"), and
* invocations of [`std::move`](../utility/move "cpp/utility/move"), `[std::forward](../utility/forward "cpp/utility/forward")`, and `[std::declval](../utility/declval "cpp/utility/declval")`.
The cv-qualification and value category of each operand is determined by assuming that each template type parameter denotes a cv-unqualified complete non-array object type.
Every expression required to be equality preserving is further required to be *stable*: two evaluations of such an expression with the same input objects must have equal outputs absent any explicit intervening modification of those input objects.
### Notes
Unlike the [LegacyOutputIterator](../named_req/outputiterator "cpp/named req/OutputIterator") requirements, the `output_iterator` concept does not require that the iterator category tag be defined.
Algorithms on output iterators should be single pass.
### See also
| | |
| --- | --- |
| [input\_or\_output\_iterator](input_or_output_iterator "cpp/iterator/input or output iterator")
(C++20) | specifies that objects of a type can be incremented and dereferenced (concept) |
cpp std::indirectly_movable std::indirectly\_movable
========================
| Defined in header `[<iterator>](../header/iterator "cpp/header/iterator")` | | |
| --- | --- | --- |
|
```
template<class In, class Out>
concept indirectly_movable =
std::indirectly_readable<In> &&
std::indirectly_writable<Out, std::iter_rvalue_reference_t<In>>;
```
| | (since C++20) |
The `indirectly_movable` concept specifies the relationship between an [`indirectly_readable`](indirectly_readable "cpp/iterator/indirectly readable") type and a type that is [`indirectly_writable`](indirectly_writable "cpp/iterator/indirectly writable"). The `indirectly_writable` type must be able to directly move the object that the `indirectly_readable` type references.
### See also
| | |
| --- | --- |
| [indirectly\_movable\_storable](indirectly_movable_storable "cpp/iterator/indirectly movable storable")
(C++20) | specifies that values may be moved from an [`indirectly_readable`](indirectly_readable "cpp/iterator/indirectly readable") type to an [`indirectly_writable`](indirectly_writable "cpp/iterator/indirectly writable") type and that the move may be performed via an intermediate object (concept) |
| [indirectly\_copyable](indirectly_copyable "cpp/iterator/indirectly copyable")
(C++20) | specifies that values may be copied from an [`indirectly_readable`](indirectly_readable "cpp/iterator/indirectly readable") type to an [`indirectly_writable`](indirectly_writable "cpp/iterator/indirectly writable") type (concept) |
cpp std::incrementable std::incrementable
==================
| Defined in header `[<iterator>](../header/iterator "cpp/header/iterator")` | | |
| --- | --- | --- |
|
```
template<class I>
concept incrementable =
std::regular<I> &&
std::weakly_incrementable<I> &&
requires(I i) {
{ i++ } -> std::same_as<I>;
};
```
| | (since C++20) |
This concept specifies requirements on types that can be incremented with the pre- and post-increment operators, whose increment operations are equality-preserving, and the type is `[std::equality\_comparable](../concepts/equality_comparable "cpp/concepts/equality comparable")`.
Unlike with `[std::weakly\_incrementable](weakly_incrementable "cpp/iterator/weakly incrementable")`, which only support single-pass algorithms, multi-pass one-directional algorithms can be used with types that model `std::incrementable`.
### Semantic requirements
`I` models `std::incrementable` only if given any two incrementable objects `a` and `b` of type `I`:
* `bool(a == b)` implies `bool(a++ == b)`, and
* `bool(a == b)` implies `bool(((void)a++, a) == ++b)`
### Equality preservation
An expression is *equality preserving* if it results in equal outputs given equal inputs.
* The inputs to an expression consist of its operands.
* The outputs of an expression consist of its result and all operands modified by the expression (if any).
In specification of standard concepts, operands are defined as the largest subexpressions that include only:
* an [id-expression](../language/expressions#Primary_expressions "cpp/language/expressions"), and
* invocations of [`std::move`](../utility/move "cpp/utility/move"), `[std::forward](../utility/forward "cpp/utility/forward")`, and `[std::declval](../utility/declval "cpp/utility/declval")`.
The cv-qualification and value category of each operand is determined by assuming that each template type parameter denotes a cv-unqualified complete non-array object type.
Every expression required to be equality preserving is further required to be *stable*: two evaluations of such an expression with the same input objects must have equal outputs absent any explicit intervening modification of those input objects.
Unless noted otherwise, every expression used in a *requires-expression* is required to be equality preserving and stable, and the evaluation of the expression may modify only its non-constant operands. Operands that are constant must not be modified.
### See also
| | |
| --- | --- |
| [weakly\_incrementable](weakly_incrementable "cpp/iterator/weakly incrementable")
(C++20) | specifies that a [`semiregular`](../concepts/semiregular "cpp/concepts/semiregular") type can be incremented with pre- and post-increment operators (concept) |
| [same\_as](../concepts/same_as "cpp/concepts/same as")
(C++20) | specifies that a type is the same as another type (concept) |
cpp std::common_iterator std::common\_iterator
=====================
| Defined in header `[<iterator>](../header/iterator "cpp/header/iterator")` | | |
| --- | --- | --- |
|
```
template< std::input_or_output_iterator I, std::sentinel_for<I> S >
requires ( !std::same_as<I, S> && std::copyable<I> )
class common_iterator;
```
| | (since C++20) |
`std::common_iterator` is an iterator `I` / sentinel `S` adaptor that may represent a non-common range (where the types of `I` and `S` differ) as a [`common_range`](../ranges/common_range "cpp/ranges/common range"), by containing either an iterator or a sentinel, and defining the appropriate equality comparison operators `operator==`.
`std::common_iterator` can be used as a "bridge" between sequences represented by iterator/sentinel pair and legacy functions that expect [`common_range`](../ranges/common_range "cpp/ranges/common range")-like sequences.
### Member functions
| | |
| --- | --- |
| [(constructor)](common_iterator/common_iterator "cpp/iterator/common iterator/common iterator")
(C++20) | constructs a new iterator adaptor (public member function) |
| [operator=](common_iterator/operator= "cpp/iterator/common iterator/operator=")
(C++20) | assigns another iterator adaptor (public member function) |
| [operator\*operator->](common_iterator/operator* "cpp/iterator/common iterator/operator*")
(C++20) | accesses the pointed-to element (public member function) |
| [operator++operator++(int)](common_iterator/operator_arith "cpp/iterator/common iterator/operator arith")
(C++20) | advances the iterator adaptor (public member function) |
### Member objects
| Member name | Definition |
| --- | --- |
| `*var*` (private) | an object of type `[std::variant](http://en.cppreference.com/w/cpp/utility/variant)<I, S>`, the name is for exposition only |
### Non-member functions
| | |
| --- | --- |
| [operator==](common_iterator/operator_cmp "cpp/iterator/common iterator/operator cmp")
(C++20) | compares the underlying iterators or sentinels (function template) |
| [operator-](common_iterator/operator- "cpp/iterator/common iterator/operator-")
(C++20) | computes the distance between two iterator adaptors (function template) |
| [iter\_move](common_iterator/iter_move "cpp/iterator/common iterator/iter move")
(C++20) | casts the result of dereferencing the underlying iterator to its associated rvalue reference type (function) |
| [iter\_swap](common_iterator/iter_swap "cpp/iterator/common iterator/iter swap")
(C++20) | swaps the objects pointed to by two underlying iterators (function template) |
### Helper classes
| | |
| --- | --- |
| [std::incrementable\_traits<std::common\_iterator>](common_iterator/incrementable_traits "cpp/iterator/common iterator/incrementable traits")
(C++20) | computes the associated difference type of the `std::common_iterator` type (class template specialization) |
| [std::iterator\_traits<std::common\_iterator>](common_iterator/iterator_traits "cpp/iterator/common iterator/iterator traits")
(C++20) | provides uniform interface to the properties of the `std::common_iterator` type (class template specialization) |
### Example
```
#include <algorithm>
#include <list>
#include <iostream>
#include <iterator>
#include <string>
template <class ForwardIter>
void fire(ForwardIter first, ForwardIter last) {
std::copy(first, last, std::ostream_iterator<std::string>{std::cout, " "});
}
int main() {
std::list<std::string> stars{"Pollux", "Arcturus", "Mira", "Aldebaran", "Sun"};
using IT = std::common_iterator<
std::counted_iterator<std::list<std::string>::iterator>,
std::default_sentinel_t>;
fire( IT(std::counted_iterator(stars.begin(), stars.size()-1)),
IT(std::default_sentinel) );
}
```
Output:
```
Pollux Arcturus Mira Aldebaran
```
### References
* C++20 standard (ISO/IEC 14882:2020):
+ 23.5.4 Common iterators [iterators.common]
### See also
| | |
| --- | --- |
| [ranges::common\_range](../ranges/common_range "cpp/ranges/common range")
(C++20) | specifies that a range has identical iterator and sentinel types (concept) |
| [ranges::common\_viewviews::common](../ranges/common_view "cpp/ranges/common view")
(C++20) | converts a [`view`](../ranges/view "cpp/ranges/view") into a [`common_range`](../ranges/common_range "cpp/ranges/common range") (class template) (range adaptor object) |
| programming_docs |
cpp std::istream_iterator std::istream\_iterator
======================
| Defined in header `[<iterator>](../header/iterator "cpp/header/iterator")` | | |
| --- | --- | --- |
|
```
template< class T,
class CharT = char,
class Traits = std::char_traits<CharT>,
class Distance = std::ptrdiff_t >
class istream_iterator: public std::iterator<std::input_iterator_tag,
T, Distance, const T*, const T&>
```
| | (until C++17) |
|
```
template< class T,
class CharT = char,
class Traits = std::char_traits<CharT>,
class Distance = std::ptrdiff_t >
class istream_iterator;
```
| | (since C++17) |
`std::istream_iterator` is a single-pass input iterator that reads successive objects of type `T` from the `[std::basic\_istream](../io/basic_istream "cpp/io/basic istream")` object for which it was constructed, by calling the appropriate `operator>>`. The actual read operation is performed when the iterator is incremented, not when it is dereferenced. The first object is read when the iterator is constructed. Dereferencing only returns a copy of the most recently read object.
The default-constructed `std::istream_iterator` is known as the *end-of-stream* iterator. When a valid `std::istream_iterator` reaches the end of the underlying stream, it becomes equal to the end-of-stream iterator. Dereferencing or incrementing it further invokes undefined behavior.
A typical implementation of `std::istream_iterator` holds two data members: a pointer to the associated `[std::basic\_istream](../io/basic_istream "cpp/io/basic istream")` object and the most recently read value of type `T`.
`T` must meet the [DefaultConstructible](../named_req/defaultconstructible "cpp/named req/DefaultConstructible"), [CopyConstructible](../named_req/copyconstructible "cpp/named req/CopyConstructible"), and [CopyAssignable](../named_req/copyassignable "cpp/named req/CopyAssignable") requirements.
### Member types
| Member type | Definition |
| --- | --- |
| `iterator_category` | `[std::input\_iterator\_tag](http://en.cppreference.com/w/cpp/iterator/iterator_tags)` |
| `value_type` | `T` |
| `difference_type` | `Distance` |
| `pointer` | `const T*` |
| `reference` | `const T&` |
| `char_type` | `CharT` |
| `traits_type` | `Traits` |
| `istream_type` | `[std::basic\_istream](http://en.cppreference.com/w/cpp/io/basic_istream)<CharT, Traits>` |
| | |
| --- | --- |
| Member types `iterator_category`, `value_type`, `difference_type`, `pointer` and `reference` are required to be obtained by inheriting from `[std::iterator](http://en.cppreference.com/w/cpp/iterator/iterator)<[std::input\_iterator\_tag](http://en.cppreference.com/w/cpp/iterator/iterator_tags), T, Distance, const T\*, const T&>`. | (until C++17) |
### Member functions
| | |
| --- | --- |
| [(constructor)](istream_iterator/istream_iterator "cpp/iterator/istream iterator/istream iterator") | constructs a new istream\_iterator (public member function) |
| [(destructor)](istream_iterator/~istream_iterator "cpp/iterator/istream iterator/~istream iterator") | destructs an istream\_iterator, including the cached value (public member function) |
| [operator\*operator->](istream_iterator/operator* "cpp/iterator/istream iterator/operator*") | returns the current element (public member function) |
| [operator++operator++(int)](istream_iterator/operator_arith "cpp/iterator/istream iterator/operator arith") | advances the iterator (public member function) |
### Non-member functions
| | |
| --- | --- |
| [operator==operator!=](istream_iterator/operator_cmp "cpp/iterator/istream iterator/operator cmp")
(removed in C++20) | compares two `istream_iterator`s (function template) |
### Notes
When reading characters, `std::istream_iterator` skips whitespace by default (unless disabled with `[std::noskipws](../io/manip/skipws "cpp/io/manip/skipws")` or equivalent), while `[std::istreambuf\_iterator](istreambuf_iterator "cpp/iterator/istreambuf iterator")` does not. In addition, `[std::istreambuf\_iterator](istreambuf_iterator "cpp/iterator/istreambuf iterator")` is more efficient, since it avoids the overhead of constructing and destructing the sentry object once per character.
### Example
```
#include <iostream>
#include <sstream>
#include <iterator>
#include <numeric>
#include <algorithm>
int main()
{
std::istringstream str("0.1 0.2 0.3 0.4");
std::partial_sum(std::istream_iterator<double>(str),
std::istream_iterator<double>(),
std::ostream_iterator<double>(std::cout, " "));
std::istringstream str2("1 3 5 7 8 9 10");
auto it = std::find_if(std::istream_iterator<int>(str2),
std::istream_iterator<int>(),
[](int i){return i%2 == 0;});
if (it != std::istream_iterator<int>())
std::cout << "\nThe first even number is " << *it << ".\n";
//" 9 10" left in the stream
}
```
Output:
```
0.1 0.3 0.6 1
The first even number is 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 |
| --- | --- | --- | --- |
| [P0738R2](https://wg21.link/P0738R2) | C++98 | the first read may be deferred to the first dereferencing | the first read is performed in the constructor |
### See also
| | |
| --- | --- |
| [ostream\_iterator](ostream_iterator "cpp/iterator/ostream iterator") | output iterator that writes to `[std::basic\_ostream](../io/basic_ostream "cpp/io/basic ostream")` (class template) |
| [istreambuf\_iterator](istreambuf_iterator "cpp/iterator/istreambuf iterator") | input iterator that reads from `[std::basic\_streambuf](../io/basic_streambuf "cpp/io/basic streambuf")` (class template) |
cpp std::indirectly_readable_traits std::indirectly\_readable\_traits
=================================
| Defined in header `[<iterator>](../header/iterator "cpp/header/iterator")` | | |
| --- | --- | --- |
|
```
template< class I >
struct indirectly_readable_traits { };
```
| (1) | (since C++20) |
|
```
template< class T >
struct indirectly_readable_traits<T*>;
```
| (2) | (since C++20) |
|
```
template< class I >
requires std::is_array_v<I>
struct indirectly_readable_traits<I>;
```
| (3) | (since C++20) |
|
```
template< class T >
struct indirectly_readable_traits<const T> :
indirectly_readable_traits<T> { };
```
| (4) | (since C++20) |
|
```
template </*has-member-value-type*/ T>
struct indirectly_readable_traits<T>;
```
| (5) | (since C++20) |
|
```
template </*has-member-element-type*/ T>
struct indirectly_readable_traits<T>;
```
| (6) | (since C++20) |
|
```
template </*has-member-value-type*/ T>
requires /*has-member-element-type*/<T>
struct indirectly_readable_traits<T> { };
```
| (7) | (since C++20) |
|
```
template </*has-member-value-type*/ T>
requires /*has-member-element-type*/<T> &&
std::same_as<std::remove_cv_t<typename T::element_type>,
std::remove_cv_t<typename T::value_type>>
struct indirectly_readable_traits<T>;
```
| (8) | (since C++20) |
Computes the associated value type of the type `I`, if any. Users may specialize `indirectly_readable_traits` for a program-defined type.
1) Primary template has no member `value_type`.
2) Specialization for pointers. If `T` is an object type, provides a member type `value_type` equal to `[std::remove\_cv\_t](http://en.cppreference.com/w/cpp/types/remove_cv)<T>`. Otherwise, there is no member `value_type`.
3) Specialization for array types. Provides a member type `value_type` equal to `[std::remove\_cv\_t](http://en.cppreference.com/w/cpp/types/remove_cv)<[std::remove\_extent\_t](http://en.cppreference.com/w/cpp/types/remove_extent)<I>>`.
4) Specialization for const-qualified types.
5) Specialization for types that define a public and accessible member type `value_type` (e.g., `[std::reverse\_iterator](reverse_iterator "cpp/iterator/reverse iterator")`). If `T::value_type` is an object type, provides a member type `value_type` equal to `[std::remove\_cv\_t](http://en.cppreference.com/w/cpp/types/remove_cv)<typename T::value\_type>`. Otherwise, there is no member `value_type`.
6) Specialization for types that define a public and accessible member type `element_type` (e.g., `[std::shared\_ptr](../memory/shared_ptr "cpp/memory/shared ptr")`). If `T::element_type` is an object type, provides a member type `value_type` equal to `[std::remove\_cv\_t](http://en.cppreference.com/w/cpp/types/remove_cv)<typename T::element\_type>`. Otherwise, there is no member `value_type`.
7-8) Specialization for types that define public and accessible member types `value_type` and `element_type` (e.g., [`std::span`](../container/span "cpp/container/span")). If both `T::value_type` and `T::element_type` are object types and they become the same type after removing cv-qualifiers on the top-level, provides a member type `value_type` equal to `[std::remove\_cv\_t](http://en.cppreference.com/w/cpp/types/remove_cv)<typename T::value\_type>`. Otherwise, there is no member `value_type`. ### Notes
`value_type` is intended for use with [`indirectly_readable`](indirectly_readable "cpp/iterator/indirectly readable") types such as iterators. It is not intended for use with ranges.
### 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 3446](https://cplusplus.github.io/LWG/issue3446) | C++20 | specializations were ambiguous for types containingboth `value_type` and `element_type` member types | a disambiguating specialization added |
| [LWG 3541](https://cplusplus.github.io/LWG/issue3541) | C++20 | LWG 3446 introduced hard error for ambiguous cases that`value_type` and `element_type` are different | made resulting substitution failure |
### See also
| | |
| --- | --- |
| [indirectly\_readable](indirectly_readable "cpp/iterator/indirectly readable")
(C++20) | specifies that a type is indirectly readable by applying operator `*` (concept) |
| [iter\_value\_titer\_reference\_titer\_const\_reference\_titer\_difference\_titer\_rvalue\_reference\_titer\_common\_reference\_t](iter_t "cpp/iterator/iter t")
(C++20)(C++20)(C++23)(C++20)(C++20)(C++20) | computes the associated types of an iterator (alias template) |
| [iterator\_traits](iterator_traits "cpp/iterator/iterator traits") | provides uniform interface to the properties of an iterator (class template) |
cpp std::indirect_strict_weak_order std::indirect\_strict\_weak\_order
==================================
| Defined in header `[<iterator>](../header/iterator "cpp/header/iterator")` | | |
| --- | --- | --- |
|
```
template< class F, class I1, class I2 = I1 >
concept indirect_strict_weak_order =
std::indirectly_readable<I1> &&
std::indirectly_readable<I2> &&
std::copy_constructible<F> &&
std::strict_weak_order<F&, std::iter_value_t<I1>&, std::iter_value_t<I2>&> &&
std::strict_weak_order<F&, std::iter_value_t<I1>&, std::iter_reference_t<I2>> &&
std::strict_weak_order<F&, std::iter_reference_t<I1>, std::iter_value_t<I2>&> &&
std::strict_weak_order<F&, std::iter_reference_t<I1>, std::iter_reference_t<I2>> &&
std::strict_weak_order<F&, std::iter_common_reference_t<I1>, std::iter_common_reference_t<I2>>;
```
| | (since C++20) |
The concept `indirect_strict_weak_order` specifies requirements for algorithms that call strict weak orders as their arguments. The key difference between this concept and `[std::strict\_weak\_order](../concepts/strict_weak_order "cpp/concepts/strict weak order")` is that it is applied to the types that `I1` and `I2` references, rather than `I1` and `I2` themselves.
### Semantic requirements
`F`, `I1`, and `I2` model `indirect_strict_weak_order` only if all concepts it subsumes are modeled.
cpp std::random_access_iterator std::random\_access\_iterator
=============================
| Defined in header `[<iterator>](../header/iterator "cpp/header/iterator")` | | |
| --- | --- | --- |
|
```
template<class I>
concept random_access_iterator =
std::bidirectional_iterator<I> &&
std::derived_from</*ITER_CONCEPT*/<I>, std::random_access_iterator_tag> &&
std::totally_ordered<I> &&
std::sized_sentinel_for<I, I> &&
requires(I i, const I j, const std::iter_difference_t<I> n) {
{ i += n } -> std::same_as<I&>;
{ j + n } -> std::same_as<I>;
{ n + j } -> std::same_as<I>;
{ i -= n } -> std::same_as<I&>;
{ j - n } -> std::same_as<I>;
{ j[n] } -> std::same_as<std::iter_reference_t<I>>;
};
```
| | (since C++20) |
The concept `random_access_iterator` refines [`bidirectional_iterator`](bidirectional_iterator "cpp/iterator/bidirectional iterator") by adding support for constant time advancement with the `+=`, `+`, `-=`, and `-` operators, constant time computation of distance with `-`, and array notation with subscripting.
### Iterator concept determination
Definition of this concept is specified via an exposition-only alias template `/*ITER_CONCEPT*/`.
In order to determine `/*ITER_CONCEPT*/<I>`, let `ITER_TRAITS<I>` denote `I` if the specialization `[std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<I>` is generated from the primary template, or `[std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<I>` otherwise:
* If `ITER_TRAITS<I>::iterator_concept` is valid and names a type, `/*ITER_CONCEPT*/<I>` denotes the type.
* Otherwise, if `ITER_TRAITS<I>::iterator_category` is valid and names a type, `/*ITER_CONCEPT*/<I>` denotes the type.
* Otherwise, if `[std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<I>` is generated from the primary template, `/*ITER_CONCEPT*/<I>` denotes `[std::random\_access\_iterator\_tag](iterator_tags "cpp/iterator/iterator tags")`.
* Otherwise, `/*ITER_CONCEPT*/<I>` does not denote a type and results in a substitution failure.
### Semantic requirements
Let `a` and `b` be valid iterators of type `I` such that `b` is reachable from `a`, and let `n` be a value of type `[std::iter\_difference\_t](http://en.cppreference.com/w/cpp/iterator/iter_t)<I>` equal to `b - a`. `random_access_iterator<I>` is modeled only if all the concepts it subsumes are modeled and:
* `(a += n)` is equal to `b`.
* `[std::addressof](http://en.cppreference.com/w/cpp/memory/addressof)(a += n)` is equal to `[std::addressof](http://en.cppreference.com/w/cpp/memory/addressof)(a)`.
* `(a + n)` is equal to `(a += n)`.
* `(a + n)` is equal to `(n + a)`.
* For any two positive integers `x` and `y`, if `a + (x + y)` is valid, then `a + (x + y)` is equal to `(a + x) + y`.
* `a + 0` is equal to `a`.
* If `(a + (n - 1))` is valid, then `--b` is equal to `(a + (n - 1))`.
* `(b += -n)` and `(b -= n)` are both equal to `a`.
* `[std::addressof](http://en.cppreference.com/w/cpp/memory/addressof)(b -= n)` is equal to `[std::addressof](http://en.cppreference.com/w/cpp/memory/addressof)(b)`.
* `(b - n)` is equal to `(b -= n)`.
* If `b` is dereferenceable, then `a[n]` is valid and is equal to `*b`.
* `bool(a <= b)` is `true`.
* Every required operation has constant time complexity.
### Equality preservation
An expression is *equality preserving* if it results in equal outputs given equal inputs.
* The inputs to an expression consist of its operands.
* The outputs of an expression consist of its result and all operands modified by the expression (if any).
In specification of standard concepts, operands are defined as the largest subexpressions that include only:
* an [id-expression](../language/expressions#Primary_expressions "cpp/language/expressions"), and
* invocations of [`std::move`](../utility/move "cpp/utility/move"), `[std::forward](../utility/forward "cpp/utility/forward")`, and `[std::declval](../utility/declval "cpp/utility/declval")`.
The cv-qualification and value category of each operand is determined by assuming that each template type parameter denotes a cv-unqualified complete non-array object type.
Every expression required to be equality preserving is further required to be *stable*: two evaluations of such an expression with the same input objects must have equal outputs absent any explicit intervening modification of those input objects.
Unless noted otherwise, every expression used in a *requires-expression* is required to be equality preserving and stable, and the evaluation of the expression may modify only its non-constant operands. Operands that are constant must not be modified.
### Implicit expression variations
A *requires-expression* that uses an expression that is non-modifying for some constant lvalue operand also implicitly requires additional variations of that expression that accept a non-constant lvalue or (possibly constant) rvalue for the given operand unless such an expression variation is explicitly required with differing semantics. These *implicit expression variations* must meet the same semantic requirements of the declared expression. The extent to which an implementation validates the syntax of the variations is unspecified.
### Notes
Unlike the [LegacyRandomAccessIterator](../named_req/randomaccessiterator "cpp/named req/RandomAccessIterator") requirements, the `random_access_iterator` concept does not require dereference to return an lvalue.
### Example
Demonstrates a possible implementation of `[std::distance](distance "cpp/iterator/distance")` via C++20 concepts.
```
#include <iterator>
namespace cxx20 {
template<std::input_or_output_iterator Iter>
constexpr std::iter_difference_t<Iter> distance(Iter first, Iter last)
{
if constexpr(std::random_access_iterator<Iter>)
return last - first;
else
{
std::iter_difference_t<Iter> result{};
for (;first != last;++first)
++result;
return result;
}
}
}
int main() {
static constexpr auto il = { 3, 1, 4 };
static_assert(cxx20::distance(il.begin(), il.end()) == 3);
static_assert(cxx20::distance(il.end(), il.begin()) == -3);
}
```
### See also
| | |
| --- | --- |
| [bidirectional\_iterator](bidirectional_iterator "cpp/iterator/bidirectional iterator")
(C++20) | specifies that a [`forward_iterator`](forward_iterator "cpp/iterator/forward iterator") is a bidirectional iterator, supporting movement backwards (concept) |
cpp std::ostream_iterator std::ostream\_iterator
======================
| Defined in header `[<iterator>](../header/iterator "cpp/header/iterator")` | | |
| --- | --- | --- |
|
```
template< class T,
class CharT = char,
class Traits = std::char_traits<CharT> >
class ostream_iterator : public std::iterator<std::output_iterator_tag,
void, void, void, void>
```
| | (until C++17) |
|
```
template< class T,
class CharT = char,
class Traits = std::char_traits<CharT>>
class ostream_iterator;
```
| | (since C++17) |
`std::ostream_iterator` is a single-pass [LegacyOutputIterator](../named_req/outputiterator "cpp/named req/OutputIterator") that writes successive objects of type `T` into the `[std::basic\_ostream](../io/basic_ostream "cpp/io/basic ostream")` object for which it was constructed, using `operator<<`. Optional delimiter string is written to the output stream after every write operation. The write operation is performed when the iterator (whether dereferenced or not) is assigned to. Incrementing the `std::ostream_iterator` is a no-op.
In a typical implementation, the only data members of `std::ostream_iterator` are a pointer to the associated `std::basic_ostream` and a pointer to the first character in the delimiter string.
When writing characters, `[std::ostreambuf\_iterator](ostreambuf_iterator "cpp/iterator/ostreambuf iterator")` is more efficient, since it avoids the overhead of constructing and destructing the sentry object once per character.
### Member types
| Member type | Definition |
| --- | --- |
| `iterator_category` | `[std::output\_iterator\_tag](http://en.cppreference.com/w/cpp/iterator/iterator_tags)` |
| `value_type` | `void` |
| `difference_type` |
| | |
| --- | --- |
| `void`. | (until C++20) |
| `[std::ptrdiff\_t](http://en.cppreference.com/w/cpp/types/ptrdiff_t)`. | (since C++20) |
|
| `pointer` | `void` |
| `reference` | `void` |
| `char_type` | `CharT` |
| `traits_type` | `Traits` |
| `ostream_type` | `[std::basic\_ostream](http://en.cppreference.com/w/cpp/io/basic_ostream)<CharT, Traits>` |
| | |
| --- | --- |
| Member types `iterator_category`, `value_type`, `difference_type`, `pointer` and `reference` are required to be obtained by inheriting from `[std::iterator](http://en.cppreference.com/w/cpp/iterator/iterator)<[std::output\_iterator\_tag](http://en.cppreference.com/w/cpp/iterator/iterator_tags), void, void, void, void>`. | (until C++17) |
### Member functions
| | |
| --- | --- |
| [(constructor)](ostream_iterator/ostream_iterator "cpp/iterator/ostream iterator/ostream iterator") | constructs a new ostream\_iterator (public member function) |
| [(destructor)](ostream_iterator/~ostream_iterator "cpp/iterator/ostream iterator/~ostream iterator") | destructs an `ostream_iterator` (public member function) |
| [operator=](ostream_iterator/operator= "cpp/iterator/ostream iterator/operator=") | writes a object to the associated output sequence (public member function) |
| [operator\*](ostream_iterator/operator* "cpp/iterator/ostream iterator/operator*") | no-op (public member function) |
| [operator++operator++(int)](ostream_iterator/operator_arith "cpp/iterator/ostream iterator/operator arith") | no-op (public member function) |
### Example
```
#include <iostream>
#include <sstream>
#include <iterator>
#include <numeric>
int main()
{
std::istringstream str("0.1 0.2 0.3 0.4");
std::partial_sum(std::istream_iterator<double>(str),
std::istream_iterator<double>(),
std::ostream_iterator<double>(std::cout, ","));
}
```
Output:
```
0.1,0.3,0.6,1,
```
### See also
| | |
| --- | --- |
| [ostreambuf\_iterator](ostreambuf_iterator "cpp/iterator/ostreambuf iterator") | output iterator that writes to `[std::basic\_streambuf](../io/basic_streambuf "cpp/io/basic streambuf")` (class template) |
| [istream\_iterator](istream_iterator "cpp/iterator/istream iterator") | input iterator that reads from `[std::basic\_istream](../io/basic_istream "cpp/io/basic istream")` (class template) |
| [std::experimental::ostream\_joiner](https://en.cppreference.com/w/cpp/experimental/ostream_joiner "cpp/experimental/ostream joiner")
(library fundamentals TS v2) | An output iterator that writes successive elements into an output stream, separating adjacent elements with a delimiter (class template) |
| programming_docs |
cpp std::move_iterator std::move\_iterator
===================
| Defined in header `[<iterator>](../header/iterator "cpp/header/iterator")` | | |
| --- | --- | --- |
|
```
template< class Iter >
class move_iterator;
```
| | (since C++11) |
`std::move_iterator` is an iterator adaptor which behaves exactly like the underlying iterator (which must be at least an [LegacyInputIterator](../named_req/inputiterator "cpp/named req/InputIterator") or model [`input_iterator`](input_iterator "cpp/iterator/input iterator") (since C++20) or stronger iterator concept (since C++23)), except that dereferencing converts the value returned by the underlying iterator into an rvalue. If this iterator is used as an input iterator, the effect is that the values are moved from, rather than copied from.
### Member types
| Member type | Definition |
| --- | --- |
| `iterator_type` | `Iter` |
| `iterator_category` |
| | |
| --- | --- |
| `[std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<Iter>::iterator\_category`. | (until C++20) |
| If `[std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<Iter>::iterator\_category` is valid and denotes a type:* if `[std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<Iter>::iterator\_category` models `[std::derived\_from](http://en.cppreference.com/w/cpp/concepts/derived_from)<[std::random\_access\_iterator\_tag](http://en.cppreference.com/w/cpp/iterator/iterator_tags)>`, member `iterator_category` is `[std::random\_access\_iterator\_tag](iterator_tags "cpp/iterator/iterator tags")`.
* Otherwise, member `iterator_category` is the same type as `[std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<Iter>::iterator\_category`.
Otherwise, there is no member `iterator_category`. | (since C++20) |
|
| `iterator_concept` |
| | |
| --- | --- |
| `[std::input\_iterator\_tag](iterator_tags "cpp/iterator/iterator tags")`. | (since C++20)(until C++23) |
| * `[std::random\_access\_iterator\_tag](iterator_tags "cpp/iterator/iterator tags")`, if `Iter` models`[std::random\_access\_iterator](random_access_iterator "cpp/iterator/random access iterator")`. Otherwise,
* `[std::bidirectional\_iterator\_tag](iterator_tags "cpp/iterator/iterator tags")`, if `Iter` models`[std::bidirectional\_iterator](bidirectional_iterator "cpp/iterator/bidirectional iterator")`. Otherwise,
* `[std::forward\_iterator\_tag](iterator_tags "cpp/iterator/iterator tags")`, if `Iter` models`[std::forward\_iterator](forward_iterator "cpp/iterator/forward iterator")`. Otherwise,
* `[std::input\_iterator\_tag](iterator_tags "cpp/iterator/iterator tags")`.
| (since C++23) |
|
| `value_type` |
| | |
| --- | --- |
| `[std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<Iter>::value\_type`. | (until C++20) |
| `[std::iter\_value\_t](http://en.cppreference.com/w/cpp/iterator/iter_t)<Iter>` | (since C++20) |
|
| `difference_type` |
| | |
| --- | --- |
| `[std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<Iter>::difference\_type`. | (until C++20) |
| `[std::iter\_difference\_t](http://en.cppreference.com/w/cpp/iterator/iter_t)<Iter>` | (since C++20) |
|
| `pointer` | `Iter` |
| `reference` |
| | |
| --- | --- |
| If `[std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<Iter>::reference` is a reference, this is the rvalue reference version of the same type. Otherwise (such as if the wrapped iterator returns by value), this is `[std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<Iter>::reference` unchanged. | (until C++20) |
| `[std::iter\_rvalue\_reference\_t](http://en.cppreference.com/w/cpp/iterator/iter_t)<Iter>` | (since C++20) |
|
### Member functions
| | |
| --- | --- |
| [(constructor)](move_iterator/move_iterator "cpp/iterator/move iterator/move iterator")
(C++11) | constructs a new iterator adaptor (public member function) |
| [operator=](move_iterator/operator= "cpp/iterator/move iterator/operator=")
(C++11) | assigns another iterator adaptor (public member function) |
| [base](move_iterator/base "cpp/iterator/move iterator/base")
(C++11) | accesses the underlying iterator (public member function) |
| [operator\*operator->](move_iterator/operator* "cpp/iterator/move iterator/operator*")
(C++11)(C++11)(deprecated in C++20) | accesses the pointed-to element (public member function) |
| [operator[]](move_iterator/operator_at "cpp/iterator/move iterator/operator at")
(C++11) | accesses an element by index (public member function) |
| [operator++operator++(int)operator+=operator+operator--operator--(int)operator-=operator-](move_iterator/operator_arith "cpp/iterator/move iterator/operator arith")
(C++11) | advances or decrements the iterator (public member function) |
### Member objects
| Member name | Definition |
| --- | --- |
| `*current*` (private) | the underlying iterator from which [`base()`](move_iterator/base "cpp/iterator/move iterator/base") copies or moves (since C++20), the name is for exposition only |
### Non-member functions
| | |
| --- | --- |
| [operator==operator!=operator<operator<=operator>operator>=operator<=>](move_iterator/operator_cmp "cpp/iterator/move iterator/operator cmp")
(C++11)(C++11)(removed in C++20)(C++11)(C++11)(C++11)(C++11)(C++20) | compares the underlying iterators (function template) |
| [operator==(std::move\_sentinel)](move_iterator/operator_cmp2 "cpp/iterator/move iterator/operator cmp2")
(C++20) | compares the underlying iterator and the underlying sentinel (function template) |
| [operator+](move_iterator/operator_plus_ "cpp/iterator/move iterator/operator+")
(C++11) | advances the iterator (function template) |
| [operator-](move_iterator/operator- "cpp/iterator/move iterator/operator-")
(C++11) | computes the distance between two iterator adaptors (function template) |
| [operator-(std::move\_sentinel)](move_iterator/operator-2 "cpp/iterator/move iterator/operator-2")
(C++20) | computes the distance between the underlying iterator and the underlying sentinel (function template) |
| [iter\_move](move_iterator/iter_move "cpp/iterator/move iterator/iter move")
(C++20) | casts the result of dereferencing the underlying iterator to its associated rvalue reference type (function) |
| [iter\_swap](move_iterator/iter_swap "cpp/iterator/move iterator/iter swap")
(C++20) | swaps the objects pointed to by two underlying iterators (function template) |
| [make\_move\_iterator](make_move_iterator "cpp/iterator/make move iterator")
(C++11) | creates a `std::move_iterator` of type inferred from the argument (function template) |
### Notes
| [Feature-test](../utility/feature_test "cpp/utility/feature test") macro |
| --- |
| [`__cpp_lib_move_iterator_concept`](../feature_test#Library_features "cpp/feature test") |
### Example
```
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <iterator>
#include <numeric>
#include <string>
int main()
{
std::vector<std::string> v{"this", "_", "is", "_", "an", "_", "example"};
auto print_v = [&](auto const rem) {
std::cout << rem;
for (const auto& s : v)
std::cout << std::quoted(s) << ' ';
std::cout << '\n';
};
print_v("Old contents of the vector: ");
std::string concat = std::accumulate(std::make_move_iterator(v.begin()),
std::make_move_iterator(v.end()),
std::string());
/* An alternative that uses std::move_iterator directly could be:
using moviter_t = std::move_iterator<std::vector<std::string>::iterator>;
std::string concat = std::accumulate(moviter_t(v.begin()),
moviter_t(v.end()),
std::string()); */
print_v("New contents of the vector: ");
std::cout << "Concatenated as string: " << quoted(concat) << '\n';
}
```
Possible output:
```
Old contents of the vector: "this" "_" "is" "_" "an" "_" "example"
New contents of the vector: "" "" "" "" "" "" ""
Concatenated as string: "this_is_an_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 2106](https://cplusplus.github.io/LWG/issue2106) | C++11 | dereferencing a `move_iterator` could return a dangling referenceif the dereferencing the underlying iterator returns a prvalue | returns the object instead |
| [P2259R1](https://wg21.link/P2259R1) | C++20 | member `iterator_category` was always defined | defined only if`[std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<Iter>::iterator\_category` exists |
### See also
| | |
| --- | --- |
| [make\_move\_iterator](make_move_iterator "cpp/iterator/make move iterator")
(C++11) | creates a `std::move_iterator` of type inferred from the argument (function template) |
| [move\_sentinel](move_sentinel "cpp/iterator/move sentinel")
(C++20) | sentinel adaptor for use with `std::move_iterator` (class template) |
cpp std::mergeable std::mergeable
==============
| Defined in header `[<iterator>](../header/iterator "cpp/header/iterator")` | | |
| --- | --- | --- |
|
```
template< class I1, class I2, class Out, class Comp = ranges::less,
class Proj1 = std::identity, class Proj2 = std::identity >
concept mergeable =
std::input_iterator<I1> &&
std::input_iterator<I2> &&
std::weakly_incrementable<Out> &&
std::indirectly_copyable<I1, Out> &&
std::indirectly_copyable<I2, Out> &&
std::indirect_strict_weak_order<Comp,
std::projected<I1, Proj1>,
std::projected<I2, Proj2>>;
```
| | (since C++20) |
The `mergeable` concept specifies the requirements for algorithms that merge two input ranges into a single output range according to the strict weak ordering imposed by `Comp`.
### Semantic requirements
`mergeable` is modeled only if all concepts it subsumes are modeled.
### See also
| | |
| --- | --- |
| [ranges::merge](../algorithm/ranges/merge "cpp/algorithm/ranges/merge")
(C++20) | merges two sorted ranges (niebloid) |
| [ranges::set\_union](../algorithm/ranges/set_union "cpp/algorithm/ranges/set union")
(C++20) | computes the union of two sets (niebloid) |
| [ranges::set\_intersection](../algorithm/ranges/set_intersection "cpp/algorithm/ranges/set intersection")
(C++20) | computes the intersection of two sets (niebloid) |
| [ranges::set\_difference](../algorithm/ranges/set_difference "cpp/algorithm/ranges/set difference")
(C++20) | computes the difference between two sets (niebloid) |
| [ranges::set\_symmetric\_difference](../algorithm/ranges/set_symmetric_difference "cpp/algorithm/ranges/set symmetric difference")
(C++20) | computes the symmetric difference between two sets (niebloid) |
cpp std::weakly_incrementable std::weakly\_incrementable
==========================
| Defined in header `[<iterator>](../header/iterator "cpp/header/iterator")` | | |
| --- | --- | --- |
|
```
template<class I>
concept weakly_incrementable =
std::movable<I> &&
requires(I i) {
typename std::iter_difference_t<I>;
requires /*is-signed-integer-like*/<std::iter_difference_t<I>>;
{ ++i } -> std::same_as<I&>; // not required to be equality-preserving
i++; // not required to be equality-preserving
};
```
| | (since C++20) |
where `/*is-signed-integer-like*/<I>` is `true` if and only if `I` is a signed-integer-like type (see below).
This concept specifies requirements on types that can be incremented with the pre- and post-increment operators, but those increment operations are not necessarily equality-preserving, and the type itself is not required to be `[std::equality\_comparable](../concepts/equality_comparable "cpp/concepts/equality comparable")`.
For `std::weakly_incrementable` types, `a == b` does not imply that `++a == ++b`. Algorithms on weakly incrementable types must be single-pass algorithms. These algorithms can be used with istreams as the source of the input data through `[std::istream\_iterator](istream_iterator "cpp/iterator/istream iterator")`.
### Semantic requirements
`I` models `std::weakly_incrementable` only if, for an object `i` of type `I`:
* The expressions `++i` and `i++` have the same domain,
* If `i` is incrementable, then both `++i` and `i++` advance `i`, and
* If `i` is incrementable, then `[std::addressof](http://en.cppreference.com/w/cpp/memory/addressof)(++i) == [std::addressof](http://en.cppreference.com/w/cpp/memory/addressof)(i)`.
### Integer-like types
An integer-like type is an (possibly cv-qualified) integer type (except for *cv* `bool`) or an implementation-provided (not user-provided) class that behaves like an integer type, including all operators, implicit conversions, and `[std::numeric\_limits](../types/numeric_limits "cpp/types/numeric limits")` specializations. If an integer-like type represents only non-negative values, it is unsigned-integer-like, otherwise it is signed-integer-like.
### 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 3467](https://cplusplus.github.io/LWG/issue3467) | C++20 | `bool` was considered as an integer-like type | excluded |
| [P2325R3](https://wg21.link/P2325R3) | C++20 | [`default_initializable`](../concepts/default_initializable "cpp/concepts/default initializable") was required | not required |
### See also
| | |
| --- | --- |
| [incrementable](incrementable "cpp/iterator/incrementable")
(C++20) | specifies that the increment operation on a **`weakly_incrementable`** type is equality-preserving and that the type is [`equality_comparable`](../concepts/equality_comparable "cpp/concepts/equality comparable") (concept) |
cpp std::data std::data
=========
| Defined in header `[<array>](../header/array "cpp/header/array")` | | |
| --- | --- | --- |
| Defined in header `[<deque>](../header/deque "cpp/header/deque")` | | |
| Defined in header `[<forward\_list>](../header/forward_list "cpp/header/forward list")` | | |
| Defined in header `[<iterator>](../header/iterator "cpp/header/iterator")` | | |
| Defined in header `[<list>](../header/list "cpp/header/list")` | | |
| Defined in header `[<map>](../header/map "cpp/header/map")` | | |
| Defined in header `[<regex>](../header/regex "cpp/header/regex")` | | |
| Defined in header `[<set>](../header/set "cpp/header/set")` | | |
| Defined in header `[<span>](../header/span "cpp/header/span")` | | (since C++20) |
| Defined in header `[<string>](../header/string "cpp/header/string")` | | |
| Defined in header `[<string\_view>](../header/string_view "cpp/header/string view")` | | |
| Defined in header `[<unordered\_map>](../header/unordered_map "cpp/header/unordered map")` | | |
| Defined in header `[<unordered\_set>](../header/unordered_set "cpp/header/unordered set")` | | |
| Defined in header `[<vector>](../header/vector "cpp/header/vector")` | | |
|
```
template <class C>
constexpr auto data(C& c) -> decltype(c.data());
```
| (1) | (since C++17) |
|
```
template <class C>
constexpr auto data(const C& c) -> decltype(c.data());
```
| (2) | (since C++17) |
|
```
template <class T, std::size_t N>
constexpr T* data(T (&array)[N]) noexcept;
```
| (3) | (since C++17) |
|
```
template <class E>
constexpr const E* data(std::initializer_list<E> il) noexcept;
```
| (4) | (since C++17) |
Returns a pointer to the block of memory containing the elements of the range.
1,2) returns `c.data()`
3) returns `array`
4) returns `il.begin()`
### Parameters
| | | |
| --- | --- | --- |
| c | - | a container or view with a `data()` member function |
| array | - | an array of arbitrary type |
| il | - | an initializer list |
### Return value
A pointer to the block of memory containing the elements of the range.
### Exceptions
1) May throw implementation-defined exceptions. ### Notes
The overload for `[std::initializer\_list](../utility/initializer_list "cpp/utility/initializer list")` is necessary because it does not have a member function `data`.
| [Feature-test](../utility/feature_test "cpp/utility/feature test") macro |
| --- |
| [`__cpp_lib_nonmember_container_access`](../feature_test#Library_features "cpp/feature test") |
### Possible implementation
| First version |
| --- |
|
```
template <class C>
constexpr auto data(C& c) -> decltype(c.data())
{
return c.data();
}
```
|
| Second version |
|
```
template <class C>
constexpr auto data(const C& c) -> decltype(c.data())
{
return c.data();
}
```
|
| Third version |
|
```
template <class T, std::size_t N>
constexpr T* data(T (&array)[N]) noexcept
{
return array;
}
```
|
| Fourth version |
|
```
template <class E>
constexpr const E* data(std::initializer_list<E> il) noexcept
{
return il.begin();
}
```
|
### Example
```
#include <string>
#include <cstring>
#include <iostream>
int main()
{
std::string s {"Hello world!\n"};
char a[20]; // storage for a C-style string
std::strcpy(a, std::data(s));
// [s.data(), s.data() + s.size()] is guaranteed to be an NTBS since C++11
std::cout << a;
}
```
Output:
```
Hello world!
```
### See also
| | |
| --- | --- |
| [ranges::data](../ranges/data "cpp/ranges/data")
(C++20) | obtains a pointer to the beginning of a contiguous range (customization point object) |
| [ranges::cdata](../ranges/cdata "cpp/ranges/cdata")
(C++20) | obtains a pointer to the beginning of a read-only contiguous range (customization point object) |
cpp std::forward_iterator std::forward\_iterator
======================
| Defined in header `[<iterator>](../header/iterator "cpp/header/iterator")` | | |
| --- | --- | --- |
|
```
template<class I>
concept forward_iterator =
std::input_iterator<I> &&
std::derived_from</*ITER_CONCEPT*/<I>, std::forward_iterator_tag> &&
std::incrementable<I> &&
std::sentinel_for<I, I>;
```
| | (since C++20) |
This concept refines `[std::input\_iterator](http://en.cppreference.com/w/cpp/iterator/input_iterator)` by requiring that `I` also model `std::incrementable` (thereby making it suitable for multi-pass algorithms), and guaranteeing that two iterators to the same range can be compared against each other.
### Iterator concept determination
Definition of this concept is specified via an exposition-only alias template `/*ITER_CONCEPT*/`.
In order to determine `/*ITER_CONCEPT*/<I>`, let `ITER_TRAITS<I>` denote `I` if the specialization `[std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<I>` is generated from the primary template, or `[std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<I>` otherwise:
* If `ITER_TRAITS<I>::iterator_concept` is valid and names a type, `/*ITER_CONCEPT*/<I>` denotes the type.
* Otherwise, if `ITER_TRAITS<I>::iterator_category` is valid and names a type, `/*ITER_CONCEPT*/<I>` denotes the type.
* Otherwise, if `[std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<I>` is generated from the primary template, `/*ITER_CONCEPT*/<I>` denotes `[std::random\_access\_iterator\_tag](iterator_tags "cpp/iterator/iterator tags")`.
* Otherwise, `/*ITER_CONCEPT*/<I>` does not denote a type and results in a substitution failure.
### Semantic requirements
`I` models `std::forward_iterator` if, and only if `I` models all the concepts it subsumes, and given objects `i` and `j` of type `I`:
* Comparison between iterators `i` and `j` has a defined result if
+ `i` and `j` are iterators to the same underlying sequence, or
+ both `i` and `j` are value-initialized, in which case they compare equal.
* Pointers and references obtained from a forward iterator into a range remain valid while the range exists.
* If `i` and `j` are dereferenceable, they offer the *multi-pass guarantee*, that is:
+ `i == j` implies `++i == ++j`, and
+ `((void)[](auto x){ ++x; }(i), *i)` is equivalent to `*i`.
### Notes
Unlike the [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator") requirements, the `forward_iterator` concept does not require dereference to return an lvalue.
### See also
| | |
| --- | --- |
| [input\_iterator](input_iterator "cpp/iterator/input iterator")
(C++20) | specifies that a type is an input iterator, that is, its referenced values can be read and it can be both pre- and post-incremented (concept) |
| programming_docs |
cpp std::indirectly_unary_invocable, std::indirectly_regular_unary_invocable std::indirectly\_unary\_invocable, std::indirectly\_regular\_unary\_invocable
=============================================================================
| Defined in header `[<iterator>](../header/iterator "cpp/header/iterator")` | | |
| --- | --- | --- |
|
```
template< class F, class I >
concept indirectly_unary_invocable =
std::indirectly_readable<I> &&
std::copy_constructible<F> &&
std::invocable<F&, std::iter_value_t<I>&> &&
std::invocable<F&, std::iter_reference_t<I>> &&
std::invocable<F&, std::iter_common_reference_t<I>> &&
std::common_reference_with<
std::invoke_result_t<F&, std::iter_value_t<I>&>,
std::invoke_result_t<F&, std::iter_reference_t<I>>>;
```
| | (since C++20) |
|
```
template< class F, class I >
concept indirectly_regular_unary_invocable =
std::indirectly_readable<I> &&
std::copy_constructible<F> &&
std::regular_invocable<F&, std::iter_value_t<I>&> &&
std::regular_invocable<F&, std::iter_reference_t<I>> &&
std::regular_invocable<F&, std::iter_common_reference_t<I>> &&
std::common_reference_with<
std::invoke_result_t<F&, std::iter_value_t<I>&>,
std::invoke_result_t<F&, std::iter_reference_t<I>>>;
```
| | (since C++20) |
The concepts `indirectly_unary_invocable` and `indirectly_regular_unary_invocable` specify requirements for algorithms that call (regular) unary invocables as their arguments. The key difference between these concepts and `[std::invocable](../concepts/invocable "cpp/concepts/invocable")` is that they are applied to the type the `I` references, rather than `I` itself.
### Semantic requirements
Each concept is modeled by `F` and `I` only if all concepts it subsume are modeled.
### Notes
The distinction between `indirectly_unary_invocable` and `indirectly_regular_unary_invocable` is purely semantic.
cpp std::sentinel_for std::sentinel\_for
==================
| Defined in header `[<iterator>](../header/iterator "cpp/header/iterator")` | | |
| --- | --- | --- |
|
```
template<class S, class I>
concept sentinel_for =
std::semiregular<S> &&
std::input_or_output_iterator<I> &&
__WeaklyEqualityComparableWith<S, I>;
```
| | (since C++20) |
The `sentinel_for` concept specifies the relationship between an [`input_or_output_iterator`](input_or_output_iterator "cpp/iterator/input or output iterator") type and a [`semiregular`](../concepts/semiregular "cpp/concepts/semiregular") type whose values denote a range. The exposition-only concept `*\_\_WeaklyEqualityComparableWith*` is described in [`equality_comparable`](../concepts/equality_comparable "cpp/concepts/equality comparable").
### Semantic requirements
Let `s` and `i` be values of type `S` and `I`, respectively, such that `[i, s)` denotes a range. `sentinel_for<S, I>` is modeled only if:
* `i == s` is well-defined.
* If `bool(i != s)` then `i` is dereferenceable and `[++i, s)` denotes a range.
* `[std::assignable\_from](http://en.cppreference.com/w/cpp/concepts/assignable_from)<I&, S>` is either modeled or not satisfied.
The domain of `==` can change over time. Given an iterator `i` and sentinel `s` such that `[i, s)` denotes a range and `i != s`, `[i, s)` is not required to continue to denote a range after incrementing any iterator equal to `i` (and so `i == s` is no longer required to be well-defined after such an increment).
### Notes
A sentinel type and its corresponding iterator type are not required to model [`equality_comparable_with`](../concepts/equality_comparable "cpp/concepts/equality comparable"), because the sentinel type may not be comparable with itself, and they are not required to have a common reference type.
It has been permitted to use a sentinel type different from the iterator type in the [range-based `for` loop](../language/range-for "cpp/language/range-for") since C++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 3453](https://cplusplus.github.io/LWG/issue3453) | C++20 | semantic requirements for `sentinel_for` were too loose for `ranges::advance` | strengthened |
cpp std::indirectly_copyable_storable std::indirectly\_copyable\_storable
===================================
| Defined in header `[<iterator>](../header/iterator "cpp/header/iterator")` | | |
| --- | --- | --- |
|
```
template<class In, class Out>
concept indirectly_copyable_storable =
std::indirectly_copyable<In, Out> &&
std::indirectly_writable<Out, std::iter_value_t<In>&> &&
std::indirectly_writable<Out, const std::iter_value_t<In>&> &&
std::indirectly_writable<Out, std::iter_value_t<In>&&> &&
std::indirectly_writable<Out, const std::iter_value_t<In>&&> &&
std::copyable<std::iter_value_t<In>> &&
std::constructible_from<std::iter_value_t<In>, std::iter_reference_t<In>> &&
std::assignable_from<std::iter_value_t<In>&, std::iter_reference_t<In>>;
```
| | (since C++20) |
The `indirectly_copyable_storable` concept specifies the relationship between an [`indirectly_readable`](indirectly_readable "cpp/iterator/indirectly readable") type and an [`indirectly_writable`](indirectly_writable "cpp/iterator/indirectly writable") type. In addition to [`indirectly_copyable`](indirectly_copyable "cpp/iterator/indirectly copyable"), this concept specifies that the copy from the `indirectly_readable` type can be performed via an intermediate object.
### Semantic requirements
`In` and `Out` model `std::indirectly_copyable_storable<In, Out>` only if given a dereferenceable value `i` of type `In`:
* After the definition `[std::iter\_value\_t](http://en.cppreference.com/w/cpp/iterator/iter_t)<In> obj(\*i);`, `obj` is equal to the value previously denoted by `*i`, and
* if `[std::iter\_reference\_t](http://en.cppreference.com/w/cpp/iterator/iter_t)<In>` is an rvalue reference type, `*i` is placed in a valid but unspecified state after the initialization of `obj`.
### Equality preservation
An expression is *equality preserving* if it results in equal outputs given equal inputs.
* The inputs to an expression consist of its operands.
* The outputs of an expression consist of its result and all operands modified by the expression (if any).
In specification of standard concepts, operands are defined as the largest subexpressions that include only:
* an [id-expression](../language/expressions#Primary_expressions "cpp/language/expressions"), and
* invocations of [`std::move`](../utility/move "cpp/utility/move"), `[std::forward](../utility/forward "cpp/utility/forward")`, and `[std::declval](../utility/declval "cpp/utility/declval")`.
The cv-qualification and value category of each operand is determined by assuming that each template type parameter denotes a cv-unqualified complete non-array object type.
Every expression required to be equality preserving is further required to be *stable*: two evaluations of such an expression with the same input objects must have equal outputs absent any explicit intervening modification of those input objects.
Unless noted otherwise, every expression used in a *requires-expression* is required to be equality preserving and stable, and the evaluation of the expression may modify only its non-constant operands. Operands that are constant must not be modified.
### See also
| | |
| --- | --- |
| [indirectly\_copyable](indirectly_copyable "cpp/iterator/indirectly copyable")
(C++20) | specifies that values may be copied from an [`indirectly_readable`](indirectly_readable "cpp/iterator/indirectly readable") type to an [`indirectly_writable`](indirectly_writable "cpp/iterator/indirectly writable") type (concept) |
| [indirectly\_movable\_storable](indirectly_movable_storable "cpp/iterator/indirectly movable storable")
(C++20) | specifies that values may be moved from an [`indirectly_readable`](indirectly_readable "cpp/iterator/indirectly readable") type to an [`indirectly_writable`](indirectly_writable "cpp/iterator/indirectly writable") type and that the move may be performed via an intermediate object (concept) |
cpp std::iterator std::iterator
=============
| Defined in header `[<iterator>](../header/iterator "cpp/header/iterator")` | | |
| --- | --- | --- |
|
```
template<
class Category,
class T,
class Distance = std::ptrdiff_t,
class Pointer = T*,
class Reference = T&
> struct iterator;
```
| | (deprecated in C++17) |
`std::iterator` is the base class provided to simplify definitions of the required types for iterators.
### Template parameters
| | | |
| --- | --- | --- |
| Category | - | the category of the iterator. Must be one of [iterator category tags](iterator_tags "cpp/iterator/iterator tags"). |
| T | - | the type of the values that can be obtained by dereferencing the iterator. This type should be `void` for output iterators. |
| Distance | - | a type that can be used to identify distance between iterators |
| Pointer | - | defines a pointer to the type iterated over (`T`) |
| Reference | - | defines a reference to the type iterated over (`T`) |
### Member types
| Member type | Definition |
| --- | --- |
| `iterator_category` | `Category` |
| `value_type` | `T` |
| `difference_type` | `Distance` |
| `pointer` | `Pointer` |
| `reference` | `Reference` |
### Example
The following example shows how to implement an [input iterator](../named_req/inputiterator "cpp/named req/InputIterator") by inheriting from std::iterator.
```
#include <iostream>
#include <algorithm>
template<long FROM, long TO>
class Range {
public:
// member typedefs provided through inheriting from std::iterator
class iterator: public std::iterator<
std::input_iterator_tag, // iterator_category
long, // value_type
long, // difference_type
const long*, // pointer
long // reference
>{
long num = FROM;
public:
explicit iterator(long _num = 0) : num(_num) {}
iterator& operator++() {num = TO >= FROM ? num + 1: num - 1; return *this;}
iterator operator++(int) {iterator retval = *this; ++(*this); return retval;}
bool operator==(iterator other) const {return num == other.num;}
bool operator!=(iterator other) const {return !(*this == other);}
reference operator*() const {return num;}
};
iterator begin() {return iterator(FROM);}
iterator end() {return iterator(TO >= FROM? TO+1 : TO-1);}
};
int main() {
// std::find requires an input iterator
auto range = Range<15, 25>();
auto itr = std::find(range.begin(), range.end(), 18);
std::cout << *itr << '\n'; // 18
// Range::iterator also satisfies range-based for requirements
for(long l : Range<3, 5>()) {
std::cout << l << ' '; // 3 4 5
}
std::cout << '\n';
}
```
Output:
```
18
3 4 5
```
### See also
| | |
| --- | --- |
| [iterator\_traits](iterator_traits "cpp/iterator/iterator traits") | provides uniform interface to the properties of an iterator (class template) |
| [input\_iterator\_tagoutput\_iterator\_tagforward\_iterator\_tagbidirectional\_iterator\_tagrandom\_access\_iterator\_tagcontiguous\_iterator\_tag](iterator_tags "cpp/iterator/iterator tags")
(C++20) | empty class types used to indicate iterator categories (class) |
cpp std::istreambuf_iterator std::istreambuf\_iterator
=========================
| Defined in header `[<iterator>](../header/iterator "cpp/header/iterator")` | | |
| --- | --- | --- |
|
```
template< class CharT, class Traits = std::char_traits<CharT> >
class istreambuf_iterator :
public std::iterator< std::input_iterator_tag,
CharT, typename Traits::off_type,
/* unspecified, usually CharT* */, CharT >
```
| | (until C++17) |
|
```
template< class CharT, class Traits = std::char_traits<CharT> >
class istreambuf_iterator;
```
| | (since C++17) |
`std::istreambuf_iterator` is a single-pass input iterator that reads successive characters from the `[std::basic\_streambuf](../io/basic_streambuf "cpp/io/basic streambuf")` object for which it was constructed.
The default-constructed `std::istreambuf_iterator` is known as the *end-of-stream* iterator. When a valid `std::istreambuf_iterator` reaches the end of the underlying stream, it becomes equal to the end-of-stream iterator. Dereferencing or incrementing it further invokes undefined behavior.
| | |
| --- | --- |
| `std::istreambuf_iterator` has a trivial copy constructor, a constexpr default constructor, and a trivial destructor. | (since C++11) |
### Member types
| Member type | Definition |
| --- | --- |
| `iterator_category` | `[std::input\_iterator\_tag](http://en.cppreference.com/w/cpp/iterator/iterator_tags)` |
| `value_type` | `CharT` |
| `difference_type` | `Traits::off_type` |
| `pointer` | `/* unspecified, usually CharT* */` |
| `reference` | `CharT` |
| `char_type` | `CharT` |
| `traits_type` | `Traits` |
| `int_type` | `typename traits::int_type` |
| `streambuf_type` | `[std::basic\_streambuf](http://en.cppreference.com/w/cpp/io/basic_streambuf)<CharT, Traits>` |
| `istream_type` | `[std::basic\_istream](http://en.cppreference.com/w/cpp/io/basic_istream)<CharT, Traits>` |
| /\* proxy \*/ | Implementation-defined class type. The name `*proxy*` is for exposition only.A `*proxy*` object holds a `char_type` character and a `streambuf_type*` pointer.Deferencing a `*proxy*` object with `operator*` yields the stored character. |
| | |
| --- | --- |
| Member types `iterator_category`, `value_type`, `difference_type`, `pointer` and `reference` are required to be obtained by inheriting from `[std::iterator](http://en.cppreference.com/w/cpp/iterator/iterator)<[std::input\_iterator\_tag](http://en.cppreference.com/w/cpp/iterator/iterator_tags), CharT, Traits::off\_type, /\* unspecified, usually CharT\* \*/, CharT>`. | (until C++17) |
### Member functions
| | |
| --- | --- |
| [(constructor)](istreambuf_iterator/istreambuf_iterator "cpp/iterator/istreambuf iterator/istreambuf iterator") | constructs a new `istreambuf_iterator` (public member function) |
| (destructor)
(implicitly declared) | destructs an `istreambuf_iterator` (public member function) |
| [operator\*operator->](istreambuf_iterator/operator* "cpp/iterator/istreambuf iterator/operator*")
(since C++11)(until C++17) | obtains a copy of the current characteraccesses a member of the current character, if `CharT` has members (public member function) |
| [operator++operator++(int)](istreambuf_iterator/operator_arith "cpp/iterator/istreambuf iterator/operator arith") | advances the iterator (public member function) |
| [equal](istreambuf_iterator/equal "cpp/iterator/istreambuf iterator/equal") | tests if both `istreambuf_iterator`s are end-of-stream or if both are valid (public member function) |
### Non-member functions
| | |
| --- | --- |
| [operator==operator!=](istreambuf_iterator/operator_cmp "cpp/iterator/istreambuf iterator/operator cmp")
(removed in C++20) | compares two `istreambuf_iterator`s (function template) |
### Example
```
#include <string>
#include <sstream>
#include <iostream>
#include <iterator>
int main()
{
// typical use case: an input stream represented as a pair of iterators
std::istringstream in{"Hello, world"};
std::istreambuf_iterator<char> it{in}, end;
std::string ss{it, end};
std::cout << "ss has " << ss.size() << " bytes; "
"it holds \"" << ss << "\"\n";
// demonstration of the single-pass nature
std::istringstream s{"abc"};
std::istreambuf_iterator<char> i1{s}, i2{s};
std::cout << "i1 returns '" << *i1 << "'\n"
"i2 returns '" << *i2 << "'\n";
++i1;
std::cout << "after incrementing i1, but not i2:\n"
"i1 returns '" << *i1 << "'\n"
"i2 returns '" << *i2 << "'\n";
++i2;
std::cout << "after incrementing i2, but not i1:\n"
"i1 returns '" << *i1 << "'\n"
"i2 returns '" << *i2 << "'\n";
}
```
Output:
```
ss has 12 bytes; it holds "Hello, world"
i1 returns 'a'
i2 returns 'a'
after incrementing i1, but not i2:
i1 returns 'b'
i2 returns 'b'
after incrementing i2, but not i1:
i1 returns 'c'
i2 returns 'c'
```
### See also
| | |
| --- | --- |
| [ostreambuf\_iterator](ostreambuf_iterator "cpp/iterator/ostreambuf iterator") | output iterator that writes to `[std::basic\_streambuf](../io/basic_streambuf "cpp/io/basic streambuf")` (class template) |
| [istream\_iterator](istream_iterator "cpp/iterator/istream iterator") | input iterator that reads from `[std::basic\_istream](../io/basic_istream "cpp/io/basic istream")` (class template) |
cpp std::prev std::prev
=========
| Defined in header `[<iterator>](../header/iterator "cpp/header/iterator")` | | |
| --- | --- | --- |
|
```
template< class BidirIt >
BidirIt prev(
BidirIt it,
typename std::iterator_traits<BidirIt>::difference_type n = 1 );
```
| | (since C++11) (until C++17) |
|
```
template< class BidirIt >
constexpr BidirIt prev(
BidirIt it,
typename std::iterator_traits<BidirIt>::difference_type n = 1 );
```
| | (since C++17) |
Return the `*n*`th predecessor of iterator `it`.
### Parameters
| | | |
| --- | --- | --- |
| it | - | an iterator |
| n | - | number of elements `it` should be descended |
| Type requirements |
| -`BidirIt` must meet the requirements of [LegacyBidirectionalIterator](../named_req/bidirectionaliterator "cpp/named req/BidirectionalIterator"). |
### Return value
The `*n*`th predecessor of iterator `it`.
### Complexity
Linear.
However, if `BidirIt` additionally meets the requirements of [LegacyRandomAccessIterator](../named_req/randomaccessiterator "cpp/named req/RandomAccessIterator"), complexity is constant.
### Possible implementation
| |
| --- |
|
```
template<class BidirIt>
constexpr // since C++17
BidirIt prev(BidirIt it, typename std::iterator_traits<BidirIt>::difference_type n = 1)
{
std::advance(it, -n);
return it;
}
```
|
### Notes
Although the expression `--c.end()` often compiles, it is not guaranteed to do so: `c.end()` is an rvalue expression, and there is no iterator requirement that specifies that decrement of an rvalue is guaranteed to work. In particular, when iterators are implemented as pointers or its `operator--` is lvalue-ref-qualified, `--c.end()` does not compile, while `std::prev(c.end())` does.
### Example
```
#include <iostream>
#include <iterator>
#include <vector>
int main()
{
std::vector<int> v{ 3, 1, 4 };
auto it = v.end();
auto pv = std::prev(it, 2);
std::cout << *pv << '\n';
it = v.begin();
pv = std::prev(it, -2);
std::cout << *pv << '\n';
}
```
Output:
```
1
4
```
### See also
| | |
| --- | --- |
| [next](next "cpp/iterator/next")
(C++11) | increment an iterator (function template) |
| [advance](advance "cpp/iterator/advance") | advances an iterator by given distance (function template) |
| [distance](distance "cpp/iterator/distance") | returns the distance between two iterators (function template) |
| [ranges::prev](ranges/prev "cpp/iterator/ranges/prev")
(C++20) | decrement an iterator by a given distance or to a bound (niebloid) |
cpp std::next std::next
=========
| Defined in header `[<iterator>](../header/iterator "cpp/header/iterator")` | | |
| --- | --- | --- |
|
```
template< class InputIt >
InputIt next(
InputIt it,
typename std::iterator_traits<InputIt>::difference_type n = 1 );
```
| | (since C++11) (until C++17) |
|
```
template< class InputIt >
constexpr InputIt next(
InputIt it,
typename std::iterator_traits<InputIt>::difference_type n = 1 );
```
| | (since C++17) |
Return the `*n*`th successor of iterator `it`.
### Parameters
| | | |
| --- | --- | --- |
| it | - | an iterator |
| n | - | number of elements to advance |
| Type requirements |
| -`InputIt` must meet the requirements of [LegacyInputIterator](../named_req/inputiterator "cpp/named req/InputIterator"). |
### Return value
The `*n*`th successor of iterator `it`.
### Complexity
Linear.
However, if `InputIt` additionally meets the requirements of [LegacyRandomAccessIterator](../named_req/randomaccessiterator "cpp/named req/RandomAccessIterator"), complexity is constant.
### Possible implementation
| |
| --- |
|
```
template<class InputIt>
constexpr // since C++17
InputIt next(InputIt it,
typename std::iterator_traits<InputIt>::difference_type n = 1)
{
std::advance(it, n);
return it;
}
```
|
### Notes
Although the expression `++c.begin()` often compiles, it is not guaranteed to do so: `c.begin()` is an rvalue expression, and there is no [LegacyInputIterator](../named_req/inputiterator "cpp/named req/InputIterator") requirement that specifies that increment of an rvalue is guaranteed to work. In particular, when iterators are implemented as pointers or its `operator++` is lvalue-ref-qualified, `++c.begin()` does not compile, while `std::next(c.begin())` does.
### Example
```
#include <iostream>
#include <iterator>
#include <vector>
int main()
{
std::vector<int> v{ 4, 5, 6 };
auto it = v.begin();
auto nx = std::next(it, 2);
std::cout << *it << ' ' << *nx << '\n';
it = v.end();
nx = std::next(it, -2);
std::cout << ' ' << *nx << '\n';
}
```
Output:
```
4 6
5
```
### 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 2353](https://cplusplus.github.io/LWG/issue2353) | C++11 | `next` required [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator") | [LegacyInputIterator](../named_req/inputiterator "cpp/named req/InputIterator") allowed |
### See also
| | |
| --- | --- |
| [prev](prev "cpp/iterator/prev")
(C++11) | decrement an iterator (function template) |
| [advance](advance "cpp/iterator/advance") | advances an iterator by given distance (function template) |
| [distance](distance "cpp/iterator/distance") | returns the distance between two iterators (function template) |
| [ranges::next](ranges/next "cpp/iterator/ranges/next")
(C++20) | increment an iterator by a given distance or to a bound (niebloid) |
| programming_docs |
cpp std::make_move_iterator std::make\_move\_iterator
=========================
| Defined in header `[<iterator>](../header/iterator "cpp/header/iterator")` | | |
| --- | --- | --- |
|
```
template< class Iter >
std::move_iterator<Iter> make_move_iterator( Iter i );
```
| | (since C++11) (until C++17) |
|
```
template< class Iter >
constexpr std::move_iterator<Iter> make_move_iterator( Iter i );
```
| | (since C++17) |
`make_move_iterator` is a convenience function template that constructs a `[std::move\_iterator](move_iterator "cpp/iterator/move iterator")` for the given iterator `i` with the type deduced from the type of the argument.
### Parameters
| | | |
| --- | --- | --- |
| i | - | input iterator to be converted to move iterator |
### Return value
A `[std::move\_iterator](move_iterator "cpp/iterator/move iterator")` which can be used to move from the elements accessed through `i`.
### Possible implementation
| |
| --- |
|
```
template< class Iter >
constexpr std::move_iterator<Iter> make_move_iterator( Iter i )
{
return std::move_iterator<Iter>(std::move(i));
}
```
|
### Example
```
#include <iostream>
#include <iomanip>
#include <list>
#include <vector>
#include <string>
#include <iterator>
auto print = [](auto const rem, auto const& seq) {
for (std::cout << rem; auto const& str : seq)
std::cout << std::quoted(str) << ' ';
std::cout << '\n';
};
int main()
{
std::list<std::string> s{"one", "two", "three"};
std::vector<std::string> v1(s.begin(), s.end()); // copy
std::vector<std::string> v2(std::make_move_iterator(s.begin()),
std::make_move_iterator(s.end())); // move
print("v1 now holds: ", v1);
print("v2 now holds: ", v2);
print("original list now holds: ", s);
}
```
Possible output:
```
v1 now holds: "one" "two" "three"
v2 now holds: "one" "two" "three"
original list now holds: "" "" ""
```
### 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 2061](https://cplusplus.github.io/LWG/issue2061) | C++11 | `make_move_iterator` did not convert array arguments to pointers | made to convert |
### See also
| | |
| --- | --- |
| [move\_iterator](move_iterator "cpp/iterator/move iterator")
(C++11) | iterator adaptor which dereferences to an rvalue reference (class template) |
| [move](../utility/move "cpp/utility/move")
(C++11) | obtains an rvalue reference (function template) |
cpp std::make_reverse_iterator std::make\_reverse\_iterator
============================
| Defined in header `[<iterator>](../header/iterator "cpp/header/iterator")` | | |
| --- | --- | --- |
|
```
template <class Iter>
std::reverse_iterator<Iter> make_reverse_iterator( Iter i );
```
| | (since C++14) (until C++17) |
|
```
template <class Iter>
constexpr std::reverse_iterator<Iter> make_reverse_iterator( Iter i );
```
| | (since C++17) |
`make_reverse_iterator` is a convenience function template that constructs a `[std::reverse\_iterator](reverse_iterator "cpp/iterator/reverse iterator")` for the given iterator `i` (which must be a [LegacyBidirectionalIterator](../named_req/bidirectionaliterator "cpp/named req/BidirectionalIterator")) with the type deduced from the type of the argument.
### Parameters
| | | |
| --- | --- | --- |
| i | - | iterator to be converted to reverse iterator |
### Return value
A `[std::reverse\_iterator](reverse_iterator "cpp/iterator/reverse iterator")` constructed from `i`.
### Notes
| [Feature-test](../utility/feature_test "cpp/utility/feature test") macro |
| --- |
| [`__cpp_lib_make_reverse_iterator`](../feature_test#Library_features "cpp/feature test") |
### Possible implementation
| |
| --- |
|
```
template< class Iter >
constexpr std::reverse_iterator<Iter> make_reverse_iterator( Iter i )
{
return std::reverse_iterator<Iter>(i);
}
```
|
### Example
```
#include <iostream>
#include <iterator>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> v{ 1, 3, 10, 8, 22 };
std::sort(v.begin(), v.end());
std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, ", "));
std::cout << '\n';
std::copy(
std::make_reverse_iterator(v.end()),
std::make_reverse_iterator(v.begin()),
std::ostream_iterator<int>(std::cout, ", "));
}
```
Output:
```
1, 3, 8, 10, 22,
22, 10, 8, 3, 1,
```
### See also
| | |
| --- | --- |
| [reverse\_iterator](reverse_iterator "cpp/iterator/reverse iterator") | iterator adaptor for reverse-order traversal (class template) |
| [rbegincrbegin](rbegin "cpp/iterator/rbegin")
(C++14) | returns a reverse iterator to the beginning of a container or array (function template) |
| [rendcrend](rend "cpp/iterator/rend")
(C++14) | returns a reverse end iterator for a container or array (function template) |
cpp std::unreachable_sentinel_t, std::unreachable_sentinel std::unreachable\_sentinel\_t, std::unreachable\_sentinel
=========================================================
| Defined in header `[<iterator>](../header/iterator "cpp/header/iterator")` | | |
| --- | --- | --- |
|
```
struct unreachable_sentinel_t;
```
| (1) | (since C++20) |
|
```
inline constexpr unreachable_sentinel_t unreachable_sentinel{};
```
| (2) | (since C++20) |
1) `unreachable_sentinel_t` is an empty class type that can be used to denote the โupper boundโ of an unbounded interval.
2) `unreachable_sentinel` is a constant of type `unreachable_sentinel_t`. ### Non-member functions
| | |
| --- | --- |
| **operator==**
(C++20) | compares an `unreachable_sentinel_t` with a value of any [`weakly_incrementable`](weakly_incrementable "cpp/iterator/weakly incrementable") type (function template) |
operator==(std::unreachable\_sentinel\_t)
------------------------------------------
| | | |
| --- | --- | --- |
|
```
template<std::weakly_incrementable I>
friend constexpr bool operator==( unreachable_sentinel_t, const I& ) noexcept
{ return false; }
```
| | (since C++20) |
`unreachable_sentinel_t` can be compared with any [`weakly_incrementable`](weakly_incrementable "cpp/iterator/weakly incrementable") type and the result is always `false`.
This function template is not visible to ordinary [unqualified](../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../language/adl "cpp/language/adl") when `std::unreachable_sentinel_t` is an associated class of the arguments.
### Example
```
#include <cstddef>
#include <iterator>
#include <algorithm>
#include <iostream>
template<class CharT>
constexpr std::size_t strlen(const CharT *s)
{
return std::ranges::find(s, std::unreachable_sentinel, CharT{}) - s;
}
template<class CharT>
constexpr std::size_t pos(const CharT *haystack, const CharT *needle)
{
// search(begin, unreachable_sentinel) is usually more efficient than
// search(begin, end) due to one less comparison per cycle.
// But "needle" MUST BE in the "haystack", otherwise the call is UB,
// which is a compile-time error in constexpr context.
return std::ranges::search(
haystack, std::unreachable_sentinel,
needle, needle + strlen(needle)
).begin() - haystack;
}
int main()
{
static_assert(
strlen("The quick brown fox jumps over the lazy dog.") == 44
);
static_assert(
pos("const short int", "short") == 6
);
// static_assert(pos("long int", "float")); // compile-time error
}
```
### See also
| | |
| --- | --- |
| [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) |
cpp std::contiguous_iterator std::contiguous\_iterator
=========================
| Defined in header `[<iterator>](../header/iterator "cpp/header/iterator")` | | |
| --- | --- | --- |
|
```
template<class I>
concept contiguous_iterator =
std::random_access_iterator<I> &&
std::derived_from</*ITER_CONCEPT*/<I>, std::contiguous_iterator_tag> &&
std::is_lvalue_reference_v<std::iter_reference_t<I>> &&
std::same_as<
std::iter_value_t<I>, std::remove_cvref_t<std::iter_reference_t<I>>
> &&
requires(const I& i) {
{ std::to_address(i) } ->
std::same_as<std::add_pointer_t<std::iter_reference_t<I>>>;
};
```
| | (since C++20) |
The `contiguous_iterator` concept refines [`random_access_iterator`](random_access_iterator "cpp/iterator/random access iterator") by providing a guarantee the denoted elements are stored contiguously in the memory.
### Iterator concept determination
Definition of this concept is specified via an exposition-only alias template `/*ITER_CONCEPT*/`.
In order to determine `/*ITER_CONCEPT*/<I>`, let `ITER_TRAITS<I>` denote `I` if the specialization `[std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<I>` is generated from the primary template, or `[std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<I>` otherwise:
* If `ITER_TRAITS<I>::iterator_concept` is valid and names a type, `/*ITER_CONCEPT*/<I>` denotes the type.
* Otherwise, if `ITER_TRAITS<I>::iterator_category` is valid and names a type, `/*ITER_CONCEPT*/<I>` denotes the type.
* Otherwise, if `[std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<I>` is generated from the primary template, `/*ITER_CONCEPT*/<I>` denotes `[std::random\_access\_iterator\_tag](iterator_tags "cpp/iterator/iterator tags")`.
* Otherwise, `/*ITER_CONCEPT*/<I>` does not denote a type and results in a substitution failure.
### Semantic requirements
Let `a` and `b` be dereferenceable iterators and `c` be a non-dereferenceable iterator of type `I` such that `b` is reachable from `a` and `c` is reachable from `b`. The type `I` models `contiguous_iterator` only if all the concepts it subsumes are modeled and:
* `[std::to\_address](http://en.cppreference.com/w/cpp/memory/to_address)(a) == [std::addressof](http://en.cppreference.com/w/cpp/memory/addressof)(\*a)`,
* `[std::to\_address](http://en.cppreference.com/w/cpp/memory/to_address)(b) == [std::to\_address](http://en.cppreference.com/w/cpp/memory/to_address)(a) + [std::iter\_difference\_t](http://en.cppreference.com/w/cpp/iterator/iter_t)<I>(b - a)`, and
* `[std::to\_address](http://en.cppreference.com/w/cpp/memory/to_address)(c) == [std::to\_address](http://en.cppreference.com/w/cpp/memory/to_address)(a) + [std::iter\_difference\_t](http://en.cppreference.com/w/cpp/iterator/iter_t)<I>(c - a)`.
### Equality preservation
An expression is *equality preserving* if it results in equal outputs given equal inputs.
* The inputs to an expression consist of its operands.
* The outputs of an expression consist of its result and all operands modified by the expression (if any).
In specification of standard concepts, operands are defined as the largest subexpressions that include only:
* an [id-expression](../language/expressions#Primary_expressions "cpp/language/expressions"), and
* invocations of [`std::move`](../utility/move "cpp/utility/move"), `[std::forward](../utility/forward "cpp/utility/forward")`, and `[std::declval](../utility/declval "cpp/utility/declval")`.
The cv-qualification and value category of each operand is determined by assuming that each template type parameter denotes a cv-unqualified complete non-array object type.
Every expression required to be equality preserving is further required to be *stable*: two evaluations of such an expression with the same input objects must have equal outputs absent any explicit intervening modification of those input objects.
Unless noted otherwise, every expression used in a *requires-expression* is required to be equality preserving and stable, and the evaluation of the expression may modify only its non-constant operands. Operands that are constant must not be modified.
### Implicit expression variations
A *requires-expression* that uses an expression that is non-modifying for some constant lvalue operand also implicitly requires additional variations of that expression that accept a non-constant lvalue or (possibly constant) rvalue for the given operand unless such an expression variation is explicitly required with differing semantics. These *implicit expression variations* must meet the same semantic requirements of the declared expression. The extent to which an implementation validates the syntax of the variations is unspecified.
### Notes
`contiguous_iterator` is modeled by every pointer type to complete object type.
Iterator types in the standard library that are required to satisfy the [LegacyContiguousIterator](../named_req/contiguousiterator "cpp/named req/ContiguousIterator") requirements in C++17 are also required to model `contiguous_iterator` in C++20.
### See also
| | |
| --- | --- |
| [random\_access\_iterator](random_access_iterator "cpp/iterator/random access iterator")
(C++20) | specifies that a [`bidirectional_iterator`](bidirectional_iterator "cpp/iterator/bidirectional iterator") is a random-access iterator, supporting advancement in constant time and subscripting (concept) |
cpp std::rend, std::crend std::rend, std::crend
=====================
| Defined in header `[<array>](../header/array "cpp/header/array")` | | |
| --- | --- | --- |
| Defined in header `[<deque>](../header/deque "cpp/header/deque")` | | |
| Defined in header `[<forward\_list>](../header/forward_list "cpp/header/forward list")` | | |
| Defined in header `[<iterator>](../header/iterator "cpp/header/iterator")` | | |
| Defined in header `[<list>](../header/list "cpp/header/list")` | | |
| Defined in header `[<map>](../header/map "cpp/header/map")` | | |
| Defined in header `[<regex>](../header/regex "cpp/header/regex")` | | |
| Defined in header `[<set>](../header/set "cpp/header/set")` | | |
| Defined in header `[<span>](../header/span "cpp/header/span")` | | (since C++20) |
| Defined in header `[<string>](../header/string "cpp/header/string")` | | |
| Defined in header `[<string\_view>](../header/string_view "cpp/header/string view")` | | (since C++17) |
| Defined in header `[<unordered\_map>](../header/unordered_map "cpp/header/unordered map")` | | |
| Defined in header `[<unordered\_set>](../header/unordered_set "cpp/header/unordered set")` | | |
| Defined in header `[<vector>](../header/vector "cpp/header/vector")` | | |
| | (1) | |
|
```
template< class C >
auto rend( C& c ) -> decltype(c.rend());
```
| (since C++14) (until C++17) |
|
```
template< class C >
constexpr auto rend( C& c ) -> decltype(c.rend());
```
| (since C++17) |
| | (1) | |
|
```
template< class C >
auto rend( const C& c ) -> decltype(c.rend());
```
| (since C++14) (until C++17) |
|
```
template< class C >
constexpr auto rend( const C& c ) -> decltype(c.rend());
```
| (since C++17) |
| | (2) | |
|
```
template< class T, std::size_t N >
std::reverse_iterator<T*> rend( T (&array)[N] );
```
| (since C++14) (until C++17) |
|
```
template< class T, std::size_t N >
constexpr std::reverse_iterator<T*> rend( T (&array)[N] );
```
| (since C++17) |
| | (3) | |
|
```
template< class T >
std::reverse_iterator<const T*> rend( std::initializer_list<T> il );
```
| (since C++14) (until C++17) |
|
```
template< class T >
constexpr std::reverse_iterator<const T*> rend( std::initializer_list<T> il );
```
| (since C++17) |
| | (4) | |
|
```
template< class C >
auto crend( const C& c ) -> decltype(std::rend(c));
```
| (since C++14) (until C++17) |
|
```
template< class C >
constexpr auto crend( const C& c ) -> decltype(std::rend(c));
```
| (since C++17) |
Returns an iterator to the reverse-end of the given range.
1) Returns an iterator to the reverse-end of the possibly const-qualified container or view `c`.
2) Returns `[std::reverse\_iterator](http://en.cppreference.com/w/cpp/iterator/reverse_iterator)<T\*>` to the reverse-end of the array `array`.
3) Returns `[std::reverse\_iterator](http://en.cppreference.com/w/cpp/iterator/reverse_iterator)<const T\*>` to the reverse-end of the `[std::initializer\_list](../utility/initializer_list "cpp/utility/initializer list")` `il`.
4) Returns an iterator to the reverse-end of the const-qualified container or view `c`. ![range-rbegin-rend.svg]()
### Parameters
| | | |
| --- | --- | --- |
| c | - | a container or view with a `rend` member function |
| array | - | an array of arbitrary type |
| il | - | an `initializer_list` |
### Return value
1) `c.rend()`
2) `[std::reverse\_iterator](http://en.cppreference.com/w/cpp/iterator/reverse_iterator)<T\*>(array)`
3) `[std::reverse\_iterator](http://en.cppreference.com/w/cpp/iterator/reverse_iterator)<const T\*>(il.begin())`
4) `c.rend()`
### Exceptions
May throw implementation-defined exceptions.
### Overloads
Custom overloads of `rend` may be provided for classes and enumerations that do not expose a suitable `rend()` member function, yet can be iterated.
| | |
| --- | --- |
| Overloads of `rend` found by [argument-dependent lookup](../language/adl "cpp/language/adl") can be used to customize the behavior of `std::[ranges::rend](http://en.cppreference.com/w/cpp/ranges/rend)` and `std::[ranges::crend](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/crend)`. | (since C++20) |
### Notes
The overload for `[std::initializer\_list](../utility/initializer_list "cpp/utility/initializer list")` is necessary because it does not have a member function `rend`.
### Example
```
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
int main()
{
int a[] = {4, 6, -3, 9, 10};
std::cout << "C-style array `a` backwards: ";
std::copy(std::rbegin(a), std::rend(a), std::ostream_iterator<int>(std::cout, " "));
auto il = { 3, 1, 4 };
std::cout << "\nstd::initializer_list `il` backwards: ";
std::copy(std::rbegin(il), std::rend(il), std::ostream_iterator<int>(std::cout, " "));
std::cout << "\nstd::vector `v` backwards: ";
std::vector<int> v = {4, 6, -3, 9, 10};
std::copy(std::rbegin(v), std::rend(v), std::ostream_iterator<int>(std::cout, " "));
}
```
Output:
```
C-style array `a` backwards: 10 9 -3 6 4
std::initializer_list `il` backwards: 4 1 3
std::vector `v` backwards: 10 9 -3 6 4
```
### See also
| | |
| --- | --- |
| [endcend](end "cpp/iterator/end")
(C++11)(C++14) | returns an iterator to the end of a container or array (function template) |
| [rbegincrbegin](rbegin "cpp/iterator/rbegin")
(C++14) | returns a reverse iterator to the beginning of a container or array (function template) |
| [begincbegin](begin "cpp/iterator/begin")
(C++11)(C++14) | returns an iterator to the beginning of a container or array (function template) |
| [ranges::rend](../ranges/rend "cpp/ranges/rend")
(C++20) | returns a reverse end iterator to a range (customization point object) |
| [ranges::crend](../ranges/crend "cpp/ranges/crend")
(C++20) | returns a reverse end iterator to a read-only range (customization point object) |
cpp std::iter_value_t, std::iter_reference_t, std::iter_const_reference_t, std::iter_difference_t, std::iter_rvalue_reference_t, std::iter_common_reference_t std::iter\_value\_t, std::iter\_reference\_t, std::iter\_const\_reference\_t, std::iter\_difference\_t, std::iter\_rvalue\_reference\_t, std::iter\_common\_reference\_t
========================================================================================================================================================================
| Defined in header `[<iterator>](../header/iterator "cpp/header/iterator")` | | |
| --- | --- | --- |
|
```
template< class T >
concept /*dereferenceable*/ = /* see below */; // exposition only
```
| | |
|
```
template< class T >
using iter_value_t = /* see below */;
```
| (1) | (since C++20) |
|
```
template< /*dereferenceable*/ T >
using iter_reference_t = decltype(*std::declval<T&>());
```
| (2) | (since C++20) |
|
```
template< std::indirectly_readable T >
using iter_const_reference_t = std::common_reference_t<const std::iter_value_t<T>&&,
std::iter_reference_t<T>>;
```
| (3) | (since C++23) |
|
```
template< class T >
using iter_difference_t = /* see below */;
```
| (4) | (since C++20) |
|
```
template< /*dereferenceable*/ T>
requires /* see below */
using iter_rvalue_reference_t = decltype(ranges::iter_move(std::declval<T&>()));
```
| (5) | (since C++20) |
|
```
template< std::indirectly_readable T >
using iter_common_reference_t = std::common_reference_t<std::iter_reference_t<T>,
std::iter_value_t<T>&>;
```
| (6) | (since C++20) |
Compute the associated types of an iterator. The exposition-only concept `*dereferenceable*` is satisfied if and only if the expression `*std::declval<T&>()` is valid and has a referenceable type (in particular, not `void`).
1) Computes the *value type* of `T`. If `[std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<T>>` is not specialized, then `std::iter_value_t<T>` is `[std::indirectly\_readable\_traits](http://en.cppreference.com/w/cpp/iterator/indirectly_readable_traits)<[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<T>>::value\_type`. Otherwise, it is `[std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<T>>::value\_type`.
2) Computes the *reference type* of `T`.
3) Computes the *const reference type* of `T`.
4) Computes the *difference type* of `T`. If `[std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<T>>` is not specialized, then `std::iter_difference_t<T>` is `[std::incrementable\_traits](http://en.cppreference.com/w/cpp/iterator/incrementable_traits)<[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<T>>::difference\_type`. Otherwise, it is `[std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<T>>::difference\_type`.
5) Computes the *rvalue reference type* of `T`. The "see below" portion of the constraint on this alias template is satisfied if and only if the expression `[ranges::iter\_move](http://en.cppreference.com/w/cpp/iterator/ranges/iter_move)([std::declval](http://en.cppreference.com/w/cpp/utility/declval)<T&>())` is valid and has a referenceable type (in particular, not `void`).
6) Computes the *common reference type* of `T`. This is the common reference type between its reference type and an lvalue reference to its value type. ### See also
| | |
| --- | --- |
| [indirectly\_readable](indirectly_readable "cpp/iterator/indirectly readable")
(C++20) | specifies that a type is indirectly readable by applying operator `*` (concept) |
| [weakly\_incrementable](weakly_incrementable "cpp/iterator/weakly incrementable")
(C++20) | specifies that a [`semiregular`](../concepts/semiregular "cpp/concepts/semiregular") type can be incremented with pre- and post-increment operators (concept) |
| [indirectly\_readable\_traits](indirectly_readable_traits "cpp/iterator/indirectly readable traits")
(C++20) | computes the value type of an [`indirectly_readable`](indirectly_readable "cpp/iterator/indirectly readable") type (class template) |
| [incrementable\_traits](incrementable_traits "cpp/iterator/incrementable traits")
(C++20) | computes the difference type of a [`weakly_incrementable`](weakly_incrementable "cpp/iterator/weakly incrementable") type (class template) |
| [iterator\_traits](iterator_traits "cpp/iterator/iterator traits") | provides uniform interface to the properties of an iterator (class template) |
| programming_docs |
cpp std::input_iterator_tag, std::output_iterator_tag, std::forward_iterator_tag, std::bidirectional_iterator_tag, std::random_access_iterator_tag, std::contiguous_iterator_tag std::input\_iterator\_tag, std::output\_iterator\_tag, std::forward\_iterator\_tag, std::bidirectional\_iterator\_tag, std::random\_access\_iterator\_tag, std::contiguous\_iterator\_tag
=========================================================================================================================================================================================
| Defined in header `[<iterator>](../header/iterator "cpp/header/iterator")` | | |
| --- | --- | --- |
|
```
struct input_iterator_tag { };
```
| (1) | |
|
```
struct output_iterator_tag { };
```
| (2) | |
|
```
struct forward_iterator_tag : public input_iterator_tag { };
```
| (3) | |
|
```
struct bidirectional_iterator_tag : public forward_iterator_tag { };
```
| (4) | |
|
```
struct random_access_iterator_tag : public bidirectional_iterator_tag { };
```
| (5) | |
|
```
struct contiguous_iterator_tag : public random_access_iterator_tag { };
```
| (6) | (since C++20) |
Defines the category of an iterator. Each tag is an empty type.
### Iterator category
For every [LegacyIterator](../named_req/iterator "cpp/named req/Iterator") type `It`, a `typedef` `[std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<It>::iterator\_category` must be defined to be an alias to one of these tag types, to indicate the most specific category that `It` is in.
1. `input_iterator_tag` corresponds to [LegacyInputIterator](../named_req/inputiterator "cpp/named req/InputIterator").
2. `output_iterator_tag` corresponds to [LegacyOutputIterator](../named_req/outputiterator "cpp/named req/OutputIterator").
3. `forward_iterator_tag` corresponds to [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator").
4. `bidirectional_iterator_tag` corresponds to [LegacyBidirectionalIterator](../named_req/bidirectionaliterator "cpp/named req/BidirectionalIterator").
5. `random_access_iterator_tag` corresponds to [LegacyRandomAccessIterator](../named_req/randomaccessiterator "cpp/named req/RandomAccessIterator").
Iterator category tags carry information that can be used to select the most efficient algorithms for the specific requirement set that is implied by the category.
| | |
| --- | --- |
| Iterator concept For every [`input_iterator`](input_iterator "cpp/iterator/input iterator") type `It`, either `It::iterator_concept` (if `[std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<It>` is generated from primary template) or `[std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<It>::iterator\_concept` (if `[std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<It>` is specialized) may be declared as an alias to one of these tags, to indicate the strongest iterator concept that `It` intends to model.1. `input_iterator_tag` corresponds to [`input_iterator`](input_iterator "cpp/iterator/input iterator").
2. `forward_iterator_tag` corresponds to [`forward_iterator`](forward_iterator "cpp/iterator/forward iterator").
3. `bidirectional_iterator_tag` corresponds to [`bidirectional_iterator`](bidirectional_iterator "cpp/iterator/bidirectional iterator").
4. `random_access_iterator_tag` corresponds to [`random_access_iterator`](random_access_iterator "cpp/iterator/random access iterator").
5. `contiguous_iterator_tag` corresponds to [`contiguous_iterator`](contiguous_iterator "cpp/iterator/contiguous iterator").
If `iterator_concept` is not provided, `iterator_category` is used as a fallback. If `iterator_category` is not provided either (i.e. `It` is not a [LegacyIterator](../named_req/iterator "cpp/named req/Iterator")), and `[std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<It>` is not specialized, `random_access_iterator_tag` is assumed.
In any case, each concept is not satisfied if the required operations are not supported, regardless of the tag. | (since C++20) |
### Notes
There is no separate tag for [LegacyContiguousIterator](../named_req/contiguousiterator "cpp/named req/ContiguousIterator"). That is, it is not possible to tell a [LegacyContiguousIterator](../named_req/contiguousiterator "cpp/named req/ContiguousIterator") based on its `iterator_category`. To define specialized algorithm for contiguous iterators, use the [`contiguous_iterator`](contiguous_iterator "cpp/iterator/contiguous iterator") concept. (since C++20).
There are no correspondences between `output_iterator_tag` and the [`output_iterator`](output_iterator "cpp/iterator/output iterator") concept. Setting `iterator_concept` to `output_iterator_tag` only indicates that the type does not model [`input_iterator`](input_iterator "cpp/iterator/input iterator").
### Example
Common technique for algorithm selection based on iterator category tags is to use a dispatcher function (the alternative is `[std::enable\_if](../types/enable_if "cpp/types/enable if")`). The iterator tag classes are also used in the corresponding concepts definitions to denote the requirements, which can't be expressed in terms of usage patterns alone. (since C++20).
```
#include <iostream>
#include <vector>
#include <list>
#include <iterator>
// Using concepts (tag checking is part of the concepts themselves)
template<std::bidirectional_iterator BDIter>
void alg(BDIter, BDIter)
{
std::cout << "1. alg() \t called for bidirectional iterator\n";
}
template<std::random_access_iterator RAIter>
void alg(RAIter, RAIter)
{
std::cout << "2. alg() \t called for random-access iterator\n";
}
// Legacy, using tag dispatch
namespace legacy {
// quite often implementation details are hidden in a dedicated namespace
namespace implementation_details {
template<class BDIter>
void alg(BDIter, BDIter, std::bidirectional_iterator_tag)
{
std::cout << "3. legacy::alg() called for bidirectional iterator\n";
}
template<class RAIter>
void alg(RAIter, RAIter, std::random_access_iterator_tag)
{
std::cout << "4. legacy::alg() called for random-access iterator\n";
}
} // namespace implementation_details
template<class Iter>
void alg(Iter first, Iter last)
{
implementation_details::alg(first, last,
typename std::iterator_traits<Iter>::iterator_category());
}
} // namespace legacy
int main()
{
std::list<int> l;
alg(l.begin(), l.end()); // 1.
legacy::alg(l.begin(), l.end()); // 3.
std::vector<int> v;
alg(v.begin(), v.end()); // 2.
legacy::alg(v.begin(), v.end()); // 4.
// std::istreambuf_iterator<char> i1(std::cin), i2;
// alg(i1, i2); // compile error: no matching function for call
// legacy::alg(i1, i2); // compile error: no matching function for call
}
```
Output:
```
1. alg() called for bidirectional iterator
3. legacy::alg() called for bidirectional iterator
2. alg() called for random-access iterator
4. legacy::alg() called for random-access iterator
```
### See also
| | |
| --- | --- |
| [iterator](iterator "cpp/iterator/iterator")
(deprecated in C++17) | base class to ease the definition of required types for simple iterators (class template) |
| [iterator\_traits](iterator_traits "cpp/iterator/iterator traits") | provides uniform interface to the properties of an iterator (class template) |
cpp std::indirectly_readable std::indirectly\_readable
=========================
| Defined in header `[<iterator>](../header/iterator "cpp/header/iterator")` | | |
| --- | --- | --- |
|
```
template< class In >
concept __IndirectlyReadableImpl = // exposition only
requires(const In in) {
typename std::iter_value_t<In>;
typename std::iter_reference_t<In>;
typename std::iter_rvalue_reference_t<In>;
{ *in } -> std::same_as<std::iter_reference_t<In>>;
{ ranges::iter_move(in) } -> std::same_as<std::iter_rvalue_reference_t<In>>;
} &&
std::common_reference_with<
std::iter_reference_t<In>&&, std::iter_value_t<In>&
> &&
std::common_reference_with<
std::iter_reference_t<In>&&, std::iter_rvalue_reference_t<In>&&
> &&
std::common_reference_with<
std::iter_rvalue_reference_t<In>&&, const std::iter_value_t<In>&
>;
```
| | (since C++20) |
|
```
template< class In >
concept indirectly_readable =
__IndirectlyReadableImpl<std::remove_cvref_t<In>>;
```
| | (since C++20) |
The concept `indirectly_readable` is modeled by types that are readable by applying `operator*`, such as pointers, smart pointers, and input iterators.
### Semantic requirements
Given a value `i` of type `I`, `I` models `indirectly_readable` only if all concepts it subsumes are modeled and the expression `*i` is equality preserving.
### Equality preservation
An expression is *equality preserving* if it results in equal outputs given equal inputs.
* The inputs to an expression consist of its operands.
* The outputs of an expression consist of its result and all operands modified by the expression (if any).
In specification of standard concepts, operands are defined as the largest subexpressions that include only:
* an [id-expression](../language/expressions#Primary_expressions "cpp/language/expressions"), and
* invocations of [`std::move`](../utility/move "cpp/utility/move"), `[std::forward](../utility/forward "cpp/utility/forward")`, and `[std::declval](../utility/declval "cpp/utility/declval")`.
The cv-qualification and value category of each operand is determined by assuming that each template type parameter denotes a cv-unqualified complete non-array object type.
Every expression required to be equality preserving is further required to be *stable*: two evaluations of such an expression with the same input objects must have equal outputs absent any explicit intervening modification of those input objects.
Unless noted otherwise, every expression used in a *requires-expression* is required to be equality preserving and stable, and the evaluation of the expression may modify only its non-constant operands. Operands that are constant must not be modified.
cpp std::back_insert_iterator std::back\_insert\_iterator
===========================
| Defined in header `[<iterator>](../header/iterator "cpp/header/iterator")` | | |
| --- | --- | --- |
|
```
template< class Container >
class back_insert_iterator : public std::iterator< std::output_iterator_tag,
void, void, void, void >
```
| | (until C++17) |
|
```
template< class Container >
class back_insert_iterator;
```
| | (since C++17) |
`std::back_insert_iterator` is a [LegacyOutputIterator](../named_req/outputiterator "cpp/named req/OutputIterator") that appends elements to a container for which it was constructed. The container's `push_back()` member function is called whenever the iterator (whether dereferenced or not) is assigned to. Incrementing the `std::back_insert_iterator` is a no-op.
### Member types
| Member type | Definition |
| --- | --- |
| `iterator_category` | `[std::output\_iterator\_tag](http://en.cppreference.com/w/cpp/iterator/iterator_tags)` |
| `value_type` | `void` |
| `difference_type` |
| | |
| --- | --- |
| `void`. | (until C++20) |
| `[std::ptrdiff\_t](http://en.cppreference.com/w/cpp/types/ptrdiff_t)`. | (since C++20) |
|
| `pointer` | `void` |
| `reference` | `void` |
| `container_type` | `Container` |
| | |
| --- | --- |
| Member types `iterator_category`, `value_type`, `difference_type`, `pointer` and `reference` are required to be obtained by inheriting from `[std::iterator](http://en.cppreference.com/w/cpp/iterator/iterator)<[std::output\_iterator\_tag](http://en.cppreference.com/w/cpp/iterator/iterator_tags), void, void, void, void>`. | (until C++17) |
### Member functions
| | |
| --- | --- |
| [(constructor)](back_insert_iterator/back_insert_iterator "cpp/iterator/back insert iterator/back insert iterator") | constructs a new `back_insert_iterator` (public member function) |
| [operator=](back_insert_iterator/operator= "cpp/iterator/back insert iterator/operator=") | inserts an object into the associated container (public member function) |
| [operator\*](back_insert_iterator/operator* "cpp/iterator/back insert iterator/operator*") | no-op (public member function) |
| [operator++operator++(int)](back_insert_iterator/operator_plus__plus_ "cpp/iterator/back insert iterator/operator++") | no-op (public member function) |
### Member objects
| Member name | Definition |
| --- | --- |
| `container` (protected) | a pointer of type `Container*` |
### Example
```
#include <iostream>
#include <iterator>
#include <algorithm>
#include <vector>
int main()
{
std::vector<int> v;
std::generate_n(
std::back_insert_iterator<std::vector<int>>(v), // C++17: std::back_insert_iterator(v)
10, [n=0]() mutable { return ++n; } // or use std::back_inserter helper
);
for (int n : v)
std::cout << n << ' ';
std::cout << '\n';
}
```
Output:
```
1 2 3 4 5 6 7 8 9 10
```
### See also
| | |
| --- | --- |
| [back\_inserter](back_inserter "cpp/iterator/back inserter") | creates a `std::back_insert_iterator` of type inferred from the argument (function template) |
| [front\_insert\_iterator](front_insert_iterator "cpp/iterator/front insert iterator") | iterator adaptor for insertion at the front of a container (class template) |
| [insert\_iterator](insert_iterator "cpp/iterator/insert iterator") | iterator adaptor for insertion into a container (class template) |
cpp std::sortable std::sortable
=============
| Defined in header `[<iterator>](../header/iterator "cpp/header/iterator")` | | |
| --- | --- | --- |
|
```
template< class I, class Comp = ranges::less, class Proj = std::identity >
concept sortable =
std::permutable<I> &&
std::indirect_strict_weak_order<Comp, std::projected<I, Proj>>;
```
| | (since C++20) |
The `sortable` concept specifies the requirements for algorithms that permute a range into an ordered range according to `Comp`.
### Semantic requirements
`std::sortable<I, Comp, Proj>` is modeled only if all concepts it subsumes are modeled.
### See also
| | |
| --- | --- |
| [ranges::sort](../algorithm/ranges/sort "cpp/algorithm/ranges/sort")
(C++20) | sorts a range into ascending order (niebloid) |
| [ranges::stable\_sort](../algorithm/ranges/stable_sort "cpp/algorithm/ranges/stable sort")
(C++20) | sorts a range of elements while preserving order between equal elements (niebloid) |
| [ranges::partial\_sort](../algorithm/ranges/partial_sort "cpp/algorithm/ranges/partial sort")
(C++20) | sorts the first N elements of a range (niebloid) |
| [ranges::nth\_element](../algorithm/ranges/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::inplace\_merge](../algorithm/ranges/inplace_merge "cpp/algorithm/ranges/inplace merge")
(C++20) | merges two ordered ranges in-place (niebloid) |
| [ranges::push\_heap](../algorithm/ranges/push_heap "cpp/algorithm/ranges/push heap")
(C++20) | adds an element to a max heap (niebloid) |
| [ranges::pop\_heap](../algorithm/ranges/pop_heap "cpp/algorithm/ranges/pop heap")
(C++20) | removes the largest element from a max heap (niebloid) |
| [ranges::make\_heap](../algorithm/ranges/make_heap "cpp/algorithm/ranges/make heap")
(C++20) | creates a max heap out of a range of elements (niebloid) |
| [ranges::sort\_heap](../algorithm/ranges/sort_heap "cpp/algorithm/ranges/sort heap")
(C++20) | turns a max heap into a range of elements sorted in ascending order (niebloid) |
| [ranges::next\_permutation](../algorithm/ranges/next_permutation "cpp/algorithm/ranges/next permutation")
(C++20) | generates the next greater lexicographic permutation of a range of elements (niebloid) |
| [ranges::prev\_permutation](../algorithm/ranges/prev_permutation "cpp/algorithm/ranges/prev permutation")
(C++20) | generates the next smaller lexicographic permutation of a range of elements (niebloid) |
cpp std::indirectly_movable_storable std::indirectly\_movable\_storable
==================================
| Defined in header `[<iterator>](../header/iterator "cpp/header/iterator")` | | |
| --- | --- | --- |
|
```
template<class In, class Out>
concept indirectly_movable_storable =
std::indirectly_movable<In, Out> &&
std::indirectly_writable<Out, std::iter_value_t<In>> &&
std::movable<std::iter_value_t<In>> &&
std::constructible_from<std::iter_value_t<In>, std::iter_rvalue_reference_t<In>> &&
std::assignable_from<std::iter_value_t<In>&, std::iter_rvalue_reference_t<In>>;
```
| | (since C++20) |
The `indirectly_movable_storable` concept specifies the relationship between an [`indirectly_readable`](indirectly_readable "cpp/iterator/indirectly readable") type and an [`indirectly_writable`](indirectly_writable "cpp/iterator/indirectly writable") type. In addition to [`indirectly_movable`](indirectly_movable "cpp/iterator/indirectly movable"), this concept specifies that the move from the `indirectly_readable` type can be performed via an intermediate object.
### Semantic requirements
`In` and `Out` model `std::indirectly_movable_storable<In, Out>` only if given a dereferenceable value `i` of type `In`:
* After the definition `[std::iter\_value\_t](http://en.cppreference.com/w/cpp/iterator/iter_t)<In> obj([ranges::iter\_move](http://en.cppreference.com/w/cpp/iterator/ranges/iter_move)(i));`, `obj` is equal to the value previously denoted by `*i`, and
* if `[std::iter\_rvalue\_reference\_t](http://en.cppreference.com/w/cpp/iterator/iter_t)<In>` is an rvalue reference type, `*i` is placed in a valid but unspecified state after the initialization of `obj`.
### Equality preservation
An expression is *equality preserving* if it results in equal outputs given equal inputs.
* The inputs to an expression consist of its operands.
* The outputs of an expression consist of its result and all operands modified by the expression (if any).
In specification of standard concepts, operands are defined as the largest subexpressions that include only:
* an [id-expression](../language/expressions#Primary_expressions "cpp/language/expressions"), and
* invocations of [`std::move`](../utility/move "cpp/utility/move"), `[std::forward](../utility/forward "cpp/utility/forward")`, and `[std::declval](../utility/declval "cpp/utility/declval")`.
The cv-qualification and value category of each operand is determined by assuming that each template type parameter denotes a cv-unqualified complete non-array object type.
Every expression required to be equality preserving is further required to be *stable*: two evaluations of such an expression with the same input objects must have equal outputs absent any explicit intervening modification of those input objects.
Unless noted otherwise, every expression used in a *requires-expression* is required to be equality preserving and stable, and the evaluation of the expression may modify only its non-constant operands. Operands that are constant must not be modified.
### See also
| | |
| --- | --- |
| [indirectly\_movable](indirectly_movable "cpp/iterator/indirectly movable")
(C++20) | specifies that values may be moved from an [`indirectly_readable`](indirectly_readable "cpp/iterator/indirectly readable") type to an [`indirectly_writable`](indirectly_writable "cpp/iterator/indirectly writable") type (concept) |
| [indirectly\_copyable\_storable](indirectly_copyable_storable "cpp/iterator/indirectly copyable storable")
(C++20) | specifies that values may be copied from an [`indirectly_readable`](indirectly_readable "cpp/iterator/indirectly readable") type to an [`indirectly_writable`](indirectly_writable "cpp/iterator/indirectly writable") type and that the copy may be performed via an intermediate object (concept) |
| programming_docs |
cpp std::sized_sentinel_for, std::disable_sized_sentinel_for std::sized\_sentinel\_for, std::disable\_sized\_sentinel\_for
=============================================================
| Defined in header `[<iterator>](../header/iterator "cpp/header/iterator")` | | |
| --- | --- | --- |
|
```
template<class S, class I>
concept sized_sentinel_for =
std::sentinel_for<S, I> &&
!std::disable_sized_sentinel_for<std::remove_cv_t<S>, std::remove_cv_t<I>> &&
requires(const I& i, const S& s) {
{ s - i } -> std::same_as<std::iter_difference_t<I>>;
{ i - s } -> std::same_as<std::iter_difference_t<I>>;
};
```
| (1) | (since C++20) |
|
```
template<class S, class I>
inline constexpr bool disable_sized_sentinel_for = false;
```
| (2) | (since C++20) |
1) The `sized_sentinel_for` concept specifies that an object of the iterator type `I` and an object of the sentinel type `S` can be subtracted to compute the distance between them in constant time.
2) The `disable_sized_sentinel_for` variable template can be used to prevent iterators and sentinels that can be subtracted but do not actually model `sized_sentinel_for` from satisfying the concept.
The variable template is allowed to be specialized for cv-unqualified non-array object type `S` and `I`, as long as at least one of which is a program-defined type. Such specializations shall be usable in [constant expressions](../language/constant_expression "cpp/language/constant expression") and have type `const bool`. ### Semantic requirements
Let `i` be an iterator of type `I`, and `s` a sentinel of type `S` such that `[i, s)` denotes a range. Let `n` be the smallest number of applications of `++i` necessary to make `bool(i == s)` be `true`. `I` and `S` model `sized_sentinel_for<S, I>` only if:
* If `n` is representable by `[std::iter\_difference\_t](http://en.cppreference.com/w/cpp/iterator/iter_t)<I>`, then `s - i` is well-defined and equals `n`; and
* If `-n` is representable by `[std::iter\_difference\_t](http://en.cppreference.com/w/cpp/iterator/iter_t)<I>`, then `i - s` is well-defined and equals `-n`.
* Subtraction between `i` and `s` has constant time complexity.
### Equality preservation
An expression is *equality preserving* if it results in equal outputs given equal inputs.
* The inputs to an expression consist of its operands.
* The outputs of an expression consist of its result and all operands modified by the expression (if any).
In specification of standard concepts, operands are defined as the largest subexpressions that include only:
* an [id-expression](../language/expressions#Primary_expressions "cpp/language/expressions"), and
* invocations of [`std::move`](../utility/move "cpp/utility/move"), `[std::forward](../utility/forward "cpp/utility/forward")`, and `[std::declval](../utility/declval "cpp/utility/declval")`.
The cv-qualification and value category of each operand is determined by assuming that each template type parameter denotes a cv-unqualified complete non-array object type.
Every expression required to be equality preserving is further required to be *stable*: two evaluations of such an expression with the same input objects must have equal outputs absent any explicit intervening modification of those input objects.
Unless noted otherwise, every expression used in a *requires-expression* is required to be equality preserving and stable, and the evaluation of the expression may modify only its non-constant operands. Operands that are constant must not be modified.
### Implicit expression variations
A *requires-expression* that uses an expression that is non-modifying for some constant lvalue operand also implicitly requires additional variations of that expression that accept a non-constant lvalue or (possibly constant) rvalue for the given operand unless such an expression variation is explicitly required with differing semantics. These *implicit expression variations* must meet the same semantic requirements of the declared expression. The extent to which an implementation validates the syntax of the variations is unspecified.
### See also
| | |
| --- | --- |
| [ranges::sized\_range](../ranges/sized_range "cpp/ranges/sized range")
(C++20) | specifies that a range knows its size in constant time (concept) |
| [ranges::size](../ranges/size "cpp/ranges/size")
(C++20) | returns an integer equal to the size of a range (customization point object) |
cpp std::front_inserter std::front\_inserter
====================
| Defined in header `[<iterator>](../header/iterator "cpp/header/iterator")` | | |
| --- | --- | --- |
|
```
template< class Container >
std::front_insert_iterator<Container> front_inserter( Container& c );
```
| | (until C++20) |
|
```
template< class Container >
constexpr std::front_insert_iterator<Container> front_inserter( Container& c );
```
| | (since C++20) |
`front_inserter` is a convenience function template that constructs a `[std::front\_insert\_iterator](front_insert_iterator "cpp/iterator/front insert iterator")` for the container `c` with the type deduced from the type of the argument.
### Parameters
| | | |
| --- | --- | --- |
| c | - | container that supports a `push_front` operation |
### Return value
A `[std::front\_insert\_iterator](front_insert_iterator "cpp/iterator/front insert iterator")` which can be used to add elements to the beginning of the container `c`.
### Possible implementation
| |
| --- |
|
```
template< class Container >
std::front_insert_iterator<Container> front_inserter( Container& c )
{
return std::front_insert_iterator<Container>(c);
}
```
|
### Example
```
#include <vector>
#include <deque>
#include <iostream>
#include <iterator>
#include <algorithm>
int main()
{
std::vector<int> v{1,2,3,4,5};
std::deque<int> d;
std::copy(v.begin(), v.end(), std::front_inserter(d));
for(int n : d)
std::cout << n << ' ';
}
```
Output:
```
5 4 3 2 1
```
### See also
| | |
| --- | --- |
| [front\_insert\_iterator](front_insert_iterator "cpp/iterator/front insert iterator") | iterator adaptor for insertion at the front of a container (class template) |
| [back\_inserter](back_inserter "cpp/iterator/back inserter") | creates a `[std::back\_insert\_iterator](back_insert_iterator "cpp/iterator/back insert iterator")` of type inferred from the argument (function template) |
| [inserter](inserter "cpp/iterator/inserter") | creates a `[std::insert\_iterator](insert_iterator "cpp/iterator/insert iterator")` of type inferred from the argument (function template) |
cpp std::insert_iterator std::insert\_iterator
=====================
| Defined in header `[<iterator>](../header/iterator "cpp/header/iterator")` | | |
| --- | --- | --- |
|
```
template< class Container >
class insert_iterator : public std::iterator< std::output_iterator_tag,
void,void,void,void >
```
| | (until C++17) |
|
```
template< class Container >
class insert_iterator;
```
| | (since C++17) |
`std::insert_iterator` is a [LegacyOutputIterator](../named_req/outputiterator "cpp/named req/OutputIterator") that inserts elements into a container for which it was constructed, at the position pointed to by the supplied iterator. The container's `insert()` member function is called whenever the iterator (whether dereferenced or not) is assigned to. Incrementing the `std::insert_iterator` is a no-op.
### Member types
| Member type | Definition |
| --- | --- |
| `iterator_category` | `[std::output\_iterator\_tag](http://en.cppreference.com/w/cpp/iterator/iterator_tags)` |
| `value_type` | `void` |
| `difference_type` |
| | |
| --- | --- |
| `void`. | (until C++20) |
| `[std::ptrdiff\_t](http://en.cppreference.com/w/cpp/types/ptrdiff_t)`. | (since C++20) |
|
| `pointer` | `void` |
| `reference` | `void` |
| `container_type` | `Container` |
| | |
| --- | --- |
| Member types `iterator_category`, `value_type`, `difference_type`, `pointer` and `reference` are required to be obtained by inheriting from `[std::iterator](http://en.cppreference.com/w/cpp/iterator/iterator)<[std::output\_iterator\_tag](http://en.cppreference.com/w/cpp/iterator/iterator_tags), void, void, void, void>`. | (until C++17) |
### Member functions
| | |
| --- | --- |
| [(constructor)](insert_iterator/insert_iterator "cpp/iterator/insert iterator/insert iterator") | constructs a new `insert_iterator` (public member function) |
| [operator=](insert_iterator/operator= "cpp/iterator/insert iterator/operator=") | inserts an object into the associated container (public member function) |
| [operator\*](insert_iterator/operator* "cpp/iterator/insert iterator/operator*") | no-op (public member function) |
| [operator++operator++(int)](insert_iterator/operator_plus__plus_ "cpp/iterator/insert iterator/operator++") | no-op (public member function) |
### Member objects
| Member name | Definition |
| --- | --- |
| `container` (protected member object) | a pointer of type `Container*` |
| `iter` (protected member object) | an iterator of type `Container::iterator` (until C++20) `ranges::iterator_t<Container>` (since C++20) |
### Example
```
#include <vector>
#include <list>
#include <iostream>
#include <iterator>
#include <algorithm>
int main()
{
std::vector<int> v{1,2,3,4,5};
std::list<int> l{-1,-2,-3};
std::copy(v.begin(), v.end(), // may be simplified with std::inserter
std::insert_iterator<std::list<int>>(l, std::next(l.begin())));
for (int n : l)
std::cout << n << ' ';
std::cout << '\n';
}
```
Output:
```
-1 1 2 3 4 5 -2 -3
```
### See also
| | |
| --- | --- |
| [inserter](inserter "cpp/iterator/inserter") | creates a `std::insert_iterator` of type inferred from the argument (function template) |
| [back\_insert\_iterator](back_insert_iterator "cpp/iterator/back insert iterator") | iterator adaptor for insertion at the end of a container (class template) |
| [front\_insert\_iterator](front_insert_iterator "cpp/iterator/front insert iterator") | iterator adaptor for insertion at the front of a container (class template) |
cpp std::bidirectional_iterator std::bidirectional\_iterator
============================
| Defined in header `[<iterator>](../header/iterator "cpp/header/iterator")` | | |
| --- | --- | --- |
|
```
template<class I>
concept bidirectional_iterator =
std::forward_iterator<I> &&
std::derived_from</*ITER_CONCEPT*/<I>, std::bidirectional_iterator_tag> &&
requires(I i) {
{ --i } -> std::same_as<I&>;
{ i-- } -> std::same_as<I>;
};
```
| | (since C++20) |
The concept `bidirectional_iterator` refines [`forward_iterator`](forward_iterator "cpp/iterator/forward iterator") by adding the ability to move an iterator backward.
### Iterator concept determination
Definition of this concept is specified via an exposition-only alias template `/*ITER_CONCEPT*/`.
In order to determine `/*ITER_CONCEPT*/<I>`, let `ITER_TRAITS<I>` denote `I` if the specialization `[std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<I>` is generated from the primary template, or `[std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<I>` otherwise:
* If `ITER_TRAITS<I>::iterator_concept` is valid and names a type, `/*ITER_CONCEPT*/<I>` denotes the type.
* Otherwise, if `ITER_TRAITS<I>::iterator_category` is valid and names a type, `/*ITER_CONCEPT*/<I>` denotes the type.
* Otherwise, if `[std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<I>` is generated from the primary template, `/*ITER_CONCEPT*/<I>` denotes `[std::random\_access\_iterator\_tag](iterator_tags "cpp/iterator/iterator tags")`.
* Otherwise, `/*ITER_CONCEPT*/<I>` does not denote a type and results in a substitution failure.
### Semantic requirements
A bidirectional iterator `r` is said to be *decrementable* if and only if there exists some `s` such that `++s == r`.
`bidirectional_iterator<I>` is modeled only if all the concepts it subsumes are modeled, and given two objects `a` and `b` of type `I`:
* If `a` is decrementable, `a` is in the domain of the expressions `--a` and `a--`.
* Pre-decrement yields an lvalue that refers to the operand: `[std::addressof](http://en.cppreference.com/w/cpp/memory/addressof)(--a) == [std::addressof](http://en.cppreference.com/w/cpp/memory/addressof)(a)`;
* Post-decrement yields the previous value of the operand: if `bool(a == b)`, then `bool(a-- == b)`.
* Post-decrement and pre-decrement perform the same modification on its operand: If `bool(a == b)`, then after evaluating both `a--` and `--b`, `bool(a == b)` still holds.
* Increment and decrement are inverses of each other:
+ If `a` is incrementable and `bool(a == b)`, then `bool(--(++a) == b)`.
+ If `a` is decrementable and `bool(a == b)`, then `bool(++(--a) == b)`.
### Equality preservation
An expression is *equality preserving* if it results in equal outputs given equal inputs.
* The inputs to an expression consist of its operands.
* The outputs of an expression consist of its result and all operands modified by the expression (if any).
In specification of standard concepts, operands are defined as the largest subexpressions that include only:
* an [id-expression](../language/expressions#Primary_expressions "cpp/language/expressions"), and
* invocations of [`std::move`](../utility/move "cpp/utility/move"), `[std::forward](../utility/forward "cpp/utility/forward")`, and `[std::declval](../utility/declval "cpp/utility/declval")`.
The cv-qualification and value category of each operand is determined by assuming that each template type parameter denotes a cv-unqualified complete non-array object type.
Every expression required to be equality preserving is further required to be *stable*: two evaluations of such an expression with the same input objects must have equal outputs absent any explicit intervening modification of those input objects.
Unless noted otherwise, every expression used in a *requires-expression* is required to be equality preserving and stable, and the evaluation of the expression may modify only its non-constant operands. Operands that are constant must not be modified.
### Notes
Unlike the [LegacyBidirectionalIterator](../named_req/bidirectionaliterator "cpp/named req/BidirectionalIterator") requirements, the `bidirectional_iterator` concept does not require dereference to return an lvalue.
### See also
| | |
| --- | --- |
| [forward\_iterator](forward_iterator "cpp/iterator/forward iterator")
(C++20) | specifies that an [`input_iterator`](input_iterator "cpp/iterator/input iterator") is a forward iterator, supporting equality comparison and multi-pass (concept) |
cpp std::input_or_output_iterator std::input\_or\_output\_iterator
================================
| Defined in header `[<iterator>](../header/iterator "cpp/header/iterator")` | | |
| --- | --- | --- |
|
```
template <class I>
concept input_or_output_iterator =
requires(I i) {
{ *i } -> /*can-reference*/;
} &&
std::weakly_incrementable<I>;
```
| | (since C++20) |
The `input_or_output_iterator` concept forms the basis of the iterator concept taxonomy; every iterator type satisfies the `input_or_output_iterator` requirements.
The exposition-only concept `/*can-reference*/` is satisfied if and only if the type is referenceable (in particular, not `void`).
### Equality preservation
An expression is *equality preserving* if it results in equal outputs given equal inputs.
* The inputs to an expression consist of its operands.
* The outputs of an expression consist of its result and all operands modified by the expression (if any).
In specification of standard concepts, operands are defined as the largest subexpressions that include only:
* an [id-expression](../language/expressions#Primary_expressions "cpp/language/expressions"), and
* invocations of [`std::move`](../utility/move "cpp/utility/move"), `[std::forward](../utility/forward "cpp/utility/forward")`, and `[std::declval](../utility/declval "cpp/utility/declval")`.
The cv-qualification and value category of each operand is determined by assuming that each template type parameter denotes a cv-unqualified complete non-array object type.
Every expression required to be equality preserving is further required to be *stable*: two evaluations of such an expression with the same input objects must have equal outputs absent any explicit intervening modification of those input objects.
Unless noted otherwise, every expression used in a *requires-expression* is required to be equality preserving and stable, and the evaluation of the expression may modify only its non-constant operands. Operands that are constant must not be modified.
### Notes
`input_or_output_iterator` itself only specifies operations for dereferencing and incrementing an iterator. Most algorithms will require additional operations, for example:
* comparing iterators with sentinels (see [`sentinel_for`](sentinel_for "cpp/iterator/sentinel for"));
* reading values from an iterator (see [`indirectly_readable`](indirectly_readable "cpp/iterator/indirectly readable") and [`input_iterator`](input_iterator "cpp/iterator/input iterator"))
* writing values to an iterator (see [`indirectly_writable`](indirectly_writable "cpp/iterator/indirectly writable") and [`output_iterator`](output_iterator "cpp/iterator/output iterator"))
* a richer set of iterator movements (see [`forward_iterator`](forward_iterator "cpp/iterator/forward iterator"), [`bidirectional_iterator`](bidirectional_iterator "cpp/iterator/bidirectional iterator"), [`random_access_iterator`](random_access_iterator "cpp/iterator/random access iterator"))
Unlike the [LegacyIterator](../named_req/iterator "cpp/named req/Iterator") requirements, the `input_or_output_iterator` concept does not require copyability.
cpp std::default_sentinel_t, std::default_sentinel std::default\_sentinel\_t, std::default\_sentinel
=================================================
| Defined in header `[<iterator>](../header/iterator "cpp/header/iterator")` | | |
| --- | --- | --- |
|
```
struct default_sentinel_t { };
```
| (1) | (since C++20) |
|
```
inline constexpr default_sentinel_t default_sentinel{};
```
| (2) | (since C++20) |
1) `default_sentinel_t` is an empty class type used to denote the end of a range. It can be used together with iterator types that know the bound of their range (e.g., `[std::counted\_iterator](counted_iterator "cpp/iterator/counted iterator")`).
2) `default_sentinel` is a constant of type `default_sentinel_t`. ### Example
```
#include <iterator>
#include <algorithm>
#include <list>
#include <iostream>
int main()
{
std::list<int> l{3,1,4,1,5,9,2,6};
std::ranges::copy(std::counted_iterator(std::begin(l), 4),
std::default_sentinel, std::ostream_iterator<int>{std::cout, " "});
}
```
Output:
```
3 1 4 1
```
### See also
| | |
| --- | --- |
| [istream\_iterator](istream_iterator "cpp/iterator/istream iterator") | input iterator that reads from `[std::basic\_istream](../io/basic_istream "cpp/io/basic istream")` (class template) |
| [istreambuf\_iterator](istreambuf_iterator "cpp/iterator/istreambuf iterator") | input iterator that reads from `[std::basic\_streambuf](../io/basic_streambuf "cpp/io/basic streambuf")` (class template) |
| [counted\_iterator](counted_iterator "cpp/iterator/counted iterator")
(C++20) | iterator adaptor that tracks the distance to the end of the range (class template) |
cpp std::front_insert_iterator std::front\_insert\_iterator
============================
| Defined in header `[<iterator>](../header/iterator "cpp/header/iterator")` | | |
| --- | --- | --- |
|
```
template< class Container >
class front_insert_iterator : public std::iterator< std::output_iterator_tag,
void,void,void,void >
```
| | (until C++17) |
|
```
template< class Container >
class front_insert_iterator;
```
| | (since C++17) |
`std::front_insert_iterator` is an [LegacyOutputIterator](../named_req/outputiterator "cpp/named req/OutputIterator") that prepends elements to a container for which it was constructed. The container's `push_front()` member function is called whenever the iterator (whether dereferenced or not) is assigned to. Incrementing the `std::front_insert_iterator` is a no-op.
### Member types
| Member type | Definition |
| --- | --- |
| `iterator_category` | `[std::output\_iterator\_tag](http://en.cppreference.com/w/cpp/iterator/iterator_tags)` |
| `value_type` | `void` |
| `difference_type` |
| | |
| --- | --- |
| `void`. | (until C++20) |
| `[std::ptrdiff\_t](http://en.cppreference.com/w/cpp/types/ptrdiff_t)`. | (since C++20) |
|
| `pointer` | `void` |
| `reference` | `void` |
| `container_type` | `Container` |
| | |
| --- | --- |
| Member types `iterator_category`, `value_type`, `difference_type`, `pointer` and `reference` are required to be obtained by inheriting from `[std::iterator](http://en.cppreference.com/w/cpp/iterator/iterator)<[std::output\_iterator\_tag](http://en.cppreference.com/w/cpp/iterator/iterator_tags), void, void, void, void>`. | (until C++17) |
### Member functions
| | |
| --- | --- |
| [(constructor)](front_insert_iterator/front_insert_iterator "cpp/iterator/front insert iterator/front insert iterator") | constructs a new `front_insert_iterator` (public member function) |
| [operator=](front_insert_iterator/operator= "cpp/iterator/front insert iterator/operator=") | inserts an object into the associated container (public member function) |
| [operator\*](front_insert_iterator/operator* "cpp/iterator/front insert iterator/operator*") | no-op (public member function) |
| [operator++operator++(int)](front_insert_iterator/operator_plus__plus_ "cpp/iterator/front insert iterator/operator++") | no-op (public member function) |
### Member objects
| Member name | Definition |
| --- | --- |
| `container` (protected) | a pointer of type `Container*` |
### Example
```
#include <vector>
#include <deque>
#include <iostream>
#include <iterator>
#include <algorithm>
int main()
{
std::vector<int> v{1,2,3,4,5};
std::deque<int> d;
std::copy(v.begin(), v.end(),
std::front_insert_iterator<std::deque<int>>(d)); // or std::front_inserter(d)
for(int n : d)
std::cout << n << ' ';
std::cout << '\n';
}
```
Output:
```
5 4 3 2 1
```
### See also
| | |
| --- | --- |
| [front\_inserter](front_inserter "cpp/iterator/front inserter") | creates a `std::front_insert_iterator` of type inferred from the argument (function template) |
| [back\_insert\_iterator](back_insert_iterator "cpp/iterator/back insert iterator") | iterator adaptor for insertion at the end of a container (class template) |
| [insert\_iterator](insert_iterator "cpp/iterator/insert iterator") | iterator adaptor for insertion into a container (class template) |
| programming_docs |
cpp std::reverse_iterator std::reverse\_iterator
======================
| Defined in header `[<iterator>](../header/iterator "cpp/header/iterator")` | | |
| --- | --- | --- |
|
```
template< class Iter >
class reverse_iterator;
```
| | |
`std::reverse_iterator` is an iterator adaptor that reverses the direction of a given iterator, which must be at least a [LegacyBidirectionalIterator](../named_req/bidirectionaliterator "cpp/named req/BidirectionalIterator") or model [`bidirectional_iterator`](bidirectional_iterator "cpp/iterator/bidirectional iterator") (since C++20). In other words, when provided with a bidirectional iterator, `std::reverse_iterator` produces a new iterator that moves from the end to the beginning of the sequence defined by the underlying bidirectional iterator.
For a reverse iterator `r` constructed from an iterator `i`, the relationship `&*r == &*(i-1)` is always true (as long as `r` is dereferenceable); thus a reverse iterator constructed from a one-past-the-end iterator dereferences to the last element in a sequence.
This is the iterator returned by member functions `rbegin()` and `rend()` of the standard library containers.
![range-rbegin-rend.svg]()
### Member types
| | | | | | | | | | | | | | | | |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
| Member type | Definition |
| --- | --- |
| `iterator_type` | `Iter` |
| `iterator_category` | `[std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<Iter>::iterator\_category` |
| `value_type` | `[std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<Iter>::value\_type` |
| `difference_type` | `[std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<Iter>::difference\_type` |
| `pointer` | `[std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<Iter>::pointer` |
| `reference` | `[std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<Iter>::reference` |
| (until C++20) |
|
| Member type | Definition |
| --- | --- |
| `iterator_type` | `Iter` |
| `iterator_concept` | If `Iter` models `[std::random\_access\_iterator](http://en.cppreference.com/w/cpp/iterator/random_access_iterator)`, this is `[std::random\_access\_iterator\_tag](iterator_tags "cpp/iterator/iterator tags")`. Otherwise, this is `[std::bidirectional\_iterator\_tag](iterator_tags "cpp/iterator/iterator tags")` |
| `iterator_category` | If `[std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<Iter>::iterator\_category` models `[std::derived\_from](http://en.cppreference.com/w/cpp/concepts/derived_from)<[std::random\_access\_iterator\_tag](http://en.cppreference.com/w/cpp/iterator/iterator_tags)>`, this is `[std::random\_access\_iterator\_tag](iterator_tags "cpp/iterator/iterator tags")`. Otherwise, this is `[std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<Iter>::iterator\_category` |
| `value_type` | `[std::iter\_value\_t](http://en.cppreference.com/w/cpp/iterator/iter_t)<Iter>` |
| `difference_type` | `[std::iter\_difference\_t](http://en.cppreference.com/w/cpp/iterator/iter_t)<Iter>` |
| `pointer` | `[std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<Iter>::pointer` |
| `reference` | `[std::iter\_reference\_t](http://en.cppreference.com/w/cpp/iterator/iter_t)<Iter>` |
| (since C++20) |
| | |
| --- | --- |
| Member types `iterator_category`, `value_type`, `difference_type`, `pointer` and `reference` are required to be obtained by inheriting from `[std::iterator](http://en.cppreference.com/w/cpp/iterator/iterator)< [std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<Iter>::iterator\_category , [std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<Iter>::value\_type , [std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<Iter>::difference\_type , [std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<Iter>::pointer , [std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<Iter>::reference >`. | (until C++17) |
### Member functions
| | |
| --- | --- |
| [(constructor)](reverse_iterator/reverse_iterator "cpp/iterator/reverse iterator/reverse iterator") | constructs a new iterator adaptor (public member function) |
| [operator=](reverse_iterator/operator= "cpp/iterator/reverse iterator/operator=") | assigns another iterator adaptor (public member function) |
| [base](reverse_iterator/base "cpp/iterator/reverse iterator/base") | accesses the underlying iterator (public member function) |
| [operator\*operator->](reverse_iterator/operator* "cpp/iterator/reverse iterator/operator*") | accesses the pointed-to element (public member function) |
| [operator[]](reverse_iterator/operator_at "cpp/iterator/reverse iterator/operator at") | accesses an element by index (public member function) |
| [operator++operator++(int)operator+=operator+operator--operator--(int)operator-=operator-](reverse_iterator/operator_arith "cpp/iterator/reverse iterator/operator arith") | advances or decrements the iterator (public member function) |
### Member objects
| Member name | Definition |
| --- | --- |
| `current` (protected) | the underlying iterator of which [`base()`](reverse_iterator/base "cpp/iterator/reverse iterator/base") returns a copy |
### Non-member functions
| | |
| --- | --- |
| [operator==operator!=operator<operator<=operator>operator>=operator<=>](reverse_iterator/operator_cmp "cpp/iterator/reverse iterator/operator cmp")
(C++20) | compares the underlying iterators (function template) |
| [operator+](reverse_iterator/operator_plus_ "cpp/iterator/reverse iterator/operator+") | advances the iterator (function template) |
| [operator-](reverse_iterator/operator- "cpp/iterator/reverse iterator/operator-") | computes the distance between two iterator adaptors (function template) |
| [iter\_move](reverse_iterator/iter_move "cpp/iterator/reverse iterator/iter move")
(C++20) | casts the result of dereferencing the adjusted underlying iterator to its associated rvalue reference type (function) |
| [iter\_swap](reverse_iterator/iter_swap "cpp/iterator/reverse iterator/iter swap")
(C++20) | swaps the objects pointed to by two adjusted underlying iterators (function template) |
| [make\_reverse\_iterator](make_reverse_iterator "cpp/iterator/make reverse iterator")
(C++14) | creates a `std::reverse_iterator` of type inferred from the argument (function template) |
### Helper templates
| | | |
| --- | --- | --- |
|
```
template< class Iterator1, class Iterator2 >
requires (!std::sized_sentinel_for<Iterator1, Iterator2>)
inline constexpr bool disable_sized_sentinel_for<
std::reverse_iterator<Iterator1>,
std::reverse_iterator<Iterator2>> = true;
```
| | (since C++20) |
This partial specialization of `std::disable_sized_sentinel_for` prevents specializations of `reverse_iterator` from satisfying [`sized_sentinel_for`](sized_sentinel_for "cpp/iterator/sized sentinel for") if their underlying iterators do not satisfy the concept.
### Possible implementation
Below is a partial implementation focusing on the way the inner iterator is saved, calling prev only when the content is fetched via operator\*.
| |
| --- |
|
```
template<typename Itr>
class reverse_iterator {
Itr itr;
public:
constexpr explicit reverse_iterator(Itr itr): itr(itr) {}
constexpr auto& operator*() {
return *std::prev(itr); // <== returns the content of prev
}
constexpr auto& operator++() {
--itr;
return *this;
}
constexpr friend bool operator!=(reverse_iterator<Itr> a, reverse_iterator<Itr> b) {
return a.itr != b.itr;
}
};
```
|
### Notes
`std::reverse_iterator` does not work with iterators whose dereference returns a reference to a member of `*this` (so-called "stashing iterators").
### Example
```
#include <iostream>
#include <iterator>
template<typename T, size_t SIZE>
class Stack {
T arr[SIZE];
size_t pos = 0;
public:
T pop() {
return arr[--pos];
}
Stack& push(const T& t) {
arr[pos++] = t;
return *this;
}
// we wish that looping on Stack would be in LIFO order
// thus we use std::reverse_iterator as an adaptor to existing iterators
// (which are in this case the simple pointers: [arr, arr+pos)
auto begin() {
return std::reverse_iterator(arr + pos);
}
auto end() {
return std::reverse_iterator(arr);
}
};
int main() {
Stack<int, 8> s;
s.push(5).push(15).push(25).push(35);
for(int val: s) {
std::cout << val << ' ';
}
}
```
Output:
```
35 25 15 5
```
### See also
| | |
| --- | --- |
| [make\_reverse\_iterator](make_reverse_iterator "cpp/iterator/make reverse iterator")
(C++14) | creates a `std::reverse_iterator` of type inferred from the argument (function template) |
| [iterator](iterator "cpp/iterator/iterator")
(deprecated in C++17) | base class to ease the definition of required types for simple iterators (class template) |
cpp std::move_sentinel std::move\_sentinel
===================
| Defined in header `[<iterator>](../header/iterator "cpp/header/iterator")` | | |
| --- | --- | --- |
|
```
template< std::semiregular S >
class move_sentinel;
```
| | (since C++20) |
`std::move_sentinel` is a sentinel adaptor used for denoting ranges together with `[std::move\_iterator](move_iterator "cpp/iterator/move iterator")`.
### Template parameters
| | | |
| --- | --- | --- |
| S | - | the type of underlying sentinel |
### Member functions
| | |
| --- | --- |
| [(constructor)](move_sentinel/move_sentinel "cpp/iterator/move sentinel/move sentinel")
(C++20) | constructs a new `move_sentinel` (public member function) |
| [operator=](move_sentinel/operator= "cpp/iterator/move sentinel/operator=")
(C++20) | assigns the contents of one `move_sentinel` to another (public member function) |
| [base](move_sentinel/base "cpp/iterator/move sentinel/base")
(C++20) | return a copy of the underlying sentinel (public member function) |
### Member objects
| Member name | Definition |
| --- | --- |
| `*last*` (private member object) | underlying sentinel, the name is for exposition only |
### Non-member functions
Notes: These functions are hidden friends of `[std::move\_iterator](move_iterator "cpp/iterator/move iterator")` and invisible to ordinary [unqualified](../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../language/qualified_lookup "cpp/language/qualified lookup").
| | |
| --- | --- |
| [operator==(std::move\_sentinel)](move_iterator/operator_cmp2 "cpp/iterator/move iterator/operator cmp2")
(C++20) | compares the underlying iterator and the underlying sentinel (function template) |
| [operator-(std::move\_sentinel)](move_iterator/operator-2 "cpp/iterator/move iterator/operator-2")
(C++20) | computes the distance between the underlying iterator and the underlying sentinel (function template) |
### Example
### See also
| | |
| --- | --- |
| [move\_iterator](move_iterator "cpp/iterator/move iterator")
(C++11) | iterator adaptor which dereferences to an rvalue reference (class template) |
cpp std::indirect_unary_predicate std::indirect\_unary\_predicate
===============================
| Defined in header `[<iterator>](../header/iterator "cpp/header/iterator")` | | |
| --- | --- | --- |
|
```
template<class F, class I>
concept indirect_unary_predicate =
std::indirectly_readable<I> &&
std::copy_constructible<F> &&
std::predicate<F&, std::iter_value_t<I>&> &&
std::predicate<F&, std::iter_reference_t<I>> &&
std::predicate<F&, std::iter_common_reference_t<I>>;
```
| | (since C++20) |
The concept `indirect_unary_predicate` specifies requirements for algorithms that call unary predicates as their arguments. The key difference between this concept and `[std::predicate](../concepts/predicate "cpp/concepts/predicate")` is that it is applied to the type that `I` references, rather than `I` itself.
### Semantic requirements
`F` and `I` model `indirect_unary_predicate` only if all concepts it subsumes are modeled.
cpp std::empty std::empty
==========
| Defined in header `[<array>](../header/array "cpp/header/array")` | | |
| --- | --- | --- |
| Defined in header `[<deque>](../header/deque "cpp/header/deque")` | | |
| Defined in header `[<forward\_list>](../header/forward_list "cpp/header/forward list")` | | |
| Defined in header `[<iterator>](../header/iterator "cpp/header/iterator")` | | |
| Defined in header `[<list>](../header/list "cpp/header/list")` | | |
| Defined in header `[<map>](../header/map "cpp/header/map")` | | |
| Defined in header `[<regex>](../header/regex "cpp/header/regex")` | | |
| Defined in header `[<set>](../header/set "cpp/header/set")` | | |
| Defined in header `[<span>](../header/span "cpp/header/span")` | | (since C++20) |
| Defined in header `[<string>](../header/string "cpp/header/string")` | | |
| Defined in header `[<string\_view>](../header/string_view "cpp/header/string view")` | | |
| Defined in header `[<unordered\_map>](../header/unordered_map "cpp/header/unordered map")` | | |
| Defined in header `[<unordered\_set>](../header/unordered_set "cpp/header/unordered set")` | | |
| Defined in header `[<vector>](../header/vector "cpp/header/vector")` | | |
| | (1) | |
|
```
template <class C>
constexpr auto empty(const C& c) -> decltype(c.empty());
```
| (since C++17) (until C++20) |
|
```
template <class C>
[[nodiscard]] constexpr auto empty(const C& c) -> decltype(c.empty());
```
| (since C++20) |
| | (2) | |
|
```
template <class T, std::size_t N>
constexpr bool empty(const T (&array)[N]) noexcept;
```
| (since C++17) (until C++20) |
|
```
template <class T, std::size_t N>
[[nodiscard]] constexpr bool empty(const T (&array)[N]) noexcept;
```
| (since C++20) |
| | (3) | |
|
```
template <class E>
constexpr bool empty(std::initializer_list<E> il) noexcept;
```
| (since C++17) (until C++20) |
|
```
template <class E>
[[nodiscard]] constexpr bool empty(std::initializer_list<E> il) noexcept;
```
| (since C++20) |
Returns whether the given range is empty.
1) returns `c.empty()`
2) returns `false`
3) returns `il.size() == 0`
### Parameters
| | | |
| --- | --- | --- |
| c | - | a container or view with an `empty` member function |
| array | - | an array of arbitrary type |
| il | - | an initializer list |
### Return value
`true` if the range doesn't have any element.
### Exceptions
1) May throw implementation-defined exceptions. ### Notes
The overload for `[std::initializer\_list](../utility/initializer_list "cpp/utility/initializer list")` is necessary because it does not have a member function `empty`.
| [Feature-test](../utility/feature_test "cpp/utility/feature test") macro |
| --- |
| [`__cpp_lib_nonmember_container_access`](../feature_test#Library_features "cpp/feature test") |
### Possible implementation
| First version |
| --- |
|
```
template <class C>
[[nodiscard]] constexpr auto empty(const C& c) -> decltype(c.empty())
{
return c.empty();
}
```
|
| Second version |
|
```
template <class T, std::size_t N>
[[nodiscard]] constexpr bool empty(const T (&array)[N]) noexcept
{
return false;
}
```
|
| Third version |
|
```
template <class E>
[[nodiscard]] constexpr bool empty(std::initializer_list<E> il) noexcept
{
return il.size() == 0;
}
```
|
### Example
```
#include <iostream>
#include <vector>
template <class T>
void print(const T& container)
{
if ( std::empty(container) )
{
std::cout << "Empty\n";
}
else
{
std::cout << "Elements:";
for ( const auto& element : container )
std::cout << ' ' << element;
std::cout << '\n';
}
}
int main()
{
std::vector<int> c = { 1, 2, 3 };
print(c);
c.clear();
print(c);
int array[] = { 4, 5, 6 };
print(array);
auto il = { 7, 8, 9 };
print(il);
}
```
Output:
```
Elements: 1 2 3
Empty
Elements: 4 5 6
Elements: 7 8 9
```
### See also
| | |
| --- | --- |
| [ranges::empty](../ranges/empty "cpp/ranges/empty")
(C++20) | checks whether a range is empty (customization point object) |
cpp std::begin, std::cbegin std::begin, std::cbegin
=======================
| Defined in header `[<array>](../header/array "cpp/header/array")` | | |
| --- | --- | --- |
| Defined in header `[<deque>](../header/deque "cpp/header/deque")` | | |
| Defined in header `[<forward\_list>](../header/forward_list "cpp/header/forward list")` | | |
| Defined in header `[<iterator>](../header/iterator "cpp/header/iterator")` | | |
| Defined in header `[<list>](../header/list "cpp/header/list")` | | |
| Defined in header `[<map>](../header/map "cpp/header/map")` | | |
| Defined in header `[<regex>](../header/regex "cpp/header/regex")` | | |
| Defined in header `[<set>](../header/set "cpp/header/set")` | | |
| Defined in header `[<span>](../header/span "cpp/header/span")` | | (since C++20) |
| Defined in header `[<string>](../header/string "cpp/header/string")` | | |
| Defined in header `[<string\_view>](../header/string_view "cpp/header/string view")` | | (since C++17) |
| Defined in header `[<unordered\_map>](../header/unordered_map "cpp/header/unordered map")` | | |
| Defined in header `[<unordered\_set>](../header/unordered_set "cpp/header/unordered set")` | | |
| Defined in header `[<vector>](../header/vector "cpp/header/vector")` | | |
| | (1) | |
|
```
template< class C >
auto begin( C& c ) -> decltype(c.begin());
```
| (since C++11) (until C++17) |
|
```
template< class C >
constexpr auto begin( C& c ) -> decltype(c.begin());
```
| (since C++17) |
| | (1) | |
|
```
template< class C >
auto begin( const C& c ) -> decltype(c.begin());
```
| (since C++11) (until C++17) |
|
```
template< class C >
constexpr auto begin( const C& c ) -> decltype(c.begin());
```
| (since C++17) |
| | (2) | |
|
```
template< class T, std::size_t N >
T* begin( T (&array)[N] );
```
| (since C++11) (until C++14) |
|
```
template< class T, std::size_t N >
constexpr T* begin( T (&array)[N] ) noexcept;
```
| (since C++14) |
|
```
template< class C >
constexpr auto cbegin( const C& c ) noexcept(/* see below */)
-> decltype(std::begin(c));
```
| (3) | (since C++14) |
Returns an iterator to the beginning of the given range.
1) Returns exactly `c.begin()`, which is typically an iterator to the beginning of the sequence represented by `c`. If `C` is a standard [Container](../named_req/container "cpp/named req/Container"), this returns `C::iterator` when `c` is not const-qualified, and `C::const_iterator` otherwise.
2) Returns a pointer to the beginning of the `array`.
3) Returns exactly `std::begin(c)`, with `c` always treated as const-qualified. If `C` is a standard [Container](../named_req/container "cpp/named req/Container"), this always returns `C::const_iterator`. ![range-begin-end.svg]()
### Parameters
| | | |
| --- | --- | --- |
| c | - | a container or view with a `begin` member function |
| array | - | an array of arbitrary type |
### Return value
An iterator to the beginning the range.
### Exceptions
3)
[`noexcept`](../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept(noexcept(std::begin(c)))`
### Overloads
Custom overloads of `begin` may be provided for classes and enumerations that do not expose a suitable `begin()` member function, yet can be iterated. The following overloads are already provided by the standard library:
| | |
| --- | --- |
| [std::begin(std::initializer\_list)](../utility/initializer_list/begin2 "cpp/utility/initializer list/begin2")
(C++11) | overloads `std::begin` (function template) |
| [std::begin(std::valarray)](../numeric/valarray/begin2 "cpp/numeric/valarray/begin2")
(C++11) | overloads `std::begin` (function template) |
| [begin(std::filesystem::directory\_iterator)end(std::filesystem::directory\_iterator)](../filesystem/directory_iterator/begin "cpp/filesystem/directory iterator/begin")
(C++17) | range-based for loop support (function) |
| [begin(std::filesystem::recursive\_directory\_iterator)end(std::filesystem::recursive\_directory\_iterator)](../filesystem/recursive_directory_iterator/begin "cpp/filesystem/recursive directory iterator/begin") | range-based for loop support (function) |
Similar to the use of `swap` (described in [Swappable](../named_req/swappable "cpp/named req/Swappable")), typical use of the `begin` function in generic context is an equivalent of `using std::begin; begin(arg);`, which allows both the [ADL](../language/adl "cpp/language/adl")-selected overloads for user-defined types and the standard library function templates to appear in the same overload set.
```
template<typename Container, typename Function>
void for_each(Container&& cont, Function f) {
using std::begin;
auto it = begin(cont);
using std::end;
auto end_it = end(cont);
while (it != end_it) {
f(*it);
++it;
}
}
```
| | |
| --- | --- |
| Overloads of `begin` found by [argument-dependent lookup](../language/adl "cpp/language/adl") can be used to customize the behavior of `std::[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)`, `std::[ranges::cbegin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/cbegin)`, and other customization pointer objects depending on `std::[ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)`. | (since C++20) |
### Notes
(1,3) exactly reflect the behavior of `C::begin()`. Their effects may be surprising if the member function does not have a reasonable implementation.
`std::cbegin` is introduced for unification of member and non-member range accesses. See also [LWG issue 2128](https://cplusplus.github.io/LWG/issue2128).
If `C` is a shallow-const view, `std::cbegin` may return a mutable iterator. Such behavior is unexpected for some users. See also [P2276](https://wg21.link/P2276) and [P2278](https://wg21.link/P2278).
### Example
```
#include <iostream>
#include <vector>
#include <iterator>
int main()
{
std::vector<int> v = { 3, 1, 4 };
auto vi = std::begin(v);
std::cout << std::showpos << *vi << '\n';
int a[] = { -5, 10, 15 };
auto ai = std::begin(a);
std::cout << *ai << '\n';
}
```
Output:
```
+3
-5
```
### See also
| | |
| --- | --- |
| [endcend](end "cpp/iterator/end")
(C++11)(C++14) | returns an iterator to the end of a container or array (function template) |
| [ranges::begin](../ranges/begin "cpp/ranges/begin")
(C++20) | returns an iterator to the beginning of a range (customization point object) |
| [ranges::cbegin](../ranges/cbegin "cpp/ranges/cbegin")
(C++20) | returns an iterator to the beginning of a read-only range (customization point object) |
| programming_docs |
cpp std::ostreambuf_iterator std::ostreambuf\_iterator
=========================
| Defined in header `[<iterator>](../header/iterator "cpp/header/iterator")` | | |
| --- | --- | --- |
|
```
template< class CharT, class Traits = std::char_traits<CharT> >
class ostreambuf_iterator : public std::iterator<std::output_iterator_tag,
void, void, void, void>
```
| | (until C++17) |
|
```
template< class CharT, class Traits = std::char_traits<CharT> >
class ostreambuf_iterator;
```
| | (since C++17) |
`std::ostreambuf_iterator` is a single-pass [LegacyOutputIterator](../named_req/outputiterator "cpp/named req/OutputIterator") that writes successive characters into the `[std::basic\_streambuf](../io/basic_streambuf "cpp/io/basic streambuf")` object for which it was constructed. The actual write operation is performed when the iterator (whether dereferenced or not) is assigned to. Incrementing the `std::ostreambuf_iterator` is a no-op.
In a typical implementation, the only data members of `std::ostreambuf_iterator` are a pointer to the associated `std::basic_streambuf` and a boolean flag indicating if the end of file condition has been reached.
### Member types
| Member type | Definition |
| --- | --- |
| `iterator_category` | `[std::output\_iterator\_tag](http://en.cppreference.com/w/cpp/iterator/iterator_tags)` |
| `value_type` | `void` |
| `difference_type` |
| | |
| --- | --- |
| `void`. | (until C++20) |
| `[std::ptrdiff\_t](http://en.cppreference.com/w/cpp/types/ptrdiff_t)`. | (since C++20) |
|
| `pointer` | `void` |
| `reference` | `void` |
| `char_type` | `CharT` |
| `traits_type` | `Traits` |
| `streambuf_type` | `[std::basic\_streambuf](http://en.cppreference.com/w/cpp/io/basic_streambuf)<CharT, Traits>` |
| `ostream_type` | `[std::basic\_ostream](http://en.cppreference.com/w/cpp/io/basic_ostream)<CharT, Traits>` |
| | |
| --- | --- |
| Member types `iterator_category`, `value_type`, `difference_type`, `pointer` and `reference` are required to be obtained by inheriting from `[std::iterator](http://en.cppreference.com/w/cpp/iterator/iterator)<[std::output\_iterator\_tag](http://en.cppreference.com/w/cpp/iterator/iterator_tags), void, void, void, void>`. | (until C++17) |
### Member functions
| | |
| --- | --- |
| [(constructor)](ostreambuf_iterator/ostreambuf_iterator "cpp/iterator/ostreambuf iterator/ostreambuf iterator") | constructs a new `ostreambuf_iterator` (public member function) |
| (destructor)
(implicitly declared) | destructs an `ostreambuf_iterator` (public member function) |
| [operator=](ostreambuf_iterator/operator= "cpp/iterator/ostreambuf iterator/operator=") | writes a character to the associated output sequence (public member function) |
| [operator\*](ostreambuf_iterator/operator* "cpp/iterator/ostreambuf iterator/operator*") | no-op (public member function) |
| [operator++operator++(int)](ostreambuf_iterator/operator_arith "cpp/iterator/ostreambuf iterator/operator arith") | no-op (public member function) |
| [failed](ostreambuf_iterator/failed "cpp/iterator/ostreambuf iterator/failed") | tests if output failed (public member function) |
### Example
```
#include <string>
#include <algorithm>
#include <iterator>
#include <iostream>
int main()
{
std::string s = "This is an example\n";
std::copy(s.begin(), s.end(), std::ostreambuf_iterator<char>(std::cout));
}
```
Output:
```
This is an example
```
### See also
| | |
| --- | --- |
| [istreambuf\_iterator](istreambuf_iterator "cpp/iterator/istreambuf iterator") | input iterator that reads from `[std::basic\_streambuf](../io/basic_streambuf "cpp/io/basic streambuf")` (class template) |
| [ostream\_iterator](ostream_iterator "cpp/iterator/ostream iterator") | output iterator that writes to `[std::basic\_ostream](../io/basic_ostream "cpp/io/basic ostream")` (class template) |
cpp std::end, std::cend std::end, std::cend
===================
| Defined in header `[<array>](../header/array "cpp/header/array")` | | |
| --- | --- | --- |
| Defined in header `[<deque>](../header/deque "cpp/header/deque")` | | |
| Defined in header `[<forward\_list>](../header/forward_list "cpp/header/forward list")` | | |
| Defined in header `[<iterator>](../header/iterator "cpp/header/iterator")` | | |
| Defined in header `[<list>](../header/list "cpp/header/list")` | | |
| Defined in header `[<map>](../header/map "cpp/header/map")` | | |
| Defined in header `[<regex>](../header/regex "cpp/header/regex")` | | |
| Defined in header `[<set>](../header/set "cpp/header/set")` | | |
| Defined in header `[<span>](../header/span "cpp/header/span")` | | (since C++20) |
| Defined in header `[<string>](../header/string "cpp/header/string")` | | |
| Defined in header `[<string\_view>](../header/string_view "cpp/header/string view")` | | (since C++17) |
| Defined in header `[<unordered\_map>](../header/unordered_map "cpp/header/unordered map")` | | |
| Defined in header `[<unordered\_set>](../header/unordered_set "cpp/header/unordered set")` | | |
| Defined in header `[<vector>](../header/vector "cpp/header/vector")` | | |
| | (1) | |
|
```
template< class C >
auto end( C& c ) -> decltype(c.end());
```
| (since C++11) (until C++17) |
|
```
template< class C >
constexpr auto end( C& c ) -> decltype(c.end());
```
| (since C++17) |
| | (1) | |
|
```
template< class C >
auto end( const C& c ) -> decltype(c.end());
```
| (since C++11) (until C++17) |
|
```
template< class C >
constexpr auto end( const C& c ) -> decltype(c.end());
```
| (since C++17) |
| | (2) | |
|
```
template< class T, std::size_t N >
T* end( T (&array)[N] );
```
| (since C++11) (until C++14) |
|
```
template< class T, std::size_t N >
constexpr T* end( T (&array)[N] ) noexcept;
```
| (since C++14) |
|
```
template< class C >
constexpr auto cend( const C& c ) noexcept(/* see below */)
-> decltype(std::end(c));
```
| (3) | (since C++14) |
Returns an iterator to the end (i.e. the element after the last element) of the given range.
1) Returns exactly `c.end()`, which is typically an iterator one past the end of the sequence represented by `c`. If `C` is a standard [Container](../named_req/container "cpp/named req/Container"), this returns a `C::iterator` when `c` is not const-qualified, and a `C::const_iterator` otherwise.
2) Returns a pointer to the end of the array `array`.
3) Returns exactly `std::end(c)`, with `c` always treated as const-qualified. If `C` is a standard [Container](../named_req/container "cpp/named req/Container"), this always returns a `C::const_iterator`. ![range-begin-end.svg]()
### Parameters
| | | |
| --- | --- | --- |
| c | - | a container or view with an `end` member function |
| array | - | an array of arbitrary type |
### Return value
An iterator to the end of the range. Note that the end of a range is defined as the element following the last valid element.
### Exceptions
3)
[`noexcept`](../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept(noexcept(std::end(c)))`
### Overloads
Custom overloads of `end` may be provided for classes and enumerations that do not expose a suitable `end()` member function, yet can be iterated. The following overloads are already provided by the standard library:
| | |
| --- | --- |
| [std::end(std::initializer\_list)](../utility/initializer_list/end2 "cpp/utility/initializer list/end2")
(C++11) | specializes `std::end` (function template) |
| [std::end(std::valarray)](../numeric/valarray/end2 "cpp/numeric/valarray/end2")
(C++11) | specializes `std::end` (function template) |
| [begin(std::filesystem::directory\_iterator)end(std::filesystem::directory\_iterator)](../filesystem/directory_iterator/begin "cpp/filesystem/directory iterator/begin")
(C++17) | range-based for loop support (function) |
| [begin(std::filesystem::recursive\_directory\_iterator)end(std::filesystem::recursive\_directory\_iterator)](../filesystem/recursive_directory_iterator/begin "cpp/filesystem/recursive directory iterator/begin") | range-based for loop support (function) |
Similar to the use of `swap` (described in [Swappable](../named_req/swappable "cpp/named req/Swappable")), typical use of the `end` function in generic context is an equivalent of `using std::end; end(arg);`, which lets both the [ADL](../language/adl "cpp/language/adl")-selected overloads for user-defined types and the standard library function templates to appear in the same overload set.
```
template<typename Container, typename Function>
void for_each(Container&& cont, Function f) {
using std::begin;
auto it = begin(cont);
using std::end;
auto end_it = end(cont);
while (it != end_it) {
f(*it);
++it;
}
}
```
| | |
| --- | --- |
| Overloads of `end` found by [argument-dependent lookup](../language/adl "cpp/language/adl") can be used to customize the behavior of `std::[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)`, `std::[ranges::cend](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/cend)`, and other customization pointer objects depending on `std::[ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)`. | (since C++20) |
### Notes
(1,3) exactly reflect the behavior of `C::end()`. Their effects may be surprising if the member function does not have a reasonable implementation.
`std::cend` is introduced for unification of member and non-member range accesses. See also [LWG issue 2128](https://cplusplus.github.io/LWG/issue2128).
If `C` is a shallow-const view, `std::cend` may return a mutable iterator. Such behavior is unexpected for some users. See also [P2276](https://wg21.link/P2276) and [P2278](https://wg21.link/P2278).
### Example
```
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
int main()
{
std::vector<int> v = { 3, 1, 4 };
if (std::find(std::begin(v), std::end(v), 5) != std::end(v)) {
std::cout << "found a 5 in vector v!\n";
}
int a[] = { 5, 10, 15 };
if (std::find(std::begin(a), std::end(a), 5) != std::end(a)) {
std::cout << "found a 5 in array a!\n";
}
}
```
Output:
```
found a 5 in array a!
```
### See also
| | |
| --- | --- |
| [begincbegin](begin "cpp/iterator/begin")
(C++11)(C++14) | returns an iterator to the beginning of a container or array (function template) |
| [ranges::end](../ranges/end "cpp/ranges/end")
(C++20) | returns a sentinel indicating the end of a range (customization point object) |
| [ranges::cend](../ranges/cend "cpp/ranges/cend")
(C++20) | returns a sentinel indicating the end of a read-only range (customization point object) |
cpp std::ranges::advance std::ranges::advance
====================
| Defined in header `[<iterator>](../../header/iterator "cpp/header/iterator")` | | |
| --- | --- | --- |
| Call signature | | |
|
```
template< std::input_or_output_iterator I >
constexpr void advance( I& i, std::iter_difference_t<I> n );
```
| (1) | (since C++20) |
|
```
template< std::input_or_output_iterator I, std::sentinel_for<I> S >
constexpr void advance( I& i, S bound );
```
| (2) | (since C++20) |
|
```
template< std::input_or_output_iterator I, std::sentinel_for<I> S >
constexpr std::iter_difference_t<I> advance( I& i, std::iter_difference_t<I> n, S bound );
```
| (3) | (since C++20) |
1) Increments given iterator `i` for `n` times.
2) Increments given iterator `i` until `i == bound`.
3) Increments given iterator `i` for `n` times, or until `i == bound`, whichever comes first. If `n` is negative, the iterator is decremented. In this case, `I` must model `[std::bidirectional\_iterator](../bidirectional_iterator "cpp/iterator/bidirectional iterator")`, and `S` must be the same type as `I` if `bound` is provided, otherwise 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
| | | |
| --- | --- | --- |
| i | - | iterator to be advanced |
| bound | - | sentinel denoting the end of the range `i` is an iterator to |
| n | - | number of maximal increments of `i` |
### Return value
3) The difference between `n` and the actual distance `i` traversed. ### Complexity
Linear.
However, if `I` additionally models `[std::random\_access\_iterator](../random_access_iterator "cpp/iterator/random access iterator")`, or `S` models `[std::sized\_sentinel\_for](http://en.cppreference.com/w/cpp/iterator/sized_sentinel_for)<I>`, or `I` and `S` model `[std::assignable\_from](http://en.cppreference.com/w/cpp/concepts/assignable_from)<I&, S>`, complexity is constant.
### Notes
The behavior is undefined if the specified sequence of increments or decrements would require that a non-incrementable iterator (such as the past-the-end iterator) is incremented, or that a non-decrementable iterator (such as the front iterator or the singular iterator) is decremented.
### Possible implementation
| |
| --- |
|
```
struct advance_fn {
template<std::input_or_output_iterator I>
constexpr void operator()(I& i, std::iter_difference_t<I> n) const
{
if constexpr (std::random_access_iterator<I>) {
i += n;
}
else {
while (n > 0) {
--n;
++i;
}
if constexpr (std::bidirectional_iterator<I>) {
while (n < 0) {
++n;
--i;
}
}
}
}
template<std::input_or_output_iterator I, std::sentinel_for<I> S>
constexpr void operator()(I& i, S bound) const
{
if constexpr (std::assignable_from<I&, S>) {
i = std::move(bound);
}
else if constexpr (std::sized_sentinel_for<S, I>) {
(*this)(i, bound - i);
}
else {
while (i != bound) {
++i;
}
}
}
template<std::input_or_output_iterator I, std::sentinel_for<I> S>
constexpr std::iter_difference_t<I>
operator()(I& i, std::iter_difference_t<I> n, S bound) const
{
if constexpr (std::sized_sentinel_for<S, I>) {
// std::abs isn't constexpr until C++23
auto abs = [](const std::iter_difference_t<I> x) { return x < 0 ? -x : x; };
const auto dist = abs(n) - abs(bound - i);
if (dist < 0) {
(*this)(i, bound);
return -dist;
}
(*this)(i, n);
return 0;
}
else {
while (n > 0 && i != bound) {
--n;
++i;
}
if constexpr (std::bidirectional_iterator<I>) {
while (n < 0 && i != bound) {
++n;
--i;
}
}
return n;
}
}
};
inline constexpr auto advance = advance_fn();
```
|
### Example
```
#include <iomanip>
#include <iostream>
#include <iterator>
#include <vector>
int main()
{
std::vector<int> v{ 3, 1, 4 };
auto vi = v.begin();
std::ranges::advance(vi, 2);
std::cout << "value: " << *vi << '\n';
{
std::ranges::advance(vi, v.end());
std::cout << std::boolalpha;
std::cout << "vi == v.end(): " << (vi == v.end()) << '\n';
std::ranges::advance(vi, -3);
std::cout << "value: " << *vi << '\n';
std::cout << "diff: " << std::ranges::advance(vi, 2, v.end()) << ", ";
std::cout << "value: " << *vi << '\n';
std::cout << "diff: " << std::ranges::advance(vi, 4, v.end()) << ", ";
std::cout << "vi == v.end(): " << (vi == v.end()) << '\n';
std::cout << std::noboolalpha;
}
}
```
Output:
```
value: 4
vi == v.end(): true
value: 3
diff: 0, value: 4
diff: 3, vi == v.end(): true
```
### See also
| | |
| --- | --- |
| [ranges::next](next "cpp/iterator/ranges/next")
(C++20) | increment an iterator by a given distance or to a bound (niebloid) |
| [ranges::prev](prev "cpp/iterator/ranges/prev")
(C++20) | decrement an iterator by a given distance or to a bound (niebloid) |
| [ranges::distance](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) |
| [advance](../advance "cpp/iterator/advance") | advances an iterator by given distance (function template) |
cpp std::ranges::iter_move std::ranges::iter\_move
=======================
| Defined in header `[<iterator>](../../header/iterator "cpp/header/iterator")` | | |
| --- | --- | --- |
|
```
inline namespace /*unspecified*/ {
inline constexpr /*unspecified*/ iter_move = /*unspecified*/;
}
```
| | (since C++20) (customization point object) |
| Call signature | | |
|
```
template< class T >
requires /* see below */
constexpr decltype(auto) iter_move( T&& t ) noexcept(/* see below */);
```
| | |
Obtains an rvalue reference or a prvalue temporary from a given iterator.
A call to `ranges::iter_move` is expression-equivalent to:
1. `iter_move([std::forward](http://en.cppreference.com/w/cpp/utility/forward)<T>(t))`, if `[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<T>` is a class or enumeration type and the expression is well-formed in unevaluated context, where the [overload resolution](../../language/overload_resolution "cpp/language/overload resolution") is performed with the following candidates:
* `void iter_move();`
* any declarations of `iter_move` found by [argument-dependent lookup](../../language/adl "cpp/language/adl").
2. Otherwise, `std::move(\*[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<T>(t))` if `\*[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<T>(t)` is well-formed and is an lvalue.
3. Otherwise, `\*[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<T>(t)` if `\*[std::forward](http://en.cppreference.com/w/cpp/utility/forward)<T>(t)` is well-formed and is an rvalue.
In all other cases, a call to `ranges::iter_move` is ill-formed, which can result in [substitution failure](../../language/sfinae "cpp/language/sfinae") when `ranges::iter_move(e)` appears in the immediate context of a template instantiation.
If `ranges::iter_move(e)` is not equal to `*e`, the program is ill-formed, no diagnostic required.
### Expression-equivalent
Expression `e` is *expression-equivalent* to expression `f`, if.
* `e` and `f` have the same effects, and
* either both are [constant subexpressions](../../language/constant_expression "cpp/language/constant expression") or else neither is a constant subexpression, and
* either both are [potentially-throwing](../../language/noexcept_spec "cpp/language/noexcept spec") or else neither is potentially-throwing (i.e. `noexcept(e) == noexcept(f)`).
### Customization point objects
The name `ranges::iter_move` denotes a *customization point object*, which is a const [function object](../../named_req/functionobject "cpp/named req/FunctionObject") of a [literal](../../named_req/literaltype "cpp/named req/LiteralType") [`semiregular`](../../concepts/semiregular "cpp/concepts/semiregular") class type. For exposition purposes, the cv-unqualified version of its type is denoted as `*\_\_iter\_move\_fn*`.
All instances of `*\_\_iter\_move\_fn*` are equal. The effects of invoking different instances of type `*\_\_iter\_move\_fn*` on the same arguments are equivalent, regardless of whether the expression denoting the instance is an lvalue or rvalue, and is const-qualified or not (however, a volatile-qualified instance is not required to be invocable). Thus, `ranges::iter_move` can be copied freely and its copies can be used interchangeably.
Given a set of types `Args...`, if `[std::declval](http://en.cppreference.com/w/cpp/utility/declval)<Args>()...` meet the requirements for arguments to `ranges::iter_move` above, `*\_\_iter\_move\_fn*` models
.
* `[std::invocable](http://en.cppreference.com/w/cpp/concepts/invocable)<__iter_move_fn, Args...>`,
* `[std::invocable](http://en.cppreference.com/w/cpp/concepts/invocable)<const __iter_move_fn, Args...>`,
* `[std::invocable](http://en.cppreference.com/w/cpp/concepts/invocable)<__iter_move_fn&, Args...>`, and
* `[std::invocable](http://en.cppreference.com/w/cpp/concepts/invocable)<const __iter_move_fn&, Args...>`.
Otherwise, no function call operator of `*\_\_iter\_move\_fn*` participates in overload resolution.
### See also
| | |
| --- | --- |
| [iter\_move](../reverse_iterator/iter_move "cpp/iterator/reverse iterator/iter move")
(C++20) | casts the result of dereferencing the adjusted underlying iterator to its associated rvalue reference type (function) |
| [iter\_move](../move_iterator/iter_move "cpp/iterator/move iterator/iter move")
(C++20) | casts the result of dereferencing the underlying iterator to its associated rvalue reference type (function) |
| programming_docs |
cpp std::ranges::distance std::ranges::distance
=====================
| Defined in header `[<iterator>](../../header/iterator "cpp/header/iterator")` | | |
| --- | --- | --- |
| Call signature | | |
|
```
template< std::input_or_output_iterator I, std::sentinel_for<I> S >
requires (!std::sized_sentinel_for<S, I>)
constexpr std::iter_difference_t<I> distance( I first, S last );
```
| (1) | (since C++20) |
|
```
template< std::input_or_output_iterator I, std::sized_sentinel_for<I> S >
constexpr std::iter_difference_t<I> distance( const I& first, const S& last );
```
| (2) | (since C++20) |
|
```
template< ranges::range R >
constexpr ranges::range_difference_t<R> distance( R&& r );
```
| (3) | (since C++20) |
1,2) Returns the number of hops from `first` to `last`.
3) Returns the size of `r` as a signed integer. 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 pointing to the first element |
| last | - | sentinel denoting the end of the range `first` is an iterator to |
| r | - | range to calculate the distance of |
### Return value
1) The number of increments needed to go from `first` to `last`.
2) `last - first`.
3) If `R` models `[ranges::sized\_range](http://en.cppreference.com/w/cpp/ranges/sized_range)`, returns `[ranges::size](http://en.cppreference.com/w/cpp/ranges/size)(r)`; otherwise `ranges::distance([ranges::begin](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/begin)(r), [ranges::end](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/end)(r))`. ### Complexity
1) Linear.
2) Constant.
2) If `R` models `[ranges::sized\_range](http://en.cppreference.com/w/cpp/ranges/sized_range)` or if `[std::sized\_sentinel\_for](http://en.cppreference.com/w/cpp/iterator/sized_sentinel_for)<[ranges::sentinel\_t](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/iterator_t)<R>, [ranges::iterator\_t](http://en.cppreference.com/w/cpp/ranges-ranges-placeholder/iterator_t)<R>>` is modeled, complexity is constant; otherwise linear. ### Possible implementation
| |
| --- |
|
```
struct distance_fn {
template<std::input_or_output_iterator I, std::sentinel_for<I> S>
requires (!std::sized_sentinel_for<S, I>)
constexpr std::iter_difference_t<I> operator()(I first, S last) const
{
std::iter_difference_t<I> result = 0;
while (first != last) {
++first;
++result;
}
return result;
}
template<std::input_or_output_iterator I, std::sized_sentinel_for<I> S>
constexpr std::iter_difference_t<I> operator()(const I& first, const S& last) const
{
return last - first;
}
template<ranges::range R>
constexpr ranges::range_difference_t<R> operator()(R&& r) const
{
if constexpr (ranges::sized_range<std::remove_cvref_t<R>>) {
return static_cast<ranges::range_difference_t<R>>(ranges::size(r));
}
else {
return (*this)(ranges::begin(r), ranges::end(r));
}
}
};
inline constexpr auto distance = distance_fn{};
```
|
### Example
```
#include <iostream>
#include <iterator>
#include <vector>
int main()
{
std::vector<int> v{ 3, 1, 4 };
namespace ranges = std::ranges;
std::cout << "distance(first, last) = "
<< ranges::distance(v.begin(), v.end()) << '\n'
<< "distance(last, first) = "
<< ranges::distance(v.end(), v.begin()) << '\n'
<< "distance(v) = " << ranges::distance(v) << '\n';
}
```
Output:
```
distance(first, last) = 3
distance(last, first) = -3
distance(v) = 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 3392](https://cplusplus.github.io/LWG/issue3392) | C++20 | `distance` takes iterator by value, thus rejecting move-only iterator lvalue with a sized sentinel | by reference overload added |
### See also
| | |
| --- | --- |
| [ranges::advance](advance "cpp/iterator/ranges/advance")
(C++20) | advances an iterator by given distance or to a given bound (niebloid) |
| [ranges::countranges::count\_if](../../algorithm/ranges/count "cpp/algorithm/ranges/count")
(C++20)(C++20) | returns the number of elements satisfying specific criteria (niebloid) |
| [distance](../distance "cpp/iterator/distance") | returns the distance between two iterators (function template) |
cpp std::ranges::prev std::ranges::prev
=================
| Defined in header `[<iterator>](../../header/iterator "cpp/header/iterator")` | | |
| --- | --- | --- |
| Call signature | | |
|
```
template< std::bidirectional_iterator I >
constexpr I prev( I i );
```
| (1) | (since C++20) |
|
```
template< std::bidirectional_iterator I >
constexpr I prev( I i, std::iter_difference_t<I> n );
```
| (2) | (since C++20) |
|
```
template< std::bidirectional_iterator I >
constexpr I prev( I i, std::iter_difference_t<I> n, I bound );
```
| (3) | (since C++20) |
Return the *n*th predecessor of iterator `i`.
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
| | | |
| --- | --- | --- |
| i | - | an iterator |
| n | - | number of elements `i` should be descended |
| bound | - | iterator denoting the beginning of the range `i` points to |
### Return value
1) The predecessor of `i`
2) The *n*th predecessor of iterator `i`
3) The *n*th predecessor of iterator `i`, or the first iterator that compares equal to `bound`, whichever is first. ### Complexity
1) Constant
2,3) Constant if `I` models `[std::random\_access\_iterator](http://en.cppreference.com/w/cpp/iterator/random_access_iterator)<I>`; otherwise linear. ### Possible implementation
| |
| --- |
|
```
struct prev_fn {
template<std::bidirectional_iterator I>
constexpr I operator()(I i) const
{
--i;
return i;
}
template< std::bidirectional_iterator I >
constexpr I operator()(I i, std::iter_difference_t<I> n) const
{
ranges::advance(i, -n);
return i;
}
template<std::bidirectional_iterator I>
constexpr I operator()(I i, std::iter_difference_t<I> n, I bound) const
{
ranges::advance(i, -n, bound);
return i;
}
};
inline constexpr auto prev = prev_fn();
```
|
### Notes
Although the expression `--r.end()` often compiles for containers, it is not guaranteed to do so: `r.end()` is an rvalue expression, and there is no iterator requirement that specifies that decrement of an rvalue is guaranteed to work. In particular, when iterators are implemented as pointers or its `operator--` is lvalue-ref-qualified, `--r.end()` does not compile, while `ranges::prev(r.end())` does.
This is further exacerbated by ranges that do not model `[ranges::common\_range](http://en.cppreference.com/w/cpp/ranges/common_range)`. For example, for some underlying ranges, `ranges::transform_view::end` doesn't have the same return type as `ranges::transform_view::begin`, and so `--r.end()` won't compile. This isn't something that `ranges::prev` can aid with, but there are workarounds.
### Example
```
#include <iostream>
#include <iterator>
#include <vector>
int main()
{
std::vector<int> v{ 3, 1, 4 };
auto pv = std::ranges::prev(v.end(), 2);
std::cout << *pv << '\n';
pv = std::ranges::prev(pv, 42, v.begin());
std::cout << *pv << '\n';
}
```
Output:
```
1
3
```
### See also
| | |
| --- | --- |
| [ranges::next](next "cpp/iterator/ranges/next")
(C++20) | increment an iterator by a given distance or to a bound (niebloid) |
| [ranges::advance](advance "cpp/iterator/ranges/advance")
(C++20) | advances an iterator by given distance or to a given bound (niebloid) |
| [prev](../prev "cpp/iterator/prev")
(C++11) | decrement an iterator (function template) |
cpp std::ranges::next std::ranges::next
=================
| Defined in header `[<iterator>](../../header/iterator "cpp/header/iterator")` | | |
| --- | --- | --- |
| Call signature | | |
|
```
template< std::input_or_output_iterator I >
constexpr I next( I i );
```
| (1) | (since C++20) |
|
```
template< std::input_or_output_iterator I >
constexpr I next( I i, std::iter_difference_t<I> n );
```
| (2) | (since C++20) |
|
```
template< std::input_or_output_iterator I, std::sentinel_for<I> S >
constexpr I next( I i, S bound );
```
| (3) | (since C++20) |
|
```
template< std::input_or_output_iterator I, std::sentinel_for<I> S >
constexpr I next( I i, std::iter_difference_t<I> n, S bound );
```
| (4) | (since C++20) |
Return the *n*th successor of iterator `i`.
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
| | | |
| --- | --- | --- |
| i | - | an iterator |
| n | - | number of elements to advance |
| bound | - | sentinel denoting the end of the range `i` points to |
### Return value
1) The successor of iterator `i`
2) The *n*th successor of iterator `i`
3) The first iterator equivalent to `bound`
4) The *n*th successor of iterator `i`, or the first iterator equivalent to `bound`, whichever is first. ### Complexity
1) Constant.
2) Constant if `I` models `[std::random\_access\_iterator](../random_access_iterator "cpp/iterator/random access iterator")`; otherwise linear.
3) Constant if `I` and `S` models both `[std::random\_access\_iterator](http://en.cppreference.com/w/cpp/iterator/random_access_iterator)<I>` and `[std::sized\_sentinel\_for](http://en.cppreference.com/w/cpp/iterator/sized_sentinel_for)<S, I>`, or if `I` and `S` models `[std::assignable\_from](http://en.cppreference.com/w/cpp/concepts/assignable_from)<I&, S>`; otherwise linear.
4) Constant if `I` and `S` models both `[std::random\_access\_iterator](http://en.cppreference.com/w/cpp/iterator/random_access_iterator)<I>` and `[std::sized\_sentinel\_for](http://en.cppreference.com/w/cpp/iterator/sized_sentinel_for)<S, I>`; otherwise linear. ### Possible implementation
| |
| --- |
|
```
struct next_fn {
template<std::input_or_output_iterator I>
constexpr I operator()(I i) const
{
++i;
return i;
}
template<std::input_or_output_iterator I>
constexpr I operator()(I i, std::iter_difference_t<I> n) const
{
ranges::advance(i, n);
return i;
}
template<std::input_or_output_iterator I, std::sentinel_for<I> S>
constexpr I operator()(I i, S bound) const
{
ranges::advance(i, bound);
return i;
}
template<std::input_or_output_iterator I, std::sentinel_for<I> S>
constexpr I operator()(I i, std::iter_difference_t<I> n, S bound) const
{
ranges::advance(i, n, bound);
return i;
}
};
inline constexpr auto next = next_fn();
```
|
### Notes
Although the expression `++x.begin()` often compiles, it is not guaranteed to do so: `x.begin()` is an rvalue expression, and there is no requirement that specifies that increment of an rvalue is guaranteed to work. In particular, when iterators are implemented as pointers or its `operator++` is lvalue-ref-qualified, `++x.begin()` does not compile, while `ranges::next(x.begin())` does.
### Example
```
#include <iomanip>
#include <iostream>
#include <iterator>
#include <vector>
int main()
{
std::cout << std::boolalpha;
std::vector<int> v{ 3, 1, 4 };
{
auto n = std::ranges::next(v.begin());
std::cout << *n << '\n';
}
{
auto n = std::ranges::next(v.begin(), 2);
std::cout << *n << '\n';
}
{
auto n = std::ranges::next(v.begin(), v.end());
std::cout << (n == v.end()) << '\n';
}
{
auto n = std::ranges::next(v.begin(), 42, v.end());
std::cout << (n == v.end()) << '\n';
}
}
```
Output:
```
1
4
true
true
```
### See also
| | |
| --- | --- |
| [ranges::prev](prev "cpp/iterator/ranges/prev")
(C++20) | decrement an iterator by a given distance or to a bound (niebloid) |
| [ranges::advance](advance "cpp/iterator/ranges/advance")
(C++20) | advances an iterator by given distance or to a given bound (niebloid) |
| [next](../next "cpp/iterator/next")
(C++11) | increment an iterator (function template) |
cpp std::ranges::iter_swap std::ranges::iter\_swap
=======================
| Defined in header `[<iterator>](../../header/iterator "cpp/header/iterator")` | | |
| --- | --- | --- |
|
```
namespace ranges {
inline namespace /*unspecified*/ {
inline constexpr /*unspecified*/ iter_swap = /*unspecified*/;
}
}
```
| | (since C++20) (customization point object) |
| Call signature | | |
|
```
template< class I1, class I2 >
constexpr void iter_swap( I1&& i1, I2&& i2 ) noexcept(/* see below */);
```
| | (since C++20) |
Swaps values denoted by two iterators.
`ranges::iter_swap(i1, i2` is expression-equivalent to:
1. `(void)iter_swap(i1, i2)`, if `[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<I1>` or `[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<I2>` is a class or enumeration type and the expression is well-formed, where the [overload resolution](../../language/overload_resolution "cpp/language/overload resolution") is performed within namespace `std::ranges` with the additional candidate:
* `void iter_swap(auto, auto) = delete;` If the selected overload does not exchange the value denoted by `i1` and `i2`, the program is ill-formed, no diagnostic required.
2. Otherwise, `[ranges::swap](http://en.cppreference.com/w/cpp/ranges-utility-placeholder/swap)(\*i1, \*i2)` if both `I1` and `I2` model [`indirectly_readable`](../indirectly_readable "cpp/iterator/indirectly readable") and if `[std::iter\_reference\_t](http://en.cppreference.com/w/cpp/iterator/iter_t)<I1>` and `[std::iter\_reference\_t](http://en.cppreference.com/w/cpp/iterator/iter_t)<I2>` model [`swappable_with`](../../concepts/swappable "cpp/concepts/swappable").
3. Otherwise, `(void)(*i1 = /*iter_exchange_move*/(i2, i1))`, if `[std::indirectly\_movable\_storable](http://en.cppreference.com/w/cpp/iterator/indirectly_movable_storable)<I1, I2>` and `[std::indirectly\_movable\_storable](http://en.cppreference.com/w/cpp/iterator/indirectly_movable_storable)<I2, I1>`, where `*iter\_exchange\_move*` is an exposition-only function template described below (and `i1` is only evaluated once).
4. Otherwise, `ranges::iter_swap(i1, i2)` is ill-formed, which can result in [substitution failure](../../language/sfinae "cpp/language/sfinae") when `ranges::iter_swap(e1, e2)` appears in the immediate context of a template instantiation.
The exposition-only function template `*iter\_exchange\_move*` is defined the equivalent of:
```
template<class X, class Y>
constexpr std::iter_value_t<X> /*iter_exchange_move*/(X&& x, Y&& y)
noexcept(noexcept(std::iter_value_t<X>(std::ranges::iter_move(x)) &&
noexcept(*x = std::ranges::iter_move(y))))
{
std::iter_value_t<X> old(std::ranges::iter_move(x));
*x = std::ranges::iter_move(y);
return old;
}
```
### Expression-equivalent
Expression `e` is *expression-equivalent* to expression `f`, if.
* `e` and `f` have the same effects, and
* either both are [constant subexpressions](../../language/constant_expression "cpp/language/constant expression") or else neither is a constant subexpression, and
* either both are [potentially-throwing](../../language/noexcept_spec "cpp/language/noexcept spec") or else neither is potentially-throwing (i.e. `noexcept(e) == noexcept(f)`).
### Customization point objects
The name `ranges::iter_swap` denotes a *customization point object*, which is a const [function object](../../named_req/functionobject "cpp/named req/FunctionObject") of a [literal](../../named_req/literaltype "cpp/named req/LiteralType") [`semiregular`](../../concepts/semiregular "cpp/concepts/semiregular") class type. For exposition purposes, the cv-unqualified version of its type is denoted as `*\_\_iter\_swap\_fn*`.
All instances of `*\_\_iter\_swap\_fn*` are equal. The effects of invoking different instances of type `*\_\_iter\_swap\_fn*` on the same arguments are equivalent, regardless of whether the expression denoting the instance is an lvalue or rvalue, and is const-qualified or not (however, a volatile-qualified instance is not required to be invocable). Thus, `ranges::iter_swap` can be copied freely and its copies can be used interchangeably.
Given a set of types `Args...`, if `[std::declval](http://en.cppreference.com/w/cpp/utility/declval)<Args>()...` meet the requirements for arguments to `ranges::iter_swap` above, `*\_\_iter\_swap\_fn*` models
.
* `[std::invocable](http://en.cppreference.com/w/cpp/concepts/invocable)<__iter_swap_fn, Args...>`,
* `[std::invocable](http://en.cppreference.com/w/cpp/concepts/invocable)<const __iter_swap_fn, Args...>`,
* `[std::invocable](http://en.cppreference.com/w/cpp/concepts/invocable)<__iter_swap_fn&, Args...>`, and
* `[std::invocable](http://en.cppreference.com/w/cpp/concepts/invocable)<const __iter_swap_fn&, Args...>`.
Otherwise, no function call operator of `*\_\_iter\_swap\_fn*` participates in overload resolution.
### See also
| | |
| --- | --- |
| [iter\_swap](../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](../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](../../algorithm/iter_swap "cpp/algorithm/iter swap") | swaps the elements pointed to by two iterators (function template) |
cpp std::insert_iterator<Container>::operator++ std::insert\_iterator<Container>::operator++
============================================
| | | |
| --- | --- | --- |
|
```
insert_iterator& operator++();
```
| | (until C++20) |
|
```
constexpr insert_iterator& operator++();
```
| | (since C++20) |
|
```
insert_iterator& operator++( int );
```
| | (until C++20) |
|
```
constexpr insert_iterator& operator++( int );
```
| | (since C++20) |
Does nothing. These operator overloads are provided to satisfy the requirements of [LegacyOutputIterator](../../named_req/outputiterator "cpp/named req/OutputIterator"). They make it possible for the expressions `*iter++=value` and `*++iter=value` to be used to output (insert) a value into the underlying container.
### Parameters
(none).
### Return value
`*this`.
| programming_docs |
cpp std::insert_iterator<Container>::operator* std::insert\_iterator<Container>::operator\*
============================================
| | | |
| --- | --- | --- |
|
```
insert_iterator& operator*();
```
| | (until C++20) |
|
```
constexpr insert_iterator& operator*();
```
| | (since C++20) |
Does nothing, this member function is provided to satisfy the requirements of [LegacyOutputIterator](../../named_req/outputiterator "cpp/named req/OutputIterator").
It returns the iterator itself, which makes it possible to use code such as `*iter = value` to output (insert) the value into the underlying container.
### Parameters
(none).
### Return value
`*this`.
cpp std::insert_iterator<Container>::operator= std::insert\_iterator<Container>::operator=
===========================================
| | | |
| --- | --- | --- |
| | (1) | |
|
```
insert_iterator<Container>&
operator=( typename Container::const_reference value );
```
| (until C++11) |
|
```
insert_iterator<Container>&
operator=( const typename Container::value_type& value );
```
| (since C++11) (until C++20) |
|
```
constexpr insert_iterator<Container>&
operator=( const typename Container::value_type& value );
```
| (since C++20) |
| | (2) | |
|
```
insert_iterator<Container>&
operator=( typename Container::value_type&& value );
```
| (since C++11) (until C++20) |
|
```
constexpr insert_iterator<Container>&
operator=( typename Container::value_type&& value );
```
| (since C++20) |
Inserts the given value `value` to the container.
1) Results in `iter = container->insert(iter, value); ++iter;`
2) Results in `iter = container->insert(iter, std::move(value)); ++iter;`
### Parameters
| | | |
| --- | --- | --- |
| value | - | the value to insert |
### Return value
`*this`.
### Notes
This function exploits the signature compatibility between hinted insert for associative containers (such as `[std::set::insert](../../container/set/insert "cpp/container/set/insert")`) and positional insert for sequential containers (such as `[std::vector::insert](../../container/vector/insert "cpp/container/vector/insert")`).
### Example
```
#include <iostream>
#include <iterator>
#include <deque>
int main()
{
std::deque<int> q;
std::insert_iterator< std::deque<int> > it(q, q.begin());
for (int i=0; i<10; ++i)
it = i; // inserts i
for (auto& elem : q) std::cout << elem << ' ';
}
```
Output:
```
0 1 2 3 4 5 6 7 8 9
```
cpp std::insert_iterator<Container>::insert_iterator std::insert\_iterator<Container>::insert\_iterator
==================================================
| | | |
| --- | --- | --- |
|
```
insert_iterator( Container& c, typename Container::iterator i );
```
| | (until C++20) |
|
```
constexpr insert_iterator( Container& c, ranges::iterator_t<Container> i );
```
| | (since C++20) |
Initializes the underlying pointer to the container to `[std::addressof](http://en.cppreference.com/w/cpp/memory/addressof)(c)` and the underlying iterator to `i`.
### Parameters
| | | |
| --- | --- | --- |
| c | - | container to initialize the inserter with |
| i | - | iterator to initialize the inserter with |
### 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 | default constructor was provided as C++20 iteratorsmust be [`default_initializable`](../../concepts/default_initializable "cpp/concepts/default initializable") | removed along with the requirement |
cpp std::ostreambuf_iterator<CharT,Traits>::failed std::ostreambuf\_iterator<CharT,Traits>::failed
===============================================
| | | |
| --- | --- | --- |
|
```
bool failed() const throw();
```
| | (until C++11) |
|
```
bool failed() const noexcept;
```
| | (since C++11) |
Returns `true` if the iterator encountered the end-of-file condition, that is, if an earlier call to `[std::basic\_streambuf::sputc](../../io/basic_streambuf/sputc "cpp/io/basic streambuf/sputc")` (made by [`operator=`](operator= "cpp/iterator/ostreambuf iterator/operator=")) returned `Traits::eof`.
### Parameters
(none).
### Return value
`true` if this iterator has encountered the end-of-file condition on output, `false` otherwise.
### Example
cpp std::ostreambuf_iterator<CharT,Traits>::operator* std::ostreambuf\_iterator<CharT,Traits>::operator\*
===================================================
| | | |
| --- | --- | --- |
|
```
ostreambuf_iterator& operator*();
```
| | |
Does nothing, this member function is provided to satisfy the requirements of [LegacyOutputIterator](../../named_req/outputiterator "cpp/named req/OutputIterator").
It returns the iterator itself, which makes it possible to use code such as `*iter = value` to output (insert) the value into the underlying stream.
### Parameters
(none).
### Return value
`*this`.
cpp std::ostreambuf_iterator<CharT,Traits>::operator= std::ostreambuf\_iterator<CharT,Traits>::operator=
==================================================
| | | |
| --- | --- | --- |
|
```
ostreambuf_iterator& operator=( CharT c );
```
| | |
If `failed()` returns `false`, inserts the character `c` into the associated stream buffer by calling `pbuf->sputc(c)`, where `pbuf` is the private member of type `streambuf_type*`. Otherwise, does nothing.
If the call to `pbuf->sputc(c)` returns `Traits::eof`, sets the failed() flag to true.
### Parameters
| | | |
| --- | --- | --- |
| c | - | the character to insert |
### Return value
`*this`.
### Example
### See also
| | |
| --- | --- |
| [sputc](../../io/basic_streambuf/sputc "cpp/io/basic streambuf/sputc") | writes one character to the put area and advances the next pointer (public member function of `std::basic_streambuf<CharT,Traits>`) |
cpp std::ostreambuf_iterator<CharT,Traits>::operator++ std::ostreambuf\_iterator<CharT,Traits>::operator++
===================================================
| | | |
| --- | --- | --- |
|
```
ostreambuf_iterator& operator++();
```
| | |
|
```
ostreambuf_iterator& operator++( int );
```
| | |
Does nothing. These operator overloads are provided to satisfy the requirements of [LegacyOutputIterator](../../named_req/outputiterator "cpp/named req/OutputIterator"). They make it possible for the expressions `*iter++=value` and `*++iter=value` to be used to output (insert) a value into the underlying stream.
### Parameters
(none).
### Return value
`*this`.
cpp std::ostreambuf_iterator<CharT,Traits>::ostreambuf_iterator std::ostreambuf\_iterator<CharT,Traits>::ostreambuf\_iterator
=============================================================
| | | |
| --- | --- | --- |
| | (1) | |
|
```
ostreambuf_iterator( streambuf_type* buffer ) throw();
```
| (until C++11) |
|
```
ostreambuf_iterator( streambuf_type* buffer ) noexcept;
```
| (since C++11) |
| | (2) | |
|
```
ostreambuf_iterator( ostream_type& stream ) throw();
```
| (until C++11) |
|
```
ostreambuf_iterator( ostream_type& stream ) noexcept;
```
| (since C++11) |
1) Constructs the iterator with the private `streambuf_type*` member set to `buffer` and the [`failed()`](failed "cpp/iterator/ostreambuf iterator/failed") flag set to `false`. The behavior is undefined if `buffer` is a null pointer.
2) Same as `ostreambuf_iterator(stream.rdbuf())`. ### Parameters
| | | |
| --- | --- | --- |
| stream | - | the output stream whose `rdbuf()` will be accessed by this iterator |
| buffer | - | the output stream buffer to be accessed by this iterator |
### Example
```
#include <fstream>
#include <iostream>
#include <iterator>
int main()
{
const char* file = "test.txt";
{
std::basic_filebuf<char> f;
f.open(file, std::ios::out);
std::ostreambuf_iterator<char> out1(&f);
*out1 = 'a'; // writes to file via iterator
}
// read back from the file
char a;
std::cout << ((std::ifstream{file} >> a), a) << std::endl;
std::ostreambuf_iterator<wchar_t> out2{std::wcout};
*out2 = L'b';
}
```
Output:
```
a
b
```
### 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 112](https://cplusplus.github.io/LWG/issue112) | C++98 | the requirement "the argument cannotbe null" was applied to overload (2) | applies to overload(1) instead |
| [P2325R3](https://wg21.link/P2325R3) | C++20 | default constructor was provided as C++20iterators must be [`default_initializable`](../../concepts/default_initializable "cpp/concepts/default initializable") | removed along withthe requirement |
cpp operator-(std::reverse_iterator)
operator-(std::reverse\_iterator)
=================================
| | | |
| --- | --- | --- |
|
```
template< class Iterator >
typename reverse_iterator<Iterator>::difference_type
operator-( const reverse_iterator<Iterator>& lhs,
const reverse_iterator<Iterator>& rhs );
```
| | (until C++11) |
|
```
template< class Iterator1, class Iterator2 >
auto operator-( const reverse_iterator<Iterator1>& lhs,
const reverse_iterator<Iterator2>& rhs
) -> decltype(rhs.base() - lhs.base());
```
| | (since C++11) (until C++17) |
|
```
template< class Iterator1, class Iterator2 >
constexpr auto operator-( const reverse_iterator<Iterator1>& lhs,
const reverse_iterator<Iterator2>& rhs
) -> decltype(rhs.base() - lhs.base());
```
| | (since C++17) |
Returns the distance between two iterator adaptors.
### Parameters
| | | |
| --- | --- | --- |
| lhs, rhs | - | iterator adaptors to compute the difference of |
### Return value
`rhs.base() - lhs.base()`.
### Example
```
#include <iostream>
#include <iterator>
#include <list>
#include <vector>
int main()
{
{
std::vector v {0, 1, 2, 3};
std::reverse_iterator<std::vector<int>::iterator>
ri1 { std::reverse_iterator{ v.rbegin() } },
ri2 { std::reverse_iterator{ v.rend() } };
std::cout << (ri2 - ri1) << ' '; // 4
std::cout << (ri1 - ri2) << '\n'; // -4
}
{
std::list l {5, 6, 7, 8};
std::reverse_iterator<std::list<int>::iterator>
ri1{ std::reverse_iterator{ l.rbegin() } },
ri2{ std::reverse_iterator{ l.rend() } };
// auto n = (ri1 - ri2); // error: the underlying iterators do not
// model the random access iterators
}
}
```
Output:
```
4 -4
```
### See also
| | |
| --- | --- |
| [operator++operator++(int)operator+=operator+operator--operator--(int)operator-=operator-](operator_arith "cpp/iterator/reverse iterator/operator arith") | advances or decrements the iterator (public member function) |
| [operator+](operator_plus_ "cpp/iterator/reverse iterator/operator+") | advances the iterator (function template) |
cpp std::reverse_iterator<Iter>::base std::reverse\_iterator<Iter>::base
==================================
| | | |
| --- | --- | --- |
|
```
iterator_type base() const;
```
| | (until C++17) |
|
```
constexpr iterator_type base() const;
```
| | (since C++17) |
Returns the underlying base iterator. That is `[std::reverse\_iterator](http://en.cppreference.com/w/cpp/iterator/reverse_iterator)(it).base() == it`.
The base iterator refers to the element that is next (from the `std::reverse_iterator::iterator_type` perspective) to the element the `reverse_iterator` is currently pointing to. That is `&*(rit.base() - 1) == &*rit`.
### Parameters
(none).
### Return value
The underlying iterator.
### Exceptions
May throw implementation-defined exceptions.
### Example
```
#include <iostream>
#include <iterator>
#include <vector>
int main()
{
std::vector<int> v = { 0, 1, 2, 3, 4, 5 };
using RevIt = std::reverse_iterator<std::vector<int>::iterator>;
const auto it = v.begin() + 3;
RevIt r_it{it};
std::cout << "*it == " << *it << '\n'
<< "*r_it == " << *r_it << '\n'
<< "*r_it.base() == " << *r_it.base() << '\n'
<< "*(r_it.base()-1) == " << *(r_it.base() - 1) << '\n';
RevIt r_end{v.begin()};
RevIt r_begin{v.end()};
for (auto it = r_end.base(); it != r_begin.base(); ++it) {
std::cout << *it << ' ';
}
std::cout << '\n';
for (auto it = r_begin; it != r_end; ++it) {
std::cout << *it << ' ';
}
std::cout << '\n';
}
```
Output:
```
*it == 3
*r_it == 2
*r_it.base() == 3
*(r_it.base()-1) == 2
0 1 2 3 4 5
5 4 3 2 1 0
```
### See also
| | |
| --- | --- |
| [operator\*operator->](operator* "cpp/iterator/reverse iterator/operator*") | accesses the pointed-to element (public member function) |
cpp std::iter_move(std::reverse_iterator)
std::iter\_move(std::reverse\_iterator)
=======================================
| | | |
| --- | --- | --- |
|
```
friend constexpr std::iter_rvalue_reference_t<Iter>
iter_move( const std::reverse_iterator& i ) noexcept(/* see below */);
```
| | (since C++20) |
Casts the result of dereferencing the adjusted underlying iterator to its associated rvalue reference type.
The function body is equivalent to:
```
auto tmp = i.base();
return std::ranges::iter_move(--tmp);
```
This function template is not visible to ordinary [unqualified](../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../language/adl "cpp/language/adl") when `std::reverse_iterator<Iter>` is an associated class of the arguments.
### Parameters
| | | |
| --- | --- | --- |
| i | - | a source reverse iterator. |
### Return value
An rvalue reference or a prvalue temporary.
### Complexity
Constant.
### Exceptions
[`noexcept`](../../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept(
[std::is\_nothrow\_copy\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_copy_constructible)<Iter> &&
noexcept(std::[ranges::iter\_move](http://en.cppreference.com/w/cpp/iterator/ranges/iter_move)(--[std::declval](http://en.cppreference.com/w/cpp/utility/declval)<Iter&>()))
.
)`
### Example
```
#include <iomanip>
#include <iostream>
#include <iterator>
#include <string>
#include <vector>
void print(auto const& rem, auto const& v) {
for (std::cout << rem << "[" << size(v) << "] { "; auto const& s : v)
std::cout << quoted(s) << " ";
std::cout << "}\n";
}
int main()
{
std::vector<std::string> p { "Alpha", "Bravo", "Charlie" }, q;
print("p", p), print("q", q);
using RI = std::reverse_iterator<std::vector<std::string>::iterator>;
for (RI iter{ p.rbegin() }, rend{ p.rend() }; iter != rend; ++iter) {
q.emplace_back( /* ADL */ iter_move(iter) );
}
print("p", p), print("q", q);
}
```
Possible output:
```
p[3] { "Alpha" "Bravo" "Charlie" }
q[0] { }
p[3] { "" "" "" }
q[3] { "Charlie" "Bravo" "Alpha" }
```
### See also
| | |
| --- | --- |
| [iter\_move](../ranges/iter_move "cpp/iterator/ranges/iter move")
(C++20) | casts the result of dereferencing an object to its associated rvalue reference type (customization point object) |
| [iter\_move](../move_iterator/iter_move "cpp/iterator/move iterator/iter move")
(C++20) | casts the result of dereferencing the underlying iterator to its associated rvalue reference type (function) |
| [move](../../utility/move "cpp/utility/move")
(C++11) | obtains an rvalue reference (function template) |
| [move\_if\_noexcept](../../utility/move_if_noexcept "cpp/utility/move if noexcept")
(C++11) | obtains an rvalue reference if the move constructor does not throw (function template) |
| [forward](../../utility/forward "cpp/utility/forward")
(C++11) | forwards a function argument (function template) |
| [ranges::move](../../algorithm/ranges/move "cpp/algorithm/ranges/move")
(C++20) | moves a range of elements to a new location (niebloid) |
| [ranges::move\_backward](../../algorithm/ranges/move_backward "cpp/algorithm/ranges/move backward")
(C++20) | moves a range of elements to a new location in backwards order (niebloid) |
cpp std::reverse_iterator<Iter>::operator[] std::reverse\_iterator<Iter>::operator[]
========================================
| | | |
| --- | --- | --- |
|
```
/*unspecified*/ operator[]( difference_type n ) const;
```
| | (until C++17) |
|
```
constexpr /*unspecified*/ operator[]( difference_type n ) const;
```
| | (since C++17) |
Returns a reference to the element at specified relative location.
### Parameters
| | | |
| --- | --- | --- |
| n | - | position relative to current location. |
### Return value
A reference to the element at relative location, that is, `base()[-n-1]`.
### Example
```
#include <array>
#include <cstddef>
#include <iostream>
#include <iterator>
#include <list>
#include <vector>
int main()
{
{
int a[]{0, 1, 2, 3};
std::reverse_iterator<int*> iter{std::rbegin(a)};
for (std::size_t i{}; i != std::size(a); ++i)
std::cout << iter[i] << ' '; // decltype(iter[i]) is `int&`
std::cout << '\n';
}
{
std::vector v{0, 1, 2, 3};
std::reverse_iterator<std::vector<int>::iterator> iter{std::rbegin(v)};
for (std::size_t i{}; i != std::size(v); ++i)
std::cout << iter[i] << ' '; // decltype(iter[i]) is `int&`
std::cout << '\n';
}
{
// constexpr context
constexpr static std::array<int, 4> z{0, 1, 2, 3};
constexpr std::reverse_iterator<decltype(z)::const_iterator> it{std::crbegin(z)};
static_assert(it[1] == 2);
}
{
std::list li{0, 1, 2, 3};
std::reverse_iterator<std::list<int>::iterator> iter{std::rbegin(li)};
*iter = 42; // OK
// iter[0] = 13; // compilation error ~ the underlying iterator
// does not model the random access iterator
}
}
```
Output:
```
3 2 1 0
3 2 1 0
```
### See also
| | |
| --- | --- |
| [operator\*operator->](operator* "cpp/iterator/reverse iterator/operator*") | accesses the pointed-to element (public member function) |
cpp std::reverse_iterator<Iter>::operator*,-> std::reverse\_iterator<Iter>::operator\*,->
===========================================
| | | |
| --- | --- | --- |
| | (1) | |
|
```
reference operator*() const;
```
| (until C++17) |
|
```
constexpr reference operator*() const;
```
| (since C++17) |
| | (2) | |
|
```
pointer operator->() const;
```
| (until C++17) |
|
```
constexpr pointer operator->() const;
```
| (since C++17) (until C++20) |
|
```
constexpr pointer operator->() const
requires (std::is_pointer_v<Iter> ||
requires (const Iter i) { i.operator->(); });
```
| (since C++20) |
Returns a reference or pointer to the element previous to `current`.
1) Equivalent to `Iter tmp = current; return *--tmp;`
| | |
| --- | --- |
| 2) Equivalent to `return [std::addressof](http://en.cppreference.com/w/cpp/memory/addressof)(operator\*());`. | (until C++20) |
| 2) Equivalent to `return current - 1;` if `Iter` is a pointer type. Otherwise, equivalent to `return [std::prev](http://en.cppreference.com/w/cpp/iterator/prev)(current).operator->();`. | (since C++20) |
### Parameters
(none).
### Return value
Reference or pointer to the element previous to `current`.
### Example
```
#include <complex>
#include <iostream>
#include <iterator>
#include <vector>
int main()
{
using RI0 = std::reverse_iterator<int*>;
int a[] { 0, 1, 2, 3 };
RI0 r0 { std::rbegin(a) };
std::cout << "*r0 = " << *r0 << '\n';
*r0 = 42;
std::cout << "a[3] = " << a[3] << '\n';
using RI1 = std::reverse_iterator<std::vector<int>::iterator>;
std::vector<int> vi { 0, 1, 2, 3 };
RI1 r1 { vi.rend() - 2 };
std::cout << "*r1 = " << *r1 << '\n';
using RI2 = std::reverse_iterator<std::vector<std::complex<double>>::iterator>;
std::vector<std::complex<double>> vc { {1,2}, {3,4}, {5,6}, {7,8} };
RI2 r2 { vc.rbegin() + 1 };
std::cout << "vc[2] = " << "(" << r2->real() << "," << r2->imag() << ")\n";
}
```
Output:
```
*r0 = 3
a[3] = 42
*r1 = 1
vc[2] = (5,6)
```
### See also
| | |
| --- | --- |
| [operator[]](operator_at "cpp/iterator/reverse iterator/operator at") | accesses an element by index (public member function) |
| programming_docs |
cpp operator+(std::reverse_iterator)
operator+(std::reverse\_iterator)
=================================
| Defined in header `[<iterator>](../../header/iterator "cpp/header/iterator")` | | |
| --- | --- | --- |
|
```
template< class Iter >
reverse_iterator<Iter>
operator+( typename reverse_iterator<Iter>::difference_type n,
const reverse_iterator<Iter>& it );
```
| | (until C++17) |
|
```
template< class Iter >
constexpr reverse_iterator<Iter>
operator+( typename reverse_iterator<Iter>::difference_type n,
const reverse_iterator<Iter>& it );
```
| | (since C++17) |
Returns the iterator `it` incremented by `n`.
### Parameters
| | | |
| --- | --- | --- |
| n | - | the number of positions to increment the iterator |
| it | - | the iterator adaptor to increment |
### Return value
The incremented iterator, that is `reverse_iterator<Iter>(it.base() - n)`.
### Example
```
#include <iostream>
#include <iterator>
#include <list>
#include <vector>
int main()
{
{
std::vector v {0, 1, 2, 3};
std::reverse_iterator<std::vector<int>::iterator>
ri1 { std::reverse_iterator{ v.rbegin() } };
std::cout << *ri1 << ' '; // 3
std::reverse_iterator<std::vector<int>::iterator> ri2 { 2 + ri1 };
std::cout << *ri2 << ' '; // 1
}
{
std::list l {5, 6, 7, 8};
std::reverse_iterator<std::list<int>::iterator>
ri1{ std::reverse_iterator{ l.rbegin() } };
std::cout << *ri1 << '\n'; // 8
// auto ri2 { 2 + ri1 }; // error: the underlying iterator does
// not model the random access iterator
}
}
```
Output:
```
3 1 8
```
### See also
| | |
| --- | --- |
| [operator++operator++(int)operator+=operator+operator--operator--(int)operator-=operator-](operator_arith "cpp/iterator/reverse iterator/operator arith") | advances or decrements the iterator (public member function) |
| [operator-](operator- "cpp/iterator/reverse iterator/operator-") | computes the distance between two iterator adaptors (function template) |
cpp std::reverse_iterator<Iter>::operator= std::reverse\_iterator<Iter>::operator=
=======================================
| | | |
| --- | --- | --- |
|
```
template< class U >
reverse_iterator& operator=( const reverse_iterator<U>& other );
```
| | (until C++17) |
|
```
template< class U >
constexpr reverse_iterator& operator=( const reverse_iterator<U>& other );
```
| | (since C++17) |
The underlying iterator is assigned the value of the underlying iterator of `other`, i.e. `other.base()`.
| | |
| --- | --- |
| This overload participates in overload resolution only if `U` is not the same type as `Iter` and `[std::convertible\_to](http://en.cppreference.com/w/cpp/concepts/convertible_to)<const U&, Iter>` and `[std::assignable\_from](http://en.cppreference.com/w/cpp/concepts/assignable_from)<Iter&, const U&>` are modeled. | (since C++20) |
### Parameters
| | | |
| --- | --- | --- |
| other | - | iterator adaptor to assign |
### Return value
`*this`.
### Example
```
#include <iostream>
#include <iterator>
int main()
{
const int a1[] {0, 1, 2};
int a2[] {0, 1, 2, 3};
short a3[] {40, 41, 42};
std::reverse_iterator<const int*> it1{ std::crbegin(a1) };
it1 = std::reverse_iterator<int*>{ std::rbegin(a2) }; // OK
// it1 = std::reverse_iterator<short*>{ std::rbegin(a3) }; // compilation error:
// incompatible pointer types
std::reverse_iterator<short const*> it2{ nullptr };
it2 = std::rbegin(a3); // OK
// it2 = std::begin(a3); // compilation error: no viable overloaded '='
std::cout << *it2 << '\n';
}
```
Output:
```
42
```
### 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 3435](https://cplusplus.github.io/LWG/issue3435) | C++20 | the converting assignment operator was not constrained | constrained |
### See also
| | |
| --- | --- |
| [(constructor)](reverse_iterator "cpp/iterator/reverse iterator/reverse iterator") | constructs a new iterator adaptor (public member function) |
cpp std::iter_swap(std::reverse_iterator)
std::iter\_swap(std::reverse\_iterator)
=======================================
| | | |
| --- | --- | --- |
|
```
template< std::indirectly_swappable<Iter> Iter2 >
friend constexpr void
iter_swap( const reverse_iterator& x,
const std::reverse_iterator<Iter2>& y ) noexcept(/*see below*/);
```
| | (since C++20) |
Swaps the objects pointed to by two adjusted underlying iterators. The function body is equivalent to:
```
auto tmp_x = x.base();
auto tmp_y = y.base();
ranges::iter_swap(--tmp_x, --tmp_y);
```
This function template is not visible to ordinary [unqualified](../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../language/adl "cpp/language/adl") when `std::reverse_iterator<Iter>` is an associated class of the arguments.
### Parameters
| | | |
| --- | --- | --- |
| x, y | - | reverse iterators to the elements to swap |
### Return value
(none).
### Complexity
Constant.
### Exceptions
[`noexcept`](../../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept(
[std::is\_nothrow\_copy\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_copy_constructible)<Iter> &&
[std::is\_nothrow\_copy\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_copy_constructible)<Iter2> &&
noexcept([ranges::iter\_swap](http://en.cppreference.com/w/cpp/iterator/ranges/iter_swap)(--[std::declval](http://en.cppreference.com/w/cpp/utility/declval)<Iter&>(), --[std::declval](http://en.cppreference.com/w/cpp/utility/declval)<Iter2&>()))
.
)`
### Example
```
#include <iostream>
#include <iterator>
#include <list>
#include <vector>
int main()
{
std::vector v {1, 2, 3};
std::list l {4, 5, 6};
std::reverse_iterator<std::vector<int>::iterator> r1 { v.rbegin() };
std::reverse_iterator<std::list<int>::iterator> r2 { l.rbegin() };
std::cout << *r1 << ' ' << *r2 << '\n';
iter_swap(r1, r2); // ADL
std::cout << *r1 << ' ' << *r2 << '\n';
}
```
Output:
```
3 6
6 3
```
### See also
| | |
| --- | --- |
| [swap](../../algorithm/swap "cpp/algorithm/swap") | swaps the values of two objects (function template) |
| [swap\_ranges](../../algorithm/swap_ranges "cpp/algorithm/swap ranges") | swaps two ranges of elements (function template) |
| [iter\_swap](../../algorithm/iter_swap "cpp/algorithm/iter swap") | swaps the elements pointed to by two iterators (function template) |
| [iter\_swap](../ranges/iter_swap "cpp/iterator/ranges/iter swap")
(C++20) | swaps the values referenced by two dereferenceable objects (customization point object) |
| [iter\_swap](../move_iterator/iter_swap "cpp/iterator/move iterator/iter swap")
(C++20) | swaps the objects pointed to by two underlying iterators (function template) |
cpp std::reverse_iterator<Iter>::reverse_iterator std::reverse\_iterator<Iter>::reverse\_iterator
===============================================
| | | |
| --- | --- | --- |
| | (1) | |
|
```
reverse_iterator();
```
| (until C++17) |
|
```
constexpr reverse_iterator();
```
| (since C++17) |
| | (2) | |
|
```
explicit reverse_iterator( iterator_type x );
```
| (until C++17) |
|
```
constexpr explicit reverse_iterator( iterator_type x );
```
| (since C++17) |
| | (3) | |
|
```
template< class U >
reverse_iterator( const reverse_iterator<U>& other );
```
| (until C++17) |
|
```
template< class U >
constexpr reverse_iterator( const reverse_iterator<U>& other );
```
| (since C++17) |
Constructs a new iterator adaptor.
1) Default constructor. The underlying iterator is value-initialized. Operations on the resulting iterator have defined behavior if and only if the corresponding operations on a value-initialized `Iter` also have defined behavior.
2) The underlying iterator is initialized with `x`.
3) The underlying iterator is initialized with that of `other`. This overload participates in overload resolution only if `U` is not the same type as `Iter` and `[std::convertible\_to](http://en.cppreference.com/w/cpp/concepts/convertible_to)<const U&, Iter>` is modeled (since C++20). ### Parameters
| | | |
| --- | --- | --- |
| x | - | iterator to adapt |
| other | - | iterator adaptor to copy |
### 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 3435](https://cplusplus.github.io/LWG/issue3435) | C++20 | the converting constructor from another `reverse_iterator` was not constrained | constrained |
### See also
| | |
| --- | --- |
| [operator=](operator= "cpp/iterator/reverse iterator/operator=") | assigns another iterator adaptor (public member function) |
| [make\_reverse\_iterator](../make_reverse_iterator "cpp/iterator/make reverse iterator")
(C++14) | creates a `[std::reverse\_iterator](../reverse_iterator "cpp/iterator/reverse iterator")` of type inferred from the argument (function template) |
cpp operator==,!=,<,<=,>,>=,<=>(std::reverse_iterator)
operator==,!=,<,<=,>,>=,<=>(std::reverse\_iterator)
===================================================
| | | |
| --- | --- | --- |
| | (1) | |
|
```
template< class Iterator1, class Iterator2 >
bool operator==( const std::reverse_iterator<Iterator1>& lhs,
const std::reverse_iterator<Iterator2>& rhs );
```
| (until C++17) |
|
```
template< class Iterator1, class Iterator2 >
constexpr bool operator==( const std::reverse_iterator<Iterator1>& lhs,
const std::reverse_iterator<Iterator2>& rhs );
```
| (since C++17) |
| | (2) | |
|
```
template< class Iterator1, class Iterator2 >
bool operator!=( const std::reverse_iterator<Iterator1>& lhs,
const std::reverse_iterator<Iterator2>& rhs );
```
| (until C++17) |
|
```
template< class Iterator1, class Iterator2 >
constexpr bool operator!=( const std::reverse_iterator<Iterator1>& lhs,
const std::reverse_iterator<Iterator2>& rhs );
```
| (since C++17) |
| | (3) | |
|
```
template< class Iterator1, class Iterator2 >
bool operator<( const std::reverse_iterator<Iterator1>& lhs,
const std::reverse_iterator<Iterator2>& rhs );
```
| (until C++17) |
|
```
template< class Iterator1, class Iterator2 >
constexpr bool operator<( const std::reverse_iterator<Iterator1>& lhs,
const std::reverse_iterator<Iterator2>& rhs );
```
| (since C++17) |
| | (4) | |
|
```
template< class Iterator1, class Iterator2 >
bool operator<=( const std::reverse_iterator<Iterator1>& lhs,
const std::reverse_iterator<Iterator2>& rhs );
```
| (until C++17) |
|
```
template< class Iterator1, class Iterator2 >
constexpr bool operator<=( const std::reverse_iterator<Iterator1>& lhs,
const std::reverse_iterator<Iterator2>& rhs );
```
| (since C++17) |
| | (5) | |
|
```
template< class Iterator1, class Iterator2 >
bool operator>( const std::reverse_iterator<Iterator1>& lhs,
const std::reverse_iterator<Iterator2>& rhs );
```
| (until C++17) |
|
```
template< class Iterator1, class Iterator2 >
constexpr bool operator>( const std::reverse_iterator<Iterator1>& lhs,
const std::reverse_iterator<Iterator2>& rhs );
```
| (since C++17) |
| | (6) | |
|
```
template< class Iterator1, class Iterator2 >
bool operator>=( const std::reverse_iterator<Iterator1>& lhs,
const std::reverse_iterator<Iterator2>& rhs );
```
| (until C++17) |
|
```
template< class Iterator1, class Iterator2 >
constexpr bool operator>=( const std::reverse_iterator<Iterator1>& lhs,
const std::reverse_iterator<Iterator2>& rhs );
```
| (since C++17) |
|
```
template< class Iterator1, std::three_way_comparable_with<Iterator1> Iterator2 >
constexpr std::compare_three_way_result_t<Iterator1, Iterator2>
operator<=>( const std::reverse_iterator<Iterator1>& lhs,
const std::reverse_iterator<Iterator2>& rhs );
```
| (7) | (since C++20) |
Compares the underlying iterators. Inverse comparisons are applied in order to take into account that the iterator order is reversed.
| | |
| --- | --- |
| (1-6) only participate in overload resolution if their underlying comparison expressions (see below) are well-formed and convertible to `bool`. | (since C++20) |
### Parameters
| | | |
| --- | --- | --- |
| lhs, rhs | - | iterator adaptors to compare |
### Return Value
1) `lhs.base() == rhs.base()`
2) `lhs.base() != rhs.base()`
3) `lhs.base() > rhs.base()`
4) `lhs.base() >= rhs.base()`
5) `lhs.base() < rhs.base()`
6) `lhs.base() <= rhs.base()`
7) `rhs.base() <=> lhs.base()`
### Example
```
#include <compare>
#include <iostream>
#include <iterator>
int main()
{
int a[] {0, 1, 2, 3};
// โ โโโโโโ x, y
// โโโโโโโโโ z
std::reverse_iterator<int*>
x { std::rend(a) - std::size(a) },
y { std::rend(a) - std::size(a) },
z { std::rbegin(a) + 1 };
std::cout
<< std::boolalpha
<< "*x == " << *x << '\n' // 3
<< "*y == " << *y << '\n' // 3
<< "*z == " << *z << '\n' // 2
<< "x == y ? " << (x == y) << '\n' // true
<< "x != y ? " << (x != y) << '\n' // false
<< "x < y ? " << (x < y) << '\n' // false
<< "x <= y ? " << (x <= y) << '\n' // true
<< "x == z ? " << (x == z) << '\n' // false
<< "x != z ? " << (x != z) << '\n' // true
<< "x < z ? " << (x < z) << '\n' // true!
<< "x <= z ? " << (x <= z) << '\n' // true
<< "x <=> y == 0 ? " << (x <=> y == 0) << '\n' // true
<< "x <=> y < 0 ? " << (x <=> y < 0) << '\n' // false
<< "x <=> y > 0 ? " << (x <=> y > 0) << '\n' // false
<< "x <=> z == 0 ? " << (x <=> z == 0) << '\n' // false
<< "x <=> z < 0 ? " << (x <=> z < 0) << '\n' // true
<< "x <=> z > 0 ? " << (x <=> z > 0) << '\n' // false
;
}
```
Output:
```
*x == 3
*y == 3
*z == 2
x == y ? true
x != y ? false
x < y ? false
x <= y ? false
x == z ? false
x != z ? true
x < z ? true
x <= z ? true
x <=> y == 0 ? true
x <=> y < 0 ? false
x <=> y > 0 ? false
x <=> z == 0 ? false
x <=> z < 0 ? true
x <=> z > 0 ? false
```
cpp operator-(std::move_iterator)
operator-(std::move\_iterator)
==============================
| | | |
| --- | --- | --- |
|
```
template< class Iterator1, class Iterator2 >
auto operator-( const move_iterator<Iterator1>& lhs,
const move_iterator<Iterator2>& rhs
) -> decltype(lhs.base() - rhs.base());
```
| | (since C++11) (until C++17) |
|
```
template< class Iterator1, class Iterator2 >
constexpr auto operator-( const move_iterator<Iterator1>& lhs,
const move_iterator<Iterator2>& rhs
) -> decltype(lhs.base() - rhs.base());
```
| | (since C++17) |
Returns the distance between two iterator adaptors.
### Parameters
| | | |
| --- | --- | --- |
| lhs, rhs | - | iterator adaptors to compute the difference of |
### Return value
`lhs.base() - rhs.base()`.
### Example
### See also
| | |
| --- | --- |
| [operator++operator++(int)operator+=operator+operator--operator--(int)operator-=operator-](operator_arith "cpp/iterator/move iterator/operator arith")
(C++11) | advances or decrements the iterator (public member function) |
| [operator+](operator_plus_ "cpp/iterator/move iterator/operator+")
(C++11) | advances the iterator (function template) |
cpp std::move_iterator<Iter>::base std::move\_iterator<Iter>::base
===============================
| | | |
| --- | --- | --- |
| | (1) | |
|
```
iterator_type base() const;
```
| (since C++11) (until C++17) |
|
```
constexpr iterator_type base() const;
```
| (since C++17) (until C++20) |
|
```
constexpr const iterator_type& base() const& noexcept;
```
| (since C++20) |
|
```
constexpr iterator_type base() &&;
```
| (2) | (since C++20) |
Returns the underlying base iterator.
| | |
| --- | --- |
| 1) Copy constructs the return value from the underlying iterator. | (until C++20) |
| 1) Returns a reference to the underlying iterator. | (since C++20) |
2) Move constructs the return value from the underlying iterator. ### Parameters
(none).
### Return value
| | |
| --- | --- |
| 1) A copy of the underlying iterator. | (until C++20) |
| 1) A reference to the underlying iterator. | (since C++20) |
2) An iterator move constructed from the underlying iterator. ### Exceptions
May throw implementation-defined exceptions.
### Example
```
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
int main()
{
std::vector<int> v{ 0, 1, 2, 3, 4 };
std::move_iterator<std::vector<int>::reverse_iterator>
m1{ v.rbegin() },
m2{ v.rend() };
std::copy(m1.base(), m2.base(), std::ostream_iterator<int>(std::cout, " "));
std::cout << '\n';
}
```
Output:
```
4 3 2 1 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 3391](https://cplusplus.github.io/LWG/issue3391) | C++20 | the const version of `base` returns a copy of the underlying iterator | returns a reference |
| [LWG 3593](https://cplusplus.github.io/LWG/issue3593) | C++20 | the const version of `base` returns a reference but might not be noexcept | made noexcept |
### See also
| | |
| --- | --- |
| [operator\*operator->](operator* "cpp/iterator/move iterator/operator*")
(C++11)(C++11)(deprecated in C++20) | accesses the pointed-to element (public member function) |
cpp iter_move(std::move_iterator)
iter\_move(std::move\_iterator)
===============================
| | | |
| --- | --- | --- |
|
```
friend constexpr std::iter_rvalue_reference_t<Iter>
iter_move( const std::move_iterator& i ) noexcept(/* see below */);
```
| | (since C++20) |
Casts the result of dereferencing the underlying iterator to its associated rvalue reference type.
The function body is equivalent to: `return std::[ranges::iter\_move](http://en.cppreference.com/w/cpp/iterator/ranges/iter_move)(i.base());`.
This function template is not visible to ordinary [unqualified](../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../language/adl "cpp/language/adl") when `std::move_iterator<Iter>` is an associated class of the arguments.
### Parameters
| | | |
| --- | --- | --- |
| i | - | a source move iterator. |
### Return value
An rvalue reference or a prvalue temporary.
### Complexity
Constant.
### Exceptions
[`noexcept`](../../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept(noexcept([ranges::iter\_move](http://en.cppreference.com/w/cpp/iterator/ranges/iter_move)(i.base())))`
### Example
```
#include <iomanip>
#include <iostream>
#include <iterator>
#include <string>
#include <vector>
void print(auto const& rem, auto const& v) {
std::cout << rem << "[" << size(v) << "] { ";
for (int o{}; auto const& s : v)
std::cout << (o++ == 0 ? "" : ", ") << quoted(s);
std::cout << " }\n";
}
int main()
{
std::vector<std::string> p { "Andromeda", "Cassiopeia", "Phoenix" }, q;
print("p", p), print("q", q);
using MI = std::move_iterator<std::vector<std::string>::iterator>;
for (MI first{ p.begin() }, last{ p.end() }; first != last; ++first) {
q.emplace_back( /* ADL */ iter_move(first) );
}
print("p", p), print("q", q);
}
```
Possible output:
```
p[3] { "Andromeda", "Cassiopeia", "Phoenix" }
q[0] { }
p[3] { "", "", "" }
q[3] { "Andromeda", "Cassiopeia", "Phoenix" }
```
### See also
| | |
| --- | --- |
| [iter\_move](../ranges/iter_move "cpp/iterator/ranges/iter move")
(C++20) | casts the result of dereferencing an object to its associated rvalue reference type (customization point object) |
| [iter\_move](../reverse_iterator/iter_move "cpp/iterator/reverse iterator/iter move")
(C++20) | casts the result of dereferencing the adjusted underlying iterator to its associated rvalue reference type (function) |
| [move](../../utility/move "cpp/utility/move")
(C++11) | obtains an rvalue reference (function template) |
| [move\_if\_noexcept](../../utility/move_if_noexcept "cpp/utility/move if noexcept")
(C++11) | obtains an rvalue reference if the move constructor does not throw (function template) |
| [forward](../../utility/forward "cpp/utility/forward")
(C++11) | forwards a function argument (function template) |
| [ranges::move](../../algorithm/ranges/move "cpp/algorithm/ranges/move")
(C++20) | moves a range of elements to a new location (niebloid) |
| [ranges::move\_backward](../../algorithm/ranges/move_backward "cpp/algorithm/ranges/move backward")
(C++20) | moves a range of elements to a new location in backwards order (niebloid) |
| programming_docs |
cpp std::move_iterator<Iter>::operator[] std::move\_iterator<Iter>::operator[]
=====================================
| | | |
| --- | --- | --- |
|
```
/*unspecified*/ operator[]( difference_type n ) const;
```
| | (since C++11) (until C++17) |
|
```
constexpr /*unspecified*/ operator[]( difference_type n ) const;
```
| | (since C++17) |
Returns a reference to the element at specified relative location.
### Parameters
| | | |
| --- | --- | --- |
| n | - | position relative to current location. |
### Return value
An rvalue reference to the element at relative location, that is, `std::move(base()[n])` (until C++20)`[ranges::iter\_move](http://en.cppreference.com/w/cpp/iterator/ranges/iter_move)(base() + n)` (since C++20).
### Example
```
#include <iomanip>
#include <iostream>
#include <iterator>
#include <list>
#include <string>
#include <vector>
void print(auto rem, auto const& v) {
for (std::cout << rem; auto const& e : v)
std::cout << quoted(e) << ' ';
std::cout << '\n';
}
int main()
{
std::vector<std::string> p{"alpha", "beta", "gamma", "delta"}, q;
print("1) p: ", p);
std::move_iterator it{p.begin()};
for (size_t t{0U}; t != p.size(); ++t) {
q.emplace_back( it[t] );
}
print("2) p: ", p);
print("3) q: ", q);
std::list l{1,2,3};
std::move_iterator it2{l.begin()};
// it2[1] = 13; // compilation error ~ the underlying iterator
// does not model the random access iterator
// *it2 = 999; // compilation error: using rvalue as lvalue
}
```
Possible output:
```
1) p: "alpha" "beta" "gamma" "delta"
2) p: "" "" "" ""
3) q: "alpha" "beta" "gamma" "delta"
```
### See also
| | |
| --- | --- |
| [operator\*operator->](operator* "cpp/iterator/move iterator/operator*")
(C++11)(C++11)(deprecated in C++20) | accesses the pointed-to element (public member function) |
cpp std::move_iterator<Iter>::move_iterator std::move\_iterator<Iter>::move\_iterator
=========================================
| | | |
| --- | --- | --- |
| | (1) | |
|
```
move_iterator();
```
| (until C++17) |
|
```
constexpr move_iterator();
```
| (since C++17) |
| | (2) | |
|
```
explicit move_iterator( iterator_type x );
```
| (until C++17) |
|
```
constexpr explicit move_iterator( iterator_type x );
```
| (since C++17) |
| | (3) | |
|
```
template< class U >
move_iterator( const move_iterator<U>& other );
```
| (until C++17) |
|
```
template< class U >
constexpr move_iterator( const move_iterator<U>& other );
```
| (since C++17) |
Constructs a new iterator adaptor.
1) Default constructor. The underlying iterator is value-initialized. Operations on the resulting iterator have defined behavior if and only if the corresponding operations on a value-initialized `Iter` also have defined behavior.
2) The underlying iterator is initialized with `x` (until C++20)`std::move(x)` (since C++20).
3) The underlying iterator is initialized with that of `other`. The behavior is undefined if `U` is not convertible to `Iter` (until C++20)This overload participates in overload resolution only if `U` is not the same type as `Iter` and `[std::convertible\_to](http://en.cppreference.com/w/cpp/concepts/convertible_to)<const U&, Iter>` is modeled (since C++20). ### Parameters
| | | |
| --- | --- | --- |
| x | - | iterator to adapt |
| other | - | iterator adaptor to copy |
### 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 3435](https://cplusplus.github.io/LWG/issue3435) | C++20 | the converting constructor from another `move_iterator` was not constrained | constrained |
### See also
| | |
| --- | --- |
| [operator=](operator= "cpp/iterator/move iterator/operator=")
(C++11) | assigns another iterator adaptor (public member function) |
| [make\_move\_iterator](../make_move_iterator "cpp/iterator/make move iterator")
(C++11) | creates a `[std::move\_iterator](../move_iterator "cpp/iterator/move iterator")` of type inferred from the argument (function template) |
cpp std::move_iterator<Iter>::operator*,-> std::move\_iterator<Iter>::operator\*,->
========================================
| | | |
| --- | --- | --- |
| | (1) | |
|
```
reference operator* () const;
```
| (since C++11) (until C++17) |
|
```
constexpr reference operator* () const;
```
| (since C++17) |
| | (2) | |
|
```
pointer operator->() const;
```
| (since C++11) (until C++17) |
|
```
constexpr pointer operator->() const;
```
| (since C++17) (deprecated in C++20) |
Returns a rvalue-reference or pointer to the current element.
1) Equivalent to `static_cast<reference>(*base())` (until C++20)`[ranges::iter\_move](http://en.cppreference.com/w/cpp/iterator/ranges/iter_move)(base())` (since C++20).
2) Equivalent to [`base()`](base "cpp/iterator/move iterator/base"). ### Parameters
(none).
### Return value
1) Rvalue-reference to the current element or its copy.
2) Copy of the underlying iterator. A pointer to the current element is eventually returned if `->` is directly used. ### Notes
Note that (2) eventually returns a pointer if `->` is directly used. When dereferencing a pointer the returned value is an lvalue. This may lead to unintended behavior.
### Example
```
#include <iomanip>
#include <iostream>
#include <iterator>
#include <string>
#include <vector>
void print(auto rem, auto const& v) {
for (std::cout << rem; auto const& e : v)
std::cout << quoted(e) << ' ';
std::cout << '\n';
}
int main()
{
std::vector<std::string> p{"alpha", "beta", "gamma", "delta"}, q;
print("1) p: ", p);
for (std::move_iterator it{p.begin()}, end{p.end()}; it != end; ++it) {
it->push_back('!'); // calls -> string::push_back(char)
q.emplace_back( *it );
}
print("2) p: ", p);
print("3) q: ", q);
std::vector v{1,2,3};
std::move_iterator it{v.begin()};
// *it = 13; // error: using rvalue as lvalue
}
```
Output:
```
1) p: "alpha" "beta" "gamma" "delta"
2) p: "" "" "" ""
3) q: "alpha!" "beta!" "gamma!" "delta!"
```
### 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 2106](https://cplusplus.github.io/LWG/issue2106) | C++11 | dereferencing a `move_iterator` could return a dangling referenceif the dereferencing the underlying iterator returns a prvalue | returns the object instead |
### See also
| | |
| --- | --- |
| [operator[]](operator_at "cpp/iterator/move iterator/operator at")
(C++11) | accesses an element by index (public member function) |
cpp operator+(std::move_iterator)
operator+(std::move\_iterator)
==============================
| Defined in header `[<iterator>](../../header/iterator "cpp/header/iterator")` | | |
| --- | --- | --- |
|
```
template< class Iter >
move_iterator<Iter>
operator+( typename move_iterator<Iter>::difference_type n,
const move_iterator<Iter>& it );
```
| | (since C++11) (until C++17) |
|
```
template< class Iter >
constexpr move_iterator<Iter>
operator+( typename move_iterator<Iter>::difference_type n,
const move_iterator<Iter>& it );
```
| | (since C++17) |
Returns the iterator `it` incremented by `n`.
| | |
| --- | --- |
| This overload participates in overload resolution only if `it.base() + n` is well-formed and has type `Iter`. | (since C++20) |
### Parameters
| | | |
| --- | --- | --- |
| n | - | the number of positions to increment the iterator |
| it | - | the iterator adaptor to increment |
### Return value
The incremented iterator, that is `move_iterator<Iter>(it.base() + n)`.
### Example
### See also
| | |
| --- | --- |
| [operator++operator++(int)operator+=operator+operator--operator--(int)operator-=operator-](operator_arith "cpp/iterator/move iterator/operator arith")
(C++11) | advances or decrements the iterator (public member function) |
| [operator-](operator- "cpp/iterator/move iterator/operator-")
(C++11) | computes the distance between two iterator adaptors (function template) |
cpp std::move_iterator<Iter>::operator= std::move\_iterator<Iter>::operator=
====================================
| | | |
| --- | --- | --- |
|
```
template< class U >
move_iterator& operator=( const move_iterator<U>& other );
```
| | (until C++17) |
|
```
template< class U >
constexpr move_iterator& operator=( const move_iterator<U>& other );
```
| | (since C++17) |
The underlying iterator is assigned the value of the underlying iterator of `other`, i.e. `other.base()`.
| | |
| --- | --- |
| The behavior is undefined if `U` is not convertible to `Iter`. | (until C++20) |
| This overload participates in overload resolution only if `U` is not the same type as `Iter` and `[std::convertible\_to](http://en.cppreference.com/w/cpp/concepts/convertible_to)<const U&, Iter>` and `[std::assignable\_from](http://en.cppreference.com/w/cpp/concepts/assignable_from)<Iter&, const U&>` are modeled. | (since C++20) |
### Parameters
| | | |
| --- | --- | --- |
| other | - | iterator adaptor to assign |
### Return value
`*this`.
### 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 3435](https://cplusplus.github.io/LWG/issue3435) | C++20 | the converting assignment operator was not constrained | constrained |
### See also
| | |
| --- | --- |
| [(constructor)](move_iterator "cpp/iterator/move iterator/move iterator")
(C++11) | constructs a new iterator adaptor (public member function) |
cpp operator-(std::move_iterator<Iter>, std::move_sentinel)
operator-(std::move\_iterator<Iter>, std::move\_sentinel)
=========================================================
| | | |
| --- | --- | --- |
|
```
template<std::sized_sentinel_for<Iter> S>
friend constexpr std::iter_difference_t<Iter>
operator-(const std::move_sentinel<S>& s, const move_iterator& i);
```
| (1) | (since C++20) |
|
```
template<std::sized_sentinel_for<Iter> S>
friend constexpr std::iter_difference_t<Iter>
operator-(const move_iterator& i, const std::move_sentinel<S>& s);
```
| (2) | (since C++20) |
Returns the distance between a `move_iterator` and a `move_sentinel`.
These function templates are not visible to ordinary [unqualified](../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../language/adl "cpp/language/adl") when `std::move_iterator<Iter>` is an associated class of the arguments.
### Parameters
| | | |
| --- | --- | --- |
| i | - | `[std::move\_iterator](http://en.cppreference.com/w/cpp/iterator/move_iterator)<Iter>` |
| s | - | `[std::move\_sentinel](http://en.cppreference.com/w/cpp/iterator/move_sentinel)<S>`, where `S` models `[std::sized\_sentinel\_for](http://en.cppreference.com/w/cpp/iterator/sized_sentinel_for)<Iter>` |
### Return value
1) `s.base() - i.base()`
2) `i.base() - s.base()`
### Example
### See also
| | |
| --- | --- |
| [operator-](operator- "cpp/iterator/move iterator/operator-")
(C++11) | computes the distance between two iterator adaptors (function template) |
cpp iter_swap(std::move_iterator)
iter\_swap(std::move\_iterator)
===============================
| | | |
| --- | --- | --- |
|
```
template< std::indirectly_swappable<Iter> Iter2 >
friend constexpr void
iter_swap( const move_iterator& x, const std::move_iterator<Iter2>& y )
noexcept(/*see below*/);
```
| | (since C++20) |
Swaps the objects pointed to by two underlying iterators. The function body is equivalent to `[ranges::iter\_swap](http://en.cppreference.com/w/cpp/iterator/ranges/iter_swap)(x.base(), y.base());`.
This function template is not visible to ordinary [unqualified](../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../language/adl "cpp/language/adl") when `std::move_iterator<Iter>` is an associated class of the arguments.
### Parameters
| | | |
| --- | --- | --- |
| x, y | - | move iterators to the elements to swap. |
### Return value
(none).
### Complexity
Constant.
### Exceptions
[`noexcept`](../../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept(noexcept( [ranges::iter\_swap](http://en.cppreference.com/w/cpp/iterator/ranges/iter_swap)( x.base(), y.base() ) ))`
### Example
```
#include <iostream>
#include <iterator>
#include <string>
#include <vector>
int main()
{
std::vector<std::string> p { "AA", "EE" },
q { "โฑฏโฑฏ", "ฦฦ" };
std::move_iterator<std::vector<std::string>::iterator>
x = std::make_move_iterator( p.begin() ),
y = std::make_move_iterator( q.begin() );
std::cout << *x << ' ' << *y << '\n';
iter_swap(x, y); // ADL
std::cout << *x << ' ' << *y << '\n';
}
```
Output:
```
AA โฑฏโฑฏ
โฑฏโฑฏ AA
```
### See also
| | |
| --- | --- |
| [swap](../../algorithm/swap "cpp/algorithm/swap") | swaps the values of two objects (function template) |
| [swap\_ranges](../../algorithm/swap_ranges "cpp/algorithm/swap ranges") | swaps two ranges of elements (function template) |
| [iter\_swap](../../algorithm/iter_swap "cpp/algorithm/iter swap") | swaps the elements pointed to by two iterators (function template) |
| [iter\_swap](../ranges/iter_swap "cpp/iterator/ranges/iter swap")
(C++20) | swaps the values referenced by two dereferenceable objects (customization point object) |
| [iter\_swap](../reverse_iterator/iter_swap "cpp/iterator/reverse iterator/iter swap")
(C++20) | swaps the objects pointed to by two adjusted underlying iterators (function template) |
cpp operator==,!=,<,<=,>,>=,<=>(std::move_iterator)
operator==,!=,<,<=,>,>=,<=>(std::move\_iterator)
================================================
| | | |
| --- | --- | --- |
| | (1) | |
|
```
template< class Iterator1, class Iterator2 >
bool operator==( const std::move_iterator<Iterator1>& lhs,
const std::move_iterator<Iterator2>& rhs );
```
| (until C++17) |
|
```
template< class Iterator1, class Iterator2 >
constexpr bool operator==( const std::move_iterator<Iterator1>& lhs,
const std::move_iterator<Iterator2>& rhs );
```
| (since C++17) |
| | (2) | |
|
```
template< class Iterator1, class Iterator2 >
bool operator!=( const std::move_iterator<Iterator1>& lhs,
const std::move_iterator<Iterator2>& rhs );
```
| (until C++17) |
|
```
template< class Iterator1, class Iterator2 >
constexpr bool operator!=( const std::move_iterator<Iterator1>& lhs,
const std::move_iterator<Iterator2>& rhs );
```
| (since C++17) (until C++20) |
| | (3) | |
|
```
template< class Iterator1, class Iterator2 >
bool operator<( const std::move_iterator<Iterator1>& lhs,
const std::move_iterator<Iterator2>& rhs );
```
| (until C++17) |
|
```
template< class Iterator1, class Iterator2 >
constexpr bool operator<( const std::move_iterator<Iterator1>& lhs,
const std::move_iterator<Iterator2>& rhs );
```
| (since C++17) |
| | (4) | |
|
```
template< class Iterator1, class Iterator2 >
bool operator<=( const std::move_iterator<Iterator1>& lhs,
const std::move_iterator<Iterator2>& rhs );
```
| (until C++17) |
|
```
template< class Iterator1, class Iterator2 >
constexpr bool operator<=( const std::move_iterator<Iterator1>& lhs,
const std::move_iterator<Iterator2>& rhs );
```
| (since C++17) |
| | (5) | |
|
```
template< class Iterator1, class Iterator2 >
bool operator>( const std::move_iterator<Iterator1>& lhs,
const std::move_iterator<Iterator2>& rhs );
```
| (until C++17) |
|
```
template< class Iterator1, class Iterator2 >
constexpr bool operator>( const std::move_iterator<Iterator1>& lhs,
const std::move_iterator<Iterator2>& rhs );
```
| (since C++17) |
| | (6) | |
|
```
template< class Iterator1, class Iterator2 >
bool operator>=( const std::move_iterator<Iterator1>& lhs,
const std::move_iterator<Iterator2>& rhs );
```
| (until C++17) |
|
```
template< class Iterator1, class Iterator2 >
constexpr bool operator>=( const std::move_iterator<Iterator1>& lhs,
const std::move_iterator<Iterator2>& rhs );
```
| (since C++17) |
|
```
template< class Iterator1, std::three_way_comparable_with<Iterator1> Iterator2 >
constexpr std::compare_three_way_result_t<Iterator1, Iterator2>
operator<=>( const std::move_iterator<Iterator1>& lhs,
const std::move_iterator<Iterator2>& rhs );
```
| (7) | (since C++20) |
Compares the underlying iterators.
| | |
| --- | --- |
| (1-6) only participate in overload resolution if their underlying comparison expressions (see below) are well-formed and convertible to `bool`.
The `!=` operator is [synthesized](../../language/operators#Relational_operators "cpp/language/operators") from `operator==`. | (since C++20) |
### Parameters
| | | |
| --- | --- | --- |
| lhs, rhs | - | iterator adaptors to compare |
### Return Value
1) `lhs.base() == rhs.base()`
2) `!(lhs == rhs)`
3) `lhs.base() < rhs.base()`
4) `!(rhs < lhs)`
5) `rhs < lhs`
6) `!(lhs < rhs)`
7) `lhs.base() <=> rhs.base()`
### Example
```
#include <compare>
#include <iostream>
#include <iterator>
int main()
{
int a[] {9, 8, 7, 6};
// โ โโโโโโ x, y
// โโโโโโโโโ z
std::move_iterator<int*>
x { std::end(a) - 1 },
y { std::end(a) - 1 },
z { std::end(a) - 2 };
std::cout
<< std::boolalpha
<< "*x == " << *x << '\n' // 6
<< "*y == " << *y << '\n' // 6
<< "*z == " << *z << '\n' // 7
<< "x == y ? " << (x == y) << '\n' // true
<< "x != y ? " << (x != y) << '\n' // false
<< "x < y ? " << (x < y) << '\n' // false
<< "x <= y ? " << (x <= y) << '\n' // true
<< "x == z ? " << (x == z) << '\n' // false
<< "x != z ? " << (x != z) << '\n' // true
<< "x < z ? " << (x < z) << '\n' // false!
<< "x <= z ? " << (x <= z) << '\n' // false
<< "x <=> y == 0 ? " << (x <=> y == 0) << '\n' // true
<< "x <=> y < 0 ? " << (x <=> y < 0) << '\n' // false
<< "x <=> y > 0 ? " << (x <=> y > 0) << '\n' // false
<< "x <=> z == 0 ? " << (x <=> z == 0) << '\n' // false
<< "x <=> z < 0 ? " << (x <=> z < 0) << '\n' // true
<< "x <=> z > 0 ? " << (x <=> z > 0) << '\n' // false
;
}
```
Output:
```
*x == 6
*y == 6
*z == 7
x == y ? true
x != y ? false
x < y ? false
x <= y ? true
x == z ? false
x != z ? true
x < z ? false
x <= z ? false
x <=> y == 0 ? true
x <=> y < 0 ? false
x <=> y > 0 ? false
x <=> z == 0 ? false
x <=> z < 0 ? false
x <=> z > 0 ? true
```
### See also
| | |
| --- | --- |
| [operator==(std::move\_sentinel)](operator_cmp2 "cpp/iterator/move iterator/operator cmp2")
(C++20) | compares the underlying iterator and the underlying sentinel (function template) |
| programming_docs |
cpp std::move_sentinel<S>::base std::move\_sentinel<S>::base
============================
| | | |
| --- | --- | --- |
|
```
constexpr S base() const;
```
| | (since C++20) |
Returns the underlying base sentinel.
### Parameters
(none).
### Return value
The underlying sentinel.
### Exceptions
May throw implementation-defined exceptions.
### Example
### See also
| | |
| --- | --- |
| [base](../move_iterator/base "cpp/iterator/move iterator/base")
(C++11) | accesses the underlying iterator (public member function of `std::move_iterator<Iter>`) |
cpp std::move_sentinel<S>::operator= std::move\_sentinel<S>::operator=
=================================
| | | |
| --- | --- | --- |
|
```
template<class S2>
requires std::assignable_from<S&, const S2&>
constexpr move_sentinel& operator=(const std::move_sentinel<S2>& other);
```
| | (since C++20) |
The underlying sentinel is assigned the value of the underlying sentinel of `other`, i.e. `other.base()`.
### Parameters
| | | |
| --- | --- | --- |
| other | - | sentinel adaptor to assign |
### Return value
`*this`.
### Example
### See also
| | |
| --- | --- |
| [operator=](../move_iterator/operator= "cpp/iterator/move iterator/operator=")
(C++11) | assigns another iterator adaptor (public member function of `std::move_iterator<Iter>`) |
cpp std::move_sentinel<S>::move_sentinel std::move\_sentinel<S>::move\_sentinel
======================================
| | | |
| --- | --- | --- |
|
```
constexpr move_sentinel();
```
| (1) | (since C++20) |
|
```
constexpr explicit move_sentinel( S x );
```
| (2) | (since C++20) |
|
```
template< class S2 >
requires std::convertible_to<const S2&, S>
constexpr move_sentinel(const std::move_sentinel<S2>& other);
```
| (3) | (since C++20) |
Constructs a new sentinel adaptor.
1) Default constructor. The underlying sentinel is value-initialized.
2) The underlying sentinel is initialized with `x`.
3) The underlying sentinel is initialized with that of `other`. ### Parameters
| | | |
| --- | --- | --- |
| x | - | sentinel to adapt |
| other | - | sentinel adaptor to copy |
### Example
### See also
| | |
| --- | --- |
| [(constructor)](../move_iterator/move_iterator "cpp/iterator/move iterator/move iterator")
(C++11) | constructs a new iterator adaptor (public member function of `std::move_iterator<Iter>`) |
cpp std::istreambuf_iterator<CharT,Traits>::operator*, operator-> std::istreambuf\_iterator<CharT,Traits>::operator\*, operator->
===============================================================
| | | |
| --- | --- | --- |
|
```
CharT operator*() const;
```
| (1) | |
|
```
pointer operator->() const;
```
| (2) | (since C++11) (until C++17) |
Reads a single character by calling `sbuf_->sgetc()` where `sbuf_` is the stored pointer to the stream buffer.
The behavior is undefined if the iterator is end-of-stream iterator.
### Parameters
(none).
### Return value
1) The value of the obtained character.
2) An object of unspecified type, such that given an istreambuf iterator `i`, the expressions `(*i).m` and `i->m` have the same effect. ### Exceptions
May throw implementation-defined exceptions.
cpp std::istreambuf_iterator<CharT,Traits>::istreambuf_iterator std::istreambuf\_iterator<CharT,Traits>::istreambuf\_iterator
=============================================================
| | | |
| --- | --- | --- |
| | (1) | |
|
```
istreambuf_iterator() throw();
```
| (until C++11) |
|
```
constexpr istreambuf_iterator() noexcept;
```
| (since C++11) |
|
```
constexpr istreambuf_iterator( std::default_sentinel_t ) noexcept;
```
| (2) | (since C++20) |
| | (3) | |
|
```
istreambuf_iterator( std::basic_istream<CharT,Traits>& is ) throw();
```
| (until C++11) |
|
```
istreambuf_iterator( std::basic_istream<CharT,Traits>& is ) noexcept;
```
| (since C++11) |
| | (4) | |
|
```
istreambuf_iterator( std::basic_streambuf<CharT,Traits>* s ) throw();
```
| (until C++11) |
|
```
istreambuf_iterator( std::basic_streambuf<CharT,Traits>* s ) noexcept;
```
| (since C++11) |
| | (5) | |
|
```
istreambuf_iterator( const /* proxy */& p ) throw();
```
| (until C++11) |
|
```
istreambuf_iterator( const /* proxy */& p ) noexcept;
```
| (since C++11) |
|
```
istreambuf_iterator( const istreambuf_iterator& ) noexcept = default;
```
| (6) | (since C++11) |
1-2) Constructs an end-of-stream iterator.
3) Initializes the iterator and stores the value of `is.rdbuf()` in a data member. If `is.rdbuf()` is null, then end-of-stream iterator is constructed.
4) Initializes the iterator and stores the value of `s` in a data member. If `s` is null, then end-of-stream iterator is constructed.
5) Effectively call (3) with the `streambuf_type*` pointer `p` holds.
6) The copy constructor is trivial and explicitly defaulted.
| | |
| --- | --- |
| The copy constructor is effectively implicitly declared and not guaranteed to be trivial. | (until C++11) |
### Parameters
| | | |
| --- | --- | --- |
| is | - | stream to obtain the stream buffer from |
| s | - | stream buffer to initialize the iterator with |
| p | - | object of the implementation-defined proxy type |
cpp std::istreambuf_iterator<CharT,Traits>::operator++, operator++(int) std::istreambuf\_iterator<CharT,Traits>::operator++, operator++(int)
====================================================================
| | | |
| --- | --- | --- |
|
```
istreambuf_iterator& operator++();
```
| (1) | |
|
```
/* proxy */ operator++(int);
```
| (2) | |
Advances the iterator by calling `sbuf_->sbumpc()` where `sbuf_` is the stored pointer to the stream buffer.
The behavior is undefined if the iterator is end-of-stream iterator.
### Parameters
(none).
### Return value
1) `*this`.
2) A `proxy` object holding the current character obtained via `operator*()` and the `sbuf_` pointer. Dereferencing a `proxy` object with `operator*` yields the stored character.
The name `proxy` is for exposition only. ### Exceptions
May throw implementation-defined exceptions.
cpp std::istreambuf_iterator<CharT,Traits>::equal std::istreambuf\_iterator<CharT,Traits>::equal
==============================================
| | | |
| --- | --- | --- |
|
```
bool equal( const istreambuf_iterator& it ) const;
```
| | |
Checks whether both `*this` and `it` are valid, or both are invalid, regardless of the stream buffer objects they use.
### Parameters
| | | |
| --- | --- | --- |
| it | - | another stream buffer iterator to compare to |
### Return value
`true` if both `*this` and `it` are valid, or both are invalid, `false` otherwise.
### Exceptions
May throw implementation-defined exceptions.
### 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 110](https://cplusplus.github.io/LWG/issue110) | C++98 | the signature was `bool equal(istreambuf_iterator& it)` | `const`s added |
cpp operator==,!=(std::istreambuf_iterator<CharT,Traits>) operator==,!=(std::istreambuf\_iterator<CharT,Traits>)
======================================================
| Defined in header `[<iterator>](../../header/iterator "cpp/header/iterator")` | | |
| --- | --- | --- |
|
```
template< class CharT, class Traits >
bool operator==( const std::istreambuf_iterator<CharT,Traits>& lhs,
const std::istreambuf_iterator<CharT,Traits>& rhs );
```
| (1) | |
|
```
template< class CharT, class Traits >
bool operator!=( const std::istreambuf_iterator<CharT,Traits>& lhs,
const std::istreambuf_iterator<CharT,Traits>& rhs );
```
| (2) | (until C++20) |
|
```
friend bool operator==( const istreambuf_iterator& lhs,
std::default_sentinel_t );
```
| (3) | (since C++20) |
Checks whether both `lhs` and `rhs` are valid, or both are invalid, regardless of the stream buffer objects they use.
1) Equivalent to `lhs.equal(rhs)`.
2) Equivalent to `!lhs.equal(rhs)`.
3) Checks whether `lhs` is invalid. Equivalent to `lhs.equal(istreambuf_iterator{})`.
This function is not visible to ordinary [unqualified](../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../language/adl "cpp/language/adl") when `std::istreambuf_iterator<CharT,Traits>` is an associated class of the arguments.
| | |
| --- | --- |
| The `!=` operator is [synthesized](../../language/operators#Relational_operators "cpp/language/operators") from `operator==`. | (since C++20) |
### Parameters
| | | |
| --- | --- | --- |
| lhs, rhs | - | stream buffer iterators to compare |
### Return value
1) The result of `lhs.equal(rhs)`.
2) The result of `!lhs.equal(rhs)`.
3) The result of `lhs.equal(istreambuf_iterator{})`. ### Exceptions
May throw implementation-defined exceptions.
cpp std::front_insert_iterator<Container>::operator++ std::front\_insert\_iterator<Container>::operator++
===================================================
| | | |
| --- | --- | --- |
|
```
front_insert_iterator& operator++();
```
| | (until C++20) |
|
```
constexpr front_insert_iterator& operator++();
```
| | (since C++20) |
|
```
front_insert_iterator operator++( int );
```
| | (until C++20) |
|
```
constexpr front_insert_iterator operator++( int );
```
| | (since C++20) |
Does nothing. These operator overloads are provided to satisfy the requirements of [LegacyOutputIterator](../../named_req/outputiterator "cpp/named req/OutputIterator"). They make it possible for the expressions `*iter++=value` and `*++iter=value` to be used to output (insert) a value into the underlying container.
### Parameters
(none).
### Return value
`*this`.
cpp std::front_insert_iterator<Container>::operator* std::front\_insert\_iterator<Container>::operator\*
===================================================
| | | |
| --- | --- | --- |
|
```
front_insert_iterator& operator*();
```
| | (until C++20) |
|
```
constexpr front_insert_iterator& operator*();
```
| | (since C++20) |
Does nothing, this member function is provided to satisfy the requirements of [LegacyOutputIterator](../../named_req/outputiterator "cpp/named req/OutputIterator").
It returns the iterator itself, which makes it possible to use code such as `*iter = value` to output (insert) the value into the underlying container.
### Parameters
(none).
### Return value
`*this`.
cpp std::front_insert_iterator<Container>::operator= std::front\_insert\_iterator<Container>::operator=
==================================================
| | | |
| --- | --- | --- |
| | (1) | |
|
```
front_insert_iterator<Container>&
operator=( typename Container::const_reference value );
```
| (until C++11) |
|
```
front_insert_iterator<Container>&
operator=( const typename Container::value_type& value );
```
| (since C++11) (until C++20) |
|
```
constexpr front_insert_iterator<Container>&
operator=( const typename Container::value_type& value );
```
| (since C++20) |
| | (2) | |
|
```
front_insert_iterator<Container>&
operator=( typename Container::value_type&& value );
```
| (since C++11) (until C++20) |
|
```
constexpr front_insert_iterator<Container>&
operator=( typename Container::value_type&& value );
```
| (since C++20) |
Inserts the given value `value` to the container.
1) Results in `container->push_front(value)`
2) Results in `container->push_front(std::move(value))`
### Parameters
| | | |
| --- | --- | --- |
| value | - | the value to insert |
### Return value
`*this`.
### Example
```
#include <iostream>
#include <iterator>
#include <deque>
int main()
{
std::deque<int> q;
std::front_insert_iterator< std::deque<int> > it(q);
for (int i=0; i<10; ++i)
it = i; // calls q.push_front(i)
for (auto& elem : q) std::cout << elem << ' ';
}
```
Output:
```
9 8 7 6 5 4 3 2 1 0
```
cpp std::front_insert_iterator<Container>::front_insert_iterator std::front\_insert\_iterator<Container>::front\_insert\_iterator
================================================================
| | | |
| --- | --- | --- |
|
```
explicit front_insert_iterator( Container& c );
```
| | (until C++20) |
|
```
explicit constexpr front_insert_iterator( Container& c );
```
| | (since C++20) |
Initializes the underlying pointer to the container to `[std::addressof](http://en.cppreference.com/w/cpp/memory/addressof)(c)`.
### Parameters
| | | |
| --- | --- | --- |
| c | - | container to initialize the inserter with |
### 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 | default constructor was provided as C++20 iteratorsmust be [`default_initializable`](../../concepts/default_initializable "cpp/concepts/default initializable") | removed along with the requirement |
cpp std::back_insert_iterator<Container>::operator++ std::back\_insert\_iterator<Container>::operator++
==================================================
| | | |
| --- | --- | --- |
|
```
back_insert_iterator& operator++();
```
| | (until C++20) |
|
```
constexpr back_insert_iterator& operator++();
```
| | (since C++20) |
|
```
back_insert_iterator operator++( int );
```
| | (until C++20) |
|
```
constexpr back_insert_iterator operator++( int );
```
| | (since C++20) |
Does nothing. These operator overloads are provided to satisfy the requirements of [LegacyOutputIterator](../../named_req/outputiterator "cpp/named req/OutputIterator"). They make it possible for the expressions `*iter++=value` and `*++iter=value` to be used to output (insert) a value into the underlying container.
### Parameters
(none).
### Return value
`*this`.
cpp std::back_insert_iterator<Container>::operator* std::back\_insert\_iterator<Container>::operator\*
==================================================
| | | |
| --- | --- | --- |
|
```
back_insert_iterator& operator*();
```
| | (until C++20) |
|
```
constexpr back_insert_iterator& operator*();
```
| | (since C++20) |
Does nothing, this member function is provided to satisfy the requirements of [LegacyOutputIterator](../../named_req/outputiterator "cpp/named req/OutputIterator").
It returns the iterator itself, which makes it possible to use code such as `*iter = value` to output (insert) the value into the underlying container.
### Parameters
(none).
### Return value
`*this`.
cpp std::back_insert_iterator<Container>::operator= std::back\_insert\_iterator<Container>::operator=
=================================================
| | | |
| --- | --- | --- |
| | (1) | |
|
```
back_insert_iterator<Container>&
operator=( typename Container::const_reference value );
```
| (until C++11) |
|
```
back_insert_iterator<Container>&
operator=( const typename Container::value_type& value );
```
| (since C++11) (until C++20) |
|
```
constexpr back_insert_iterator<Container>&
operator=( const typename Container::value_type& value );
```
| (since C++20) |
| | (2) | |
|
```
back_insert_iterator<Container>&
operator=( typename Container::value_type&& value );
```
| (since C++11) (until C++20) |
|
```
constexpr back_insert_iterator<Container>&
operator=( typename Container::value_type&& value );
```
| (since C++20) |
Inserts the given value `value` to the container.
1) Results in `container->push_back(value)`
2) Results in `container->push_back(std::move(value))`
### Parameters
| | | |
| --- | --- | --- |
| value | - | the value to insert |
### Return value
`*this`.
### Example
```
#include <iostream>
#include <iterator>
#include <deque>
int main()
{
std::deque<int> q;
std::back_insert_iterator< std::deque<int> > it(q);
for (int i=0; i<10; ++i)
it = i; // calls q.push_back(i)
for (auto& elem : q) std::cout << elem << ' ';
}
```
Output:
```
0 1 2 3 4 5 6 7 8 9
```
cpp std::back_insert_iterator<Container>::back_insert_iterator std::back\_insert\_iterator<Container>::back\_insert\_iterator
==============================================================
| | | |
| --- | --- | --- |
|
```
explicit back_insert_iterator( Container& c );
```
| | (until C++20) |
|
```
explicit constexpr back_insert_iterator( Container& c );
```
| | (since C++20) |
Initializes the underlying pointer to the container to `[std::addressof](http://en.cppreference.com/w/cpp/memory/addressof)(c)`.
### Parameters
| | | |
| --- | --- | --- |
| c | - | container to initialize the inserter with |
### 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 | default constructor was provided as C++20 iteratorsmust be [`default_initializable`](../../concepts/default_initializable "cpp/concepts/default initializable") | removed along with the requirement |
cpp std::istream_iterator<T,CharT,Traits,Distance>::~istream_iterator std::istream\_iterator<T,CharT,Traits,Distance>::~istream\_iterator
===================================================================
| | | |
| --- | --- | --- |
|
```
~istream_iterator();
```
| | (until C++11) |
|
```
~istream_iterator() = default;
```
| | (since C++11) |
Destroys the iterator, including the cached value.
| | |
| --- | --- |
| If `[std::is\_trivially\_destructible](http://en.cppreference.com/w/cpp/types/is_destructible)<T>::value` is `true`, then this destructor is a trivial destructor. | (since C++11) |
cpp std::istream_iterator<T,CharT,Traits,Distance>::istream_iterator std::istream\_iterator<T,CharT,Traits,Distance>::istream\_iterator
==================================================================
| | | |
| --- | --- | --- |
| | (1) | |
|
```
istream_iterator();
```
| (until C++11) |
|
```
constexpr istream_iterator();
```
| (since C++11) |
|
```
constexpr istream_iterator( std::default_sentinel_t );
```
| (2) | (since C++20) |
|
```
istream_iterator( istream_type& stream );
```
| (3) | |
| | (4) | |
|
```
istream_iterator( const istream_iterator& other );
```
| (until C++11) |
|
```
istream_iterator( const istream_iterator& other ) = default;
```
| (since C++11) |
1-2) Constructs the end-of-stream iterator, value-initializes the stored value. This constructor is constexpr if the initializer in the definition `auto x = T();` is a constant initializer (since C++11).
3) Initializes the iterator, stores the address of `stream` in a data member, and performs the first read from the input stream to initialize the cached value data member.
4) Constructs a copy of `other`. If `[std::is\_trivially\_copy\_constructible](http://en.cppreference.com/w/cpp/types/is_copy_constructible)<T>::value` is `true`, this copy constructor is a trivial copy constructor. (since C++11)
### Parameters
| | | |
| --- | --- | --- |
| stream | - | stream to initialize the istream\_iterator with |
| other | - | another istream\_iterator of the same type |
### Examples
```
#include <iostream>
#include <iterator>
#include <algorithm>
#include <sstream>
int main()
{
std::istringstream stream("1 2 3 4 5");
std::copy(
std::istream_iterator<int>(stream),
std::istream_iterator<int>(),
std::ostream_iterator<int>(std::cout, " ")
);
}
```
Output:
```
1 2 3 4 5
```
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [P0738R2](https://wg21.link/P0738R2) | C++98 | the first read may be deferred to the first dereferencing | the first read is performed in the constructor |
| programming_docs |
cpp std::istream_iterator<T,CharT,Traits,Distance>::operator*, operator-> std::istream\_iterator<T,CharT,Traits,Distance>::operator\*, operator->
=======================================================================
| | | |
| --- | --- | --- |
|
```
const T& operator*() const;
```
| (1) | |
|
```
const T* operator->() const;
```
| (2) | |
Returns a pointer or a reference to the current element.
The behavior is undefined if the iterator is end-of-stream iterator.
### Parameters
(none).
### Return value
A pointer or a reference to the current element.
### Exceptions
May throw implementation-defined exceptions.
cpp std::istream_iterator<T,CharT,Traits,Distance>::operator++, operator++(int) std::istream\_iterator<T,CharT,Traits,Distance>::operator++, operator++(int)
============================================================================
| | | |
| --- | --- | --- |
|
```
istream_iterator& operator++();
```
| (1) | |
|
```
istream_iterator operator++(int);
```
| (2) | |
Reads a value from the underlying stream and stores it into the iterator object. If the read fails, the iterator becomes the end-of-stream iterator.
The behavior is undefined if the iterator is end-of-stream iterator.
### Parameters
(none).
### Return value
1) `*this`.
2) An `istream_iterator` that holds an unchanged value. ### Exceptions
May throw implementation-defined exceptions.
cpp operator==,!=(std::istream_iterator<T,CharT,Traits,Dist>) operator==,!=(std::istream\_iterator<T,CharT,Traits,Dist>)
==========================================================
| Defined in header `[<iterator>](../../header/iterator "cpp/header/iterator")` | | |
| --- | --- | --- |
|
```
template< class T, class CharT, class Traits, class Dist >
bool operator==( const std::istream_iterator<T,CharT,Traits,Dist>& lhs,
const std::istream_iterator<T,CharT,Traits,Dist>& rhs );
```
| (1) | |
|
```
template< class CharT, class Traits >
bool operator!=( const std::istream_iterator<T,CharT,Traits,Dist>& lhs,
const std::istream_iterator<T,CharT,Traits,Dist>& rhs );
```
| (2) | (until C++20) |
|
```
friend bool operator==( const istream_iterator& i, std::default_sentinel_t );
```
| (3) | (since C++20) |
Checks whether both `lhs` and `rhs` are equal. Two stream iterators are equal if both of them are end-of-stream iterators or both of them refer to the same stream.
1) Checks whether `lhs` is *equal to* `rhs`.
2) Checks whether `lhs` is *not equal to* `rhs`.
3) Checks whether `lhs` is an end-of-stream iterator.
This function is not visible to ordinary [unqualified](../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../language/adl "cpp/language/adl") when `std::istream_iterator<T,CharT,Traits,Dist>` is an associated class of the arguments.
| | |
| --- | --- |
| The `!=` operator is [synthesized](../../language/operators#Relational_operators "cpp/language/operators") from `operator==`. | (since C++20) |
### Parameters
| | | |
| --- | --- | --- |
| lhs, rhs | - | stream iterators to compare |
### Return value
1) `true` if `lhs` is *equal to* `rhs`, `false` otherwise.
2) `true` if `lhs` is *not equal to* `rhs`, `false` otherwise.
3) `true` if `lhs` is an end-of-stream iterator, `false` otherwise. ### Exceptions
May throw implementation-defined exceptions.
cpp operator-(std::common_iterator)
operator-(std::common\_iterator)
================================
| | | |
| --- | --- | --- |
|
```
template< std::sized_sentinel_for<I> I2, std::sized_sentinel_for<I> S2 >
requires std::sized_sentinel_for<S, I2>
friend constexpr std::iter_difference_t<I2>
operator-( const common_iterator& x, const std::common_iterator<I2, S2>& y );
```
| | (since C++20) |
Computes the distance between two iterator adaptors. Two sentinels are considered equal.
Let `*var*` denote the underlying `[std::variant](../../utility/variant "cpp/utility/variant")` member object in `[std::common\_iterator](../common_iterator "cpp/iterator/common iterator")`, the behavior is undefined if either `x` or `y` is invalid, i.e. `x.var.valueless_by_exception() || y.var.valueless_by_exception()` is `true`.
This function template is not visible to ordinary [unqualified](../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../language/adl "cpp/language/adl") when `std::common_iterator<I>` is an associated class of the arguments.
### Parameters
| | | |
| --- | --- | --- |
| x, y | - | iterator adaptors to compute the difference of |
### Return value
* `โ0โ` if `x.var` holds an `S` object and `y.var` holds an `S2` object, i.e. both of them hold a sentinel.
* Otherwise, `alt_x - alt_y`, where `alt_x` and `alt_y` are the alternatives held by `x.var` and `y.var`, respectively (either two iterators or one iterator and one sentinel).
### Example
```
#include <algorithm>
#include <iostream>
#include <iterator>
int main()
{
int a[] {0, 1, 2, 3, 4, 5};
using CI = std::common_iterator<
std::counted_iterator<int*>,
std::default_sentinel_t
>;
CI i1{ std::counted_iterator{ a + 1, 2 } };
CI i2{ std::counted_iterator{ a + 1, 3 } };
CI s1{ std::default_sentinel };
CI s2{ std::default_sentinel };
std::cout << (s2 - s1) << ' '
<< (i2 - i1) << ' '
<< (i1 - s1) << '\n';
}
```
Output:
```
0 -1 -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 3574](https://cplusplus.github.io/LWG/issue3574) | C++20 | `variant` was fully constexpr (P2231R1) but `common_iterator` was not | also made constexpr |
### See also
| | |
| --- | --- |
| [operator++operator++(int)](operator_arith "cpp/iterator/common iterator/operator arith")
(C++20) | advances the iterator adaptor (public member function) |
cpp iter_move(std::common_iterator)
iter\_move(std::common\_iterator)
=================================
| | | |
| --- | --- | --- |
|
```
friend std::iter_rvalue_reference_t<I>
iter_move( const std::common_iterator& i )
noexcept(noexcept(ranges::iter_move(std::declval<const I&>()))
requires std::input_iterator<I>;
```
| | (since C++20) |
Casts the result of dereferencing the underlying iterator to its associated rvalue reference type. The behavior is undefined if `i.var` does not hold an `I` object (i.e. an iterator).
The function body is equivalent to: `return std::[ranges::iter\_move](http://en.cppreference.com/w/cpp/iterator/ranges/iter_move)([std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<I>(i.var));`.
This function is not visible to ordinary [unqualified](../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../language/adl "cpp/language/adl") when `std::common_iterator<I,S>` is an associated class of the arguments.
### Parameters
| | | |
| --- | --- | --- |
| i | - | a source iterator adaptor. |
### Return value
An rvalue reference or a prvalue temporary.
### Complexity
Constant.
### Example
```
#include <iomanip>
#include <iostream>
#include <iterator>
#include <string>
#include <vector>
void print(auto const& rem, auto const& v) {
std::cout << rem << "[" << size(v) << "] { ";
for (int o{}; auto const& s : v)
std::cout << (o++ == 0 ? "" : ", ") << quoted(s);
std::cout << " }\n";
}
int main()
{
std::vector<std::string> p { "Andromeda", "Cassiopeia", "Phoenix" }, q;
print("p", p), print("q", q);
using CI = std::common_iterator<
std::counted_iterator<std::vector<std::string>::iterator>,
std::default_sentinel_t
>;
CI last{ std::default_sentinel };
for (CI first{ {p.begin(), 2} }; first != last; ++first) {
q.emplace_back( /* ADL */ iter_move(first) );
}
print("p", p), print("q", q);
}
```
Possible output:
```
p[3] { "Andromeda", "Cassiopeia", "Phoenix" }
q[0] { }
p[3] { "", "", "Phoenix" }
q[2] { "Andromeda", "Cassiopeia" }
```
### See also
| | |
| --- | --- |
| [iter\_move](../ranges/iter_move "cpp/iterator/ranges/iter move")
(C++20) | casts the result of dereferencing an object to its associated rvalue reference type (customization point object) |
| [iter\_move](../counted_iterator/iter_move "cpp/iterator/counted iterator/iter move")
(C++20) | casts the result of dereferencing the underlying iterator to its associated rvalue reference type (function) |
| [move](../../utility/move "cpp/utility/move")
(C++11) | obtains an rvalue reference (function template) |
| [move\_if\_noexcept](../../utility/move_if_noexcept "cpp/utility/move if noexcept")
(C++11) | obtains an rvalue reference if the move constructor does not throw (function template) |
| [forward](../../utility/forward "cpp/utility/forward")
(C++11) | forwards a function argument (function template) |
| [ranges::move](../../algorithm/ranges/move "cpp/algorithm/ranges/move")
(C++20) | moves a range of elements to a new location (niebloid) |
| [ranges::move\_backward](../../algorithm/ranges/move_backward "cpp/algorithm/ranges/move backward")
(C++20) | moves a range of elements to a new location in backwards order (niebloid) |
cpp std::common_iterator<I,S>::common_iterator std::common\_iterator<I,S>::common\_iterator
============================================
| | | |
| --- | --- | --- |
|
```
constexpr common_iterator() requires std::default_initializable<I> = default;
```
| (1) | (since C++20) |
|
```
constexpr common_iterator( I i );
```
| (2) | (since C++20) |
|
```
constexpr common_iterator( S s );
```
| (3) | (since C++20) |
|
```
template< class I2, class S2 >
requires std::convertible_to<const I2&, I> &&
std::convertible_to<const S2&, S>
constexpr common_iterator( const common_iterator<I2, S2>& x );
```
| (4) | (since C++20) |
Constructs a new iterator adaptor, effectively initializes the underlying `[std::variant](http://en.cppreference.com/w/cpp/utility/variant)<I, S>` member object `*var*` to hold an `I` (iterator) or `S` (sentinel) object.
1) Default constructor. Default-initializes `*var*`. After construction, `*var*` holds a value-initialized `I` object. Operations on the resulting iterator adaptor have defined behavior if and only if the corresponding operations on a value-initialized `I` also have defined behavior.
2) After construction, `*var*` holds an `I` object move-constructed from `i`.
3) After construction, `*var*` holds an `S` object move-constructed from `s`.
4) After construction, `*var*` holds an `I` or `S` object initialized from the `I2` or `S2` held by `x.var`, if `x.var` holds that alternative, respectively. The behavior is undefined if `x` is in an invalid state, that is, `x.var.valueless_by_exception()` is equal to `true`. ### Parameters
| | | |
| --- | --- | --- |
| i | - | iterator to adapt |
| s | - | sentinel to adapt |
| x | - | iterator adaptor to copy |
### Example
```
#include <algorithm>
#include <iostream>
#include <iterator>
#include <numeric>
#include <vector>
int main()
{
std::vector v {3,1,4,1,5,9,2};
using CI = std::common_iterator<
std::counted_iterator<std::vector<int>::iterator>,
std::default_sentinel_t
>;
CI unused; // (1)
CI start { std::counted_iterator{std::next(begin(v)), ssize(v)-2} }; // (2)
CI finish { std::default_sentinel }; // (3)
CI first { start }; // (4)
CI last { finish }; // (4)
std::copy(first, last, std::ostream_iterator<int>{std::cout, " "});
std::cout << '\n';
std::common_iterator<
std::counted_iterator<
std::ostream_iterator<double>>,
std::default_sentinel_t>
beg { std::counted_iterator{std::ostream_iterator<double>{std::cout,"; "}, 5} },
end { std::default_sentinel };
std::iota(beg, end, 3.1);
std::cout << '\n';
}
```
Output:
```
1 4 1 5 9
3.1; 4.1; 5.1; 6.1; 7.1;
```
### See also
| | |
| --- | --- |
| [operator=](operator= "cpp/iterator/common iterator/operator=")
(C++20) | assigns another iterator adaptor (public member function) |
cpp std::common_iterator<I,S>::operator*,-> std::common\_iterator<I,S>::operator\*,->
=========================================
| | | |
| --- | --- | --- |
|
```
constexpr decltype(auto) operator*();
```
| (1) | (since C++20) |
|
```
constexpr decltype(auto) operator*() const
requires /*dereferenceable*/<const I>;
```
| (2) | (since C++20) |
|
```
constexpr auto operator->() const
requires /* see description */;
```
| (3) | (since C++20) |
| Helper types | | |
|
```
class /*proxy*/ { // exposition only
std::iter_value_t<I> keep_;
constexpr proxy(std::iter_reference_t<I>&& x)
: keep_(std::move(x)) {}
public:
constexpr const std::iter_value_t<I>* operator->() const noexcept {
return std::addressof(keep_);
}
};
```
| (4) | (since C++20) |
Returns pointer or reference to the current element, or a proxy holding it.
The behavior is undefined if the underlying `[std::variant](../../utility/variant "cpp/utility/variant")` member object `*var*` does not hold an object of type `I`, i.e. `[std::holds\_alternative](http://en.cppreference.com/w/cpp/utility/variant/holds_alternative)<I>(var)` is equal to `false`.
Let `it` denote the iterator of type `I` held by `*var*`, that is `[std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<I>(var)`.
1-2) Returns the result of dereferencing `it`. 3) Returns a pointer or underlying iterator to the current element, or a proxy holding it: * Equivalent to `return it;`, if `I` is a pointer type or if the expression `it.operator->()` is well-formed
* Otherwise, equivalent to `auto&& tmp = \*it; return [std::addressof](http://en.cppreference.com/w/cpp/memory/addressof)(tmp);`, if `[std::iter\_reference\_t](http://en.cppreference.com/w/cpp/iterator/iter_t)<I>` is a reference type,
* Otherwise, equivalent to `return proxy(*it);`, where `*proxy*` is an exposition only class (4).
The expression in the `requires`-clause is equivalent to
`[std::indirectly\_readable](http://en.cppreference.com/w/cpp/iterator/indirectly_readable)<const I> && (
requires(const I& i) { i.operator->(); } ||
[std::is\_reference\_v](http://en.cppreference.com/w/cpp/types/is_reference)<[std::iter\_reference\_t](http://en.cppreference.com/w/cpp/iterator/iter_t)<I>> ||
[std::constructible\_from](http://en.cppreference.com/w/cpp/concepts/constructible_from)<[std::iter\_value\_t](http://en.cppreference.com/w/cpp/iterator/iter_t)<I>, [std::iter\_reference\_t](http://en.cppreference.com/w/cpp/iterator/iter_t)<I>>
)`. ### Parameters
(none).
### Return value
1-2) Reference to the current element, or prvalue temporary. Equivalent to `*it`.
3) Pointer or iterator to the current element or proxy holding it as described above. ### Example
```
#include <algorithm>
#include <complex>
#include <iostream>
#include <iterator>
#include <initializer_list>
using std::complex_literals::operator""i;
int main() {
const auto il = {1i,3.14+2i,3i,4i,5i};
using CI = std::common_iterator<
std::counted_iterator<decltype(il)::iterator>,
std::default_sentinel_t>;
CI ci { std::counted_iterator{
std::next(begin(il), 1), ssize(il) - 1} };
std::cout << *ci << ' ' << ci->real() << '\n';
}
```
Output:
```
(3.14,2) 3.14
```
### 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 3574](https://cplusplus.github.io/LWG/issue3574) | C++20 | `variant` was fully constexpr (P2231R1) but `common_iterator` was not | also made constexpr |
| [LWG 3595](https://cplusplus.github.io/LWG/issue3595) | C++20 | functions of the proxy type lacked constexpr and noexcept | added |
| [LWG 3672](https://cplusplus.github.io/LWG/issue3672) | C++20 | `operator->` might return by reference in usual cases | always returns by value |
### See also
| | |
| --- | --- |
| [(constructor)](common_iterator "cpp/iterator/common iterator/common iterator")
(C++20) | constructs a new iterator adaptor (public member function) |
cpp std::common_iterator<I,S>::operator= std::common\_iterator<I,S>::operator=
=====================================
| | | |
| --- | --- | --- |
|
```
template< class I2, class S2 >
requires std::convertible_to<const I2&, I> &&
std::convertible_to<const S2&, S> &&
std::assignable_from<I&, const I2&> &&
std::assignable_from<S&, const S2&>
constexpr common_iterator& operator=( const common_iterator<I2, S2>& x );
```
| | (since C++20) |
Assigns the underlying `[std::variant](../../utility/variant "cpp/utility/variant")` member object `*var*` from that of `x`.
Let `i` is `x.var.index()`. Then, this assignment is equivalent to:
* `[std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<i>(var) = [std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<i>(x.var)`, if `var.index() == i`,
* `var.emplace<i>([std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<i>(x.var))` otherwise.
The behavior is undefined if `x` is in an invalid state, that is, `x.var.valueless_by_exception()` is equal to `true`.
### Parameters
| | | |
| --- | --- | --- |
| x | - | iterator adaptor to assign from |
### Return value
`*this`.
### Example
```
#include <algorithm>
#include <iostream>
#include <iterator>
#include <initializer_list>
int main() {
const auto il = {1,2,3,4,5,6};
using CI = std::common_iterator<
std::counted_iterator<std::initializer_list<int>::iterator>,
std::default_sentinel_t>;
CI first { std::counted_iterator{std::next(begin(il), 1), ssize(il) - 1} };
const CI first2 { std::counted_iterator{std::next(begin(il), 2), ssize(il) - 2} };
const CI last { std::default_sentinel };
std::copy(first, last, std::ostream_iterator<int>{std::cout, " "});
std::cout << '\n';
first = first2;
std::copy(first, last, std::ostream_iterator<int>{std::cout, " "});
std::cout << '\n';
}
```
Output:
```
2 3 4 5 6
3 4 5 6
```
### 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 3574](https://cplusplus.github.io/LWG/issue3574) | C++20 | `variant` was fully constexpr (P2231R1) but `common_iterator` was not | also made constexpr |
### See also
| | |
| --- | --- |
| [(constructor)](common_iterator "cpp/iterator/common iterator/common iterator")
(C++20) | constructs a new iterator adaptor (public member function) |
cpp iter_swap(std::common_iterator)
iter\_swap(std::common\_iterator)
=================================
| | | |
| --- | --- | --- |
|
```
template< std::indirectly_swappable<I> I2, class S2 >
friend constexpr void
iter_swap( const common_iterator& x,
const std::common_iterator<I2, S2>& y ) noexcept(/*see below*/);
```
| | (since C++20) |
Swaps the objects pointed to by two underlying iterators. The behavior is undefined if `x` does not hold an `I` object or `y` does not hold an `I2` object (i.e. at least one of `x` and `y` does not hold an iterator).
The function body is equivalent to `[ranges::iter\_swap](http://en.cppreference.com/w/cpp/iterator/ranges/iter_swap)([std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<I>(x.var), [std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<I2>(y.var))`.
This function template is not visible to ordinary [unqualified](../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../language/adl "cpp/language/adl") when `std::common_iterator<I,S>` is an associated class of the arguments.
### Parameters
| | | |
| --- | --- | --- |
| x, y | - | the iterators to the elements to swap |
### Return value
(none).
### Complexity
Constant.
### Exceptions
[`noexcept`](../../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept(noexcept([ranges::iter\_swap](http://en.cppreference.com/w/cpp/iterator/ranges/iter_swap)([std::declval](http://en.cppreference.com/w/cpp/utility/declval)<const I&>(), [std::declval](http://en.cppreference.com/w/cpp/utility/declval)<const I2&>())))`
### Example
```
#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>
#include <vector>
int main()
{
std::vector<std::string> v1 { "1", "2", "3", "4", "5" },
v2 { "ฮฑ", "ฮฒ", "ฮณ", "ฮด", "ฮต" };
using CI = std::common_iterator<
std::counted_iterator<std::vector<std::string>::iterator>,
std::default_sentinel_t
>;
CI first1 { std::counted_iterator { v1.begin(), 3 } };
CI first2 { std::counted_iterator { v2.begin(), 4 } };
CI last { std::default_sentinel };
auto print = [&] (auto rem) {
std::cout << rem << "v1 = ";
std::ranges::copy(v1, std::ostream_iterator<std::string>{std::cout, " "});
std::cout << "\nv2 = ";
std::ranges::copy(v2, std::ostream_iterator<std::string>{std::cout, " "});
std::cout << '\n';
};
print("Before iter_swap:\n");
for (; first1 != last && first2 != last; ++first1, ++first2) {
iter_swap( first1, first2 ); // ADL
}
print("After iter_swap:\n");
}
```
Output:
```
Before iter_swap:
v1 = 1 2 3 4 5
v2 = ฮฑ ฮฒ ฮณ ฮด ฮต
After iter_swap:
v1 = ฮฑ ฮฒ ฮณ 4 5
v2 = 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 3574](https://cplusplus.github.io/LWG/issue3574) | C++20 | `variant` was fully constexpr (P2231R1) but `common_iterator` was not | also made constexpr |
### See also
| | |
| --- | --- |
| [swap](../../algorithm/swap "cpp/algorithm/swap") | swaps the values of two objects (function template) |
| [swap\_ranges](../../algorithm/swap_ranges "cpp/algorithm/swap ranges") | swaps two ranges of elements (function template) |
| [iter\_swap](../../algorithm/iter_swap "cpp/algorithm/iter swap") | swaps the elements pointed to by two iterators (function template) |
| [iter\_swap](../ranges/iter_swap "cpp/iterator/ranges/iter swap")
(C++20) | swaps the values referenced by two dereferenceable objects (customization point object) |
| [iter\_swap](../counted_iterator/iter_swap "cpp/iterator/counted iterator/iter swap")
(C++20) | swaps the objects pointed to by two underlying iterators (function template) |
| programming_docs |
cpp operator==(std::common_iterator)
operator==(std::common\_iterator)
=================================
| | | |
| --- | --- | --- |
|
```
template <class I2, std::sentinel_for<I> S2>
requires std::sentinel_for<S, I2>
friend constexpr bool operator==( const common_iterator& x,
const std::common_iterator<I2, S2>& y );
```
| (1) | (since C++20) |
|
```
template <class I2, std::sentinel_for<I> S2>
requires std::sentinel_for<S, I2> && std::equality_comparable_with<I, I2>
friend constexpr bool operator==( const common_iterator& x,
const std::common_iterator<I2, S2>& y );
```
| (2) | (since C++20) |
Compares the iterators and/or sentinels held by underlying `[std::variant](../../utility/variant "cpp/utility/variant")` member objects `*var*`. Two incomparable iterators or two sentinels are considered equal.
The behavior is undefined if either `x` or `y` is in an invalid state, i.e. `x.var.valueless_by_exception() || y.var.valueless_by_exception()` is equal to `true`.
Let `i` be `x.var.index()` and `j` be `y.var.index()`.
1) if `i == j` (i.e. both `x` and `y` hold iterators or both hold sentinels), returns `true`, otherwise returns `[std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<i>(x.var) == [std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<j>(y.var)`;
2) if `i == 1 && j == 1` (i.e. both `x` and `y` hold sentinels), returns `true`, otherwise returns `[std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<i>(x.var) == [std::get](http://en.cppreference.com/w/cpp/utility/variant/get)<j>(y.var)`. The `!=` operator is [synthesized](../../language/operators#Relational_operators "cpp/language/operators") from `operator==`.
These function templates are not visible to ordinary [unqualified](../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../language/adl "cpp/language/adl") when `std::common_iterator<I>` is an associated class of the arguments.
### Parameters
| | | |
| --- | --- | --- |
| x, y | - | iterator adaptors to compare |
### Return value
`true` if underlying iterators and/or sentinels are equal.
### Example
```
#include <algorithm>
#include <iostream>
#include <iterator>
#include <initializer_list>
int main()
{
int a[] {0, 1, 2, 3};
using CI = std::common_iterator<
std::counted_iterator<int*>,
std::default_sentinel_t
>;
CI i1{ std::counted_iterator{ a + 0, 2 } };
CI i2{ std::counted_iterator{ a + 1, 2 } };
CI i3{ std::counted_iterator{ a + 0, 3 } };
CI i4{ std::counted_iterator{ a + 0, 0 } };
CI s1{ std::default_sentinel };
CI s2{ std::default_sentinel };
std::cout << std::boolalpha
<< (i1 == i2) << ' ' // true
<< (i1 == i3) << ' ' // false
<< (i2 == i3) << ' ' // false
<< (s1 == s2) << ' ' // true
<< (i1 == s1) << ' ' // false
<< (i4 == s1) << '\n'; // true
}
```
Output:
```
true false false true false 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 3574](https://cplusplus.github.io/LWG/issue3574) | C++20 | `variant` was fully constexpr (P2231R1) but `common_iterator` was not | also made constexpr |
### See also
| | |
| --- | --- |
| [operator-](operator- "cpp/iterator/common iterator/operator-")
(C++20) | computes the distance between two iterator adaptors (function template) |
cpp std::counted_iterator<I>::counted_iterator std::counted\_iterator<I>::counted\_iterator
============================================
| | | |
| --- | --- | --- |
|
```
constexpr counted_iterator() requires std::default_initializable<I> = default;
```
| (1) | (since C++20) |
|
```
constexpr counted_iterator( I x, std::iter_difference_t<I> n );
```
| (2) | (since C++20) |
|
```
template< class I2 >
requires std::convertible_to<const I2&, I>
constexpr counted_iterator( const counted_iterator<I2>& other );
```
| (3) | (since C++20) |
Constructs a new iterator adaptor.
1) Default constructor. [Value-initializes](../../language/value_initialization "cpp/language/value initialization") the underlying iterator and initialized the underlying *length* with `โ0โ`. Operations on the resulting iterator have defined behavior if and only if the corresponding operations on a value-initialized `I` also have defined behavior.
2) The underlying iterator is initialized with `std::move(x)` and the underlying *length* is initialized with `n`. The behavior is undefined if `n` is negative.
3) The underlying iterator and *length* are initialized with those of `other`. ### Parameters
| | | |
| --- | --- | --- |
| x | - | iterator to adapt |
| n | - | distance to the end |
| other | - | iterator adaptor to convert |
### Example
```
#include <algorithm>
#include <initializer_list>
#include <iostream>
#include <iterator>
int main() {
static constexpr auto pi = {3, 1, 4, 1, 5, 9, 2};
// (1) default constructor:
constexpr std::counted_iterator<std::initializer_list<int>::iterator> i1{};
static_assert(i1 == std::default_sentinel);
static_assert(i1.count() == 0);
// (2) initializes the iterator and length respectively:
constexpr std::counted_iterator<std::initializer_list<int>::iterator> i2{
pi.begin(), pi.size() - 2
};
static_assert(i2.count() == 5);
static_assert(*i2 == 3 && i2[1] == 1);
// (3) converting-constructor:
std::counted_iterator<std::initializer_list<const int>::iterator> i3{i2};
std::ranges::copy(i3, std::default_sentinel,
std::ostream_iterator<const int>{std::cout, " "});
}
```
Output:
```
3 1 4 1 5
```
### See also
| | |
| --- | --- |
| [operator=](operator= "cpp/iterator/counted iterator/operator=")
(C++20) | assigns another iterator adaptor (public member function) |
cpp operator-(std::counted_iterator)
operator-(std::counted\_iterator)
=================================
| | | |
| --- | --- | --- |
|
```
template< std::common_with<I> I2 >
friend constexpr std::iter_difference_t<I2> operator-(
const counted_iterator& x, const counted_iterator<I2>& y );
```
| | (since C++20) |
Computes the distance between two iterator adaptors.
The behavior is undefined if `x` and `y` do not point to elements of the same sequence. That is, there must exist some `n` such that `[std::next](http://en.cppreference.com/w/cpp/iterator/next)(x.base(), x.count() + n)` and `[std::next](http://en.cppreference.com/w/cpp/iterator/next)(y.base(), y.count() + n)` refer to the same element.
This function template is not visible to ordinary [unqualified](../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../language/adl "cpp/language/adl") when `std::counted_iterator<I>` is an associated class of the arguments.
### Parameters
| | | |
| --- | --- | --- |
| x, y | - | iterator adaptors to compute the difference of |
### Return value
`y.count() - x.count()`.
### Notes
Since the *length* counts down, not up, the order of the arguments of `operator-` in the underlying expression is reversed, i.e. `y` is *lhs* and `x` is *rhs*.
### Example
```
#include <initializer_list>
#include <iterator>
int main()
{
static constexpr auto v = {1, 2, 3, 4, 5, 6};
constexpr std::counted_iterator<std::initializer_list<int>::iterator>
it1 {v.begin(), 5},
it2 {it1 + 3},
it3 {v.begin(), 2};
static_assert(it1 - it2 == -3);
static_assert(it2 - it1 == +3);
// static_assert(it1 - it3 == -3); // UB: operands of operator- do not refer to
// elements of the same sequence
}
```
### See also
| | |
| --- | --- |
| [operator++operator++(int)operator+=operator+operator--operator--(int)operator-=operator-](operator_arith "cpp/iterator/counted iterator/operator arith")
(C++20) | advances or decrements the iterator (public member function) |
| [operator+](operator_plus_ "cpp/iterator/counted iterator/operator+")
(C++20) | advances the iterator (function template) |
| [operator-(std::default\_sentinel\_t)](operator-2 "cpp/iterator/counted iterator/operator-2")
(C++20) | computes the signed distance to the end (function template) |
cpp std::counted_iterator<I>::base std::counted\_iterator<I>::base
===============================
| | | |
| --- | --- | --- |
|
```
constexpr const I& base() const & noexcept;
```
| (1) | (since C++20) |
|
```
constexpr I base() &&;
```
| (2) | (since C++20) |
Returns the underlying base iterator.
1) Returns a reference to the underlying iterator.
2) Move constructs the return value from the underlying iterator. ### Parameters
(none).
### Return value
1) A reference to the underlying iterator.
1) An iterator move constructed from the underlying iterator. ### Exceptions
May throw implementation-defined exceptions.
### Example
```
#include <algorithm>
#include <iostream>
#include <iterator>
#include <type_traits>
#include <vector>
int main()
{
std::vector<int> v = { 0, 1, 2, 3, 4 };
std::reverse_iterator<std::vector<int>::iterator> reverse{v.rbegin()};
std::counted_iterator counted{reverse, 3};
static_assert(std::is_same<decltype(counted.base()),
std::reverse_iterator<std::vector<int>::iterator>>{});
std::cout << "Print with reverse_iterator: ";
for (auto r = counted.base(); r != v.rend(); ++r)
std::cout << *r << ' ';
std::cout << '\n';
std::cout << "Print with counted_iterator: ";
for (; counted != std::default_sentinel; ++counted)
std::cout << counted[0] << ' ';
std::cout << '\n';
}
```
Output:
```
Print with reverse_iterator: 4 3 2 1 0
Print with counted_iterator: 4 3 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 3391](https://cplusplus.github.io/LWG/issue3391) | C++20 | the const version of `base` returns a copy of the underlying iterator | returns a reference |
| [LWG 3593](https://cplusplus.github.io/LWG/issue3593) | C++20 | the const version of `base` returns a reference but might not be noexcept | made noexcept |
### See also
| | |
| --- | --- |
| [operator\*operator->](operator* "cpp/iterator/counted iterator/operator*")
(C++20) | accesses the pointed-to element (public member function) |
| [count](count "cpp/iterator/counted iterator/count")
(C++20) | returns the distance to the end (public member function) |
cpp iter_move(std::counted_iterator)
iter\_move(std::counted\_iterator)
==================================
| | | |
| --- | --- | --- |
|
```
friend constexpr std::iter_rvalue_reference_t<I>
iter_move( const std::counted_iterator& i )
noexcept(noexcept(ranges::iter_move(i.base())))
requires std::input_iterator<I>;
```
| | (since C++20) |
Casts the result of dereferencing the underlying iterator to its associated rvalue reference type. The behavior is undefined if `i.count()` is equal to `โ0โ`.
The function body is equivalent to `return [ranges::iter\_move](http://en.cppreference.com/w/cpp/iterator/ranges/iter_move)(i.base());`.
This function is not visible to ordinary [unqualified](../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../language/adl "cpp/language/adl") when `[std::counted\_iterator](http://en.cppreference.com/w/cpp/iterator/counted_iterator)<I>` is an associated class of the arguments.
### Parameters
| | | |
| --- | --- | --- |
| i | - | a source iterator adaptor |
### Return value
An rvalue reference or a prvalue temporary.
### Complexity
Constant.
### Example
```
#include <iomanip>
#include <iostream>
#include <iterator>
#include <string>
#include <vector>
void print(auto const& rem, auto const& v) {
for (std::cout << rem << "[" << size(v) << "] { "; auto const& s : v)
std::cout << quoted(s) << " ";
std::cout << "}\n";
}
int main()
{
std::vector<std::string> p { "Alpha", "Bravo", "Charlie" }, q;
print("p", p), print("q", q);
using RI = std::counted_iterator<std::vector<std::string>::iterator>;
for (RI iter{ p.begin(), 2 }; iter != std::default_sentinel; ++iter) {
q.emplace_back( /* ADL */ iter_move(iter) );
}
print("p", p), print("q", q);
}
```
Possible output:
```
p[3] { "Alpha" "Bravo" "Charlie" }
q[0] { }
p[3] { "" "" "Charlie" }
q[2] { "Alpha" "Bravo" }
```
### See also
| | |
| --- | --- |
| [iter\_move](../ranges/iter_move "cpp/iterator/ranges/iter move")
(C++20) | casts the result of dereferencing an object to its associated rvalue reference type (customization point object) |
| [iter\_swap](iter_swap "cpp/iterator/counted iterator/iter swap")
(C++20) | swaps the objects pointed to by two underlying iterators (function template) |
| [move](../../utility/move "cpp/utility/move")
(C++11) | obtains an rvalue reference (function template) |
| [move\_if\_noexcept](../../utility/move_if_noexcept "cpp/utility/move if noexcept")
(C++11) | obtains an rvalue reference if the move constructor does not throw (function template) |
| [forward](../../utility/forward "cpp/utility/forward")
(C++11) | forwards a function argument (function template) |
| [ranges::move](../../algorithm/ranges/move "cpp/algorithm/ranges/move")
(C++20) | moves a range of elements to a new location (niebloid) |
| [ranges::move\_backward](../../algorithm/ranges/move_backward "cpp/algorithm/ranges/move backward")
(C++20) | moves a range of elements to a new location in backwards order (niebloid) |
cpp std::counted_iterator<I>::operator[] std::counted\_iterator<I>::operator[]
=====================================
| | | |
| --- | --- | --- |
|
```
constexpr decltype(auto) operator[]( std::iter_difference_t<I> n ) const
requires std::random_access_iterator<I>;
```
| | (since C++20) |
Accesses the element at specified relative location. The behavior is undefined if `n` is not less than the recorded distance to the end.
### Parameters
| | | |
| --- | --- | --- |
| n | - | position relative to current location |
### Return value
`this->base()[n]`.
### Example
```
#include <iostream>
#include <iterator>
#include <array>
#include <list>
int main()
{
std::array array{'A', 'B', 'C', 'D', 'E'};
std::counted_iterator it{ array.begin() + 1, /*count:*/ 3 };
for (int i{}; i != it.count(); ++i)
std::cout << it[i] << ' ';
std::cout << '\n';
for (int i{}; i != it.count(); ++i)
it[i] += ('E' - 'A');
for (int i{}; i != it.count(); ++i)
std::cout << it[i] << ' ';
std::cout << '\n';
std::list list {'X', 'Y', 'Z', 'W'};
std::counted_iterator it2{ list.begin(), 3 };
// char x = it2[0]; // Error: requirement `random_access_iterator` was not satisfied.
std::cout << *it2 << '\n'; // OK
}
```
Output:
```
B C D
F G H
X
```
### See also
| | |
| --- | --- |
| [operator\*operator->](operator* "cpp/iterator/counted iterator/operator*")
(C++20) | accesses the pointed-to element (public member function) |
cpp std::counted_iterator<I>::count std::counted\_iterator<I>::count
================================
| | | |
| --- | --- | --- |
|
```
constexpr std::iter_difference_t<I> count() const noexcept;
```
| | (since C++20) |
Returns the underlying *length* that is the distance to the end.
### Parameters
(none).
### Return value
the underlying *length*.
### Example
```
#include <iostream>
#include <iterator>
int main()
{
constexpr static auto il = { 1, 2, 3, 4, 5 };
constexpr std::counted_iterator i1{il.begin() + 1, 3};
static_assert(i1.count() == 3);
for (auto i2{i1}; std::default_sentinel != i2; ++i2)
std::cout << *i2 << ' ';
std::cout << '\n';
}
```
Output:
```
2 3 4
```
### See also
| | |
| --- | --- |
| [base](base "cpp/iterator/counted iterator/base")
(C++20) | accesses the underlying iterator (public member function) |
cpp std::counted_iterator<I>::operator*,-> std::counted\_iterator<I>::operator\*,->
========================================
| | | |
| --- | --- | --- |
|
```
constexpr decltype(auto) operator*();
```
| (1) | (since C++20) |
|
```
constexpr decltype(auto) operator*() const
requires /*dereferenceable*/<const I>;
```
| (2) | (since C++20) |
|
```
constexpr auto operator->() const noexcept
requires std::contiguous_iterator<I>;
```
| (3) | (since C++20) |
1-2) Returns a reference to the current element. The behavior is undefined if `this->count() <= 0`. The function's body is equivalent to `return *current;`.
3) Returns a pointer to the current element. The function's body is equivalent to `return [std::to\_address](http://en.cppreference.com/w/cpp/memory/to_address)(current);`. ### Parameters
(none).
### Return value
Reference or pointer to the current element.
### Example
```
#include <complex>
#include <iostream>
#include <iterator>
using std::operator""i;
int main()
{
const auto il = { 1.i, 2.i, 3.i, 4.i, 5.i };
for (std::counted_iterator i{il.begin() + 1, 3}; i != std::default_sentinel; ++i)
std::cout << *i << ' ';
std::cout << '\n';
for (std::counted_iterator i{il.begin() + 1, 3}; i != std::default_sentinel; ++i)
std::cout << i->imag() << ' ';
std::cout << '\n';
}
```
Output:
```
(0,2) (0,3) (0,4)
2 3 4
```
### See also
| | |
| --- | --- |
| [operator[]](operator_at "cpp/iterator/counted iterator/operator at")
(C++20) | accesses an element by index (public member function) |
cpp operator+(std::counted_iterator)
operator+(std::counted\_iterator)
=================================
| | | |
| --- | --- | --- |
|
```
friend constexpr counted_iterator operator+(
std::iter_difference_t<I> n, const counted_iterator& x )
requires std::random_access_iterator<I>;
```
| | (since C++20) |
Returns an iterator adaptor which is advanced by `n`. The behavior is undefined if `n` is greater than the length recorded within `x` (i.e. if `x + n` result in undefined behavior).
This function is not visible to ordinary [unqualified](../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../language/adl "cpp/language/adl") when `std::counted_iterator<I>` is an associated class of the arguments.
### Parameters
| | | |
| --- | --- | --- |
| n | - | the number of positions to increment the iterator |
| x | - | the iterator adaptor to increment |
### Return value
An iterator adaptor equal to `x + n`.
### Example
```
#include <iostream>
#include <iterator>
#include <list>
#include <vector>
int main()
{
std::vector v { 0, 1, 2, 3, 4, 5 };
std::counted_iterator<std::vector<int>::iterator> p{ v.begin() + 1, 4 };
std::cout << "*p:" << *p << ", count:" << p.count() << '\n';
std::counted_iterator<std::vector<int>::iterator> q{ 2 + p };
std::cout << "*q:" << *q << ", count:" << q.count() << '\n';
std::list l { 6, 7, 8, 9 };
std::counted_iterator<std::list<int>::iterator> r{ l.begin(), 3 };
std::cout << "*r:" << *r << ", count:" << r.count() << '\n';
// auto s { 2 + r }; // error: the underlying iterator does
// not model std::random_access_iterator
}
```
Output:
```
*p:1, count:4
*q:3, count:2
*r:6, count:3
```
### See also
| | |
| --- | --- |
| [operator++operator++(int)operator+=operator+operator--operator--(int)operator-=operator-](operator_arith "cpp/iterator/counted iterator/operator arith")
(C++20) | advances or decrements the iterator (public member function) |
| [operator-](operator- "cpp/iterator/counted iterator/operator-")
(C++20) | computes the distance between two iterator adaptors (function template) |
| [operator-(std::default\_sentinel\_t)](operator-2 "cpp/iterator/counted iterator/operator-2")
(C++20) | computes the signed distance to the end (function template) |
| programming_docs |
cpp std::counted_iterator<I>::operator= std::counted\_iterator<I>::operator=
====================================
| | | |
| --- | --- | --- |
|
```
template <class I2>
requires std::assignable_from<I&, const I2&>
constexpr counted_iterator& operator=( const counted_iterator<I2>& other );
```
| | (since C++20) |
The underlying iterator and *length* are assigned with those of `other`.
### Parameters
| | | |
| --- | --- | --- |
| other | - | iterator adaptor to assign from |
### Return value
`*this`.
### Example
```
#include <algorithm>
#include <cassert>
#include <initializer_list>
#include <iterator>
int main()
{
auto a = {3, 1, 4, 1, 5, 9, 2};
std::counted_iterator<std::initializer_list<int>::iterator> p(begin(a), size(a)-2);
std::counted_iterator<std::initializer_list<int>::iterator> q;
assert(q.count() == 0);
assert(q.count() != p.count());
q = p;
assert(q.count() == p.count());
assert(std::ranges::equal(p, std::default_sentinel, q, std::default_sentinel));
}
```
### See also
| | |
| --- | --- |
| [(constructor)](counted_iterator "cpp/iterator/counted iterator/counted iterator")
(C++20) | constructs a new iterator adaptor (public member function) |
cpp iter_swap(std::counted_iterator)
iter\_swap(std::counted\_iterator)
==================================
| | | |
| --- | --- | --- |
|
```
template< std::indirectly_swappable<I> I2 >
friend constexpr void
iter_swap( const counted_iterator& x, const std::counted_iterator<I2>& y )
noexcept(noexcept(ranges::iter_swap(x.base(), y.base())));
```
| | (since C++20) |
Swaps the objects pointed to by two underlying iterators. The behavior is undefined if either `x.count()` or `y.count()` is equal to `โ0โ`.
The function body is equivalent to: `[ranges::iter\_swap](http://en.cppreference.com/w/cpp/iterator/ranges/iter_swap)(x.base(), y.base());`.
This function template is not visible to ordinary [unqualified](../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../language/adl "cpp/language/adl") when `[std::counted\_iterator](http://en.cppreference.com/w/cpp/iterator/counted_iterator)<I>` is an associated class of the arguments.
### Parameters
| | | |
| --- | --- | --- |
| x, y | - | iterator adaptors to the elements to swap |
### Return value
(none).
### Complexity
Constant.
### Example
```
#include <iostream>
#include <iterator>
#include <list>
#include <vector>
int main()
{
std::vector p { 1, 2, 3, 4 },
q { 5, 6, 7, 8 };
std::counted_iterator<std::vector<int>::iterator> ip { p.begin(), 2 };
std::counted_iterator<std::vector<int>::iterator> iq { q.begin(), 3 };
std::cout << *ip << ' ' << *iq << '\n';
iter_swap(ip, iq); // ADL
std::cout << *ip << ' ' << *iq << '\n';
std::list x {0, 1, 3};
std::counted_iterator<std::list<int>::iterator> ix { x.begin(), 2 };
// iter_swap(ip, ix); // error: not indirectly swappable
}
```
Output:
```
1 5
5 1
```
### See also
| | |
| --- | --- |
| [swap](../../algorithm/swap "cpp/algorithm/swap") | swaps the values of two objects (function template) |
| [swap\_ranges](../../algorithm/swap_ranges "cpp/algorithm/swap ranges") | swaps two ranges of elements (function template) |
| [iter\_swap](../../algorithm/iter_swap "cpp/algorithm/iter swap") | swaps the elements pointed to by two iterators (function template) |
| [iter\_swap](../ranges/iter_swap "cpp/iterator/ranges/iter swap")
(C++20) | swaps the values referenced by two dereferenceable objects (customization point object) |
| [iter\_move](iter_move "cpp/iterator/counted iterator/iter move")
(C++20) | casts the result of dereferencing the underlying iterator to its associated rvalue reference type (function) |
cpp operator==,<=>(std::counted_iterator)
operator==,<=>(std::counted\_iterator)
======================================
| | | |
| --- | --- | --- |
|
```
template< std::common_with<I> I2 >
friend constexpr bool operator==(
const counted_iterator& x, const counted_iterator<I2>& y );
```
| (1) | (since C++20) |
|
```
template< std::common_with<I> I2 >
friend constexpr strong_ordering operator<=>(
const counted_iterator& x, const counted_iterator<I2>& y );
```
| (2) | (since C++20) |
Compares the underlying lengths (i.e. distances to the end).
1) Checks if the underlying lengths are equal.
2) Compares the underlying lengths with operator `<=>`. The behavior is undefined if `x` and `y` do not point to elements of the same sequence. That is, there must exist some `n` such that `[std::next](http://en.cppreference.com/w/cpp/iterator/next)(x.base(), x.count() + n)` and `[std::next](http://en.cppreference.com/w/cpp/iterator/next)(y.base(), y.count() + n)` refer to the same element.
The `<`, `<=`, `>`, `>=`, and `!=` operators are [synthesized](../../language/operators#Relational_operators "cpp/language/operators") from `operator<=>` and `operator==` respectively.
This function template is not visible to ordinary [unqualified](../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../language/adl "cpp/language/adl") when `std::counted_iterator<I>` is an associated class of the arguments.
### Parameters
| | | |
| --- | --- | --- |
| x, y | - | iterator adaptors. |
### Return value
1) `x.count() == y.count()`
2) `y.count() <=> x.count()`
### Notes
Since the *length* counts down, not up, the order of the arguments of `operator<=>` in the underlying comparison expression is reversed, i.e. `y` is *lhs*, `x` is *rhs*.
### Example
```
#include <initializer_list>
#include <iterator>
int main()
{
static constexpr auto v = {1, 2, 3, 4, 5, 6};
constexpr std::counted_iterator<std::initializer_list<int>::iterator>
it1 {v.begin(), 5},
it2 {v.begin(), 5},
it3 {v.begin() + 1, 4},
it4 {v.begin(), 0};
static_assert( it1 == it2 );
static_assert( it2 != it3 );
static_assert( it2 < it3 );
static_assert( it1 <= it2 );
static_assert( it3 != std::default_sentinel );
static_assert( it4 == std::default_sentinel );
// it2 == std::counted_iterator{v.begin(), 4}; // UB: operands do not refer to
// elements of the same sequence
}
```
### See also
| | |
| --- | --- |
| [operator==(std::default\_sentinel)](operator_cmp2 "cpp/iterator/counted iterator/operator cmp2")
(C++20) | checks if the distance to the end is equal to `โ0โ` (function template) |
| [operator+](operator_plus_ "cpp/iterator/counted iterator/operator+")
(C++20) | advances the iterator (function template) |
| [operator-](operator- "cpp/iterator/counted iterator/operator-")
(C++20) | computes the distance between two iterator adaptors (function template) |
cpp operator==(std::counted_iterator<I>, std::default_sentinel_t)
operator==(std::counted\_iterator<I>, std::default\_sentinel\_t)
================================================================
| | | |
| --- | --- | --- |
|
```
friend constexpr bool operator==(
const counted_iterator& x, std::default_sentinel_t );
```
| | (since C++20) |
Checks if the underlying *length* (i.e. distance to the end) is equal to `โ0โ`.
This function template is not visible to ordinary [unqualified](../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../language/adl "cpp/language/adl") when `std::counted_iterator<I>` is an associated class of the arguments.
The `!=` operator is [synthesized](../../language/operators#Relational_operators "cpp/language/operators") from `operator==`.
### Parameters
| | | |
| --- | --- | --- |
| x | - | an iterator adaptor |
### Return value
`true` if `x.count()` is equal to `โ0โ`, `false` otherwise.
### Example
```
#include <initializer_list>
#include <iterator>
int main()
{
static constexpr auto v = {1, 2, 3, 4};
constexpr std::counted_iterator<std::initializer_list<int>::iterator>
it1 {v.begin(), 3},
it2 {v.begin(), 0};
static_assert( it1 != std::default_sentinel );
static_assert( it2 == std::default_sentinel );
static_assert( std::default_sentinel != it1 );
static_assert( std::default_sentinel == it2 );
}
```
### See also
| | |
| --- | --- |
| [operator==operator<=>](operator_cmp "cpp/iterator/counted iterator/operator cmp")
(C++20) | compares the distances to the end (function template) |
cpp std::ostream_iterator<T,CharT,Traits>::~ostream_iterator std::ostream\_iterator<T,CharT,Traits>::~ostream\_iterator
==========================================================
| | | |
| --- | --- | --- |
|
```
~ostream_iterator()
```
| | |
Destructs the iterator. Does not affect the associated output stream.
cpp std::ostream_iterator<T,CharT,Traits>::ostream_iterator std::ostream\_iterator<T,CharT,Traits>::ostream\_iterator
=========================================================
| | | |
| --- | --- | --- |
|
```
ostream_iterator( ostream_type& stream, const CharT* delim );
```
| (1) | |
|
```
ostream_iterator( ostream_type& stream );
```
| (2) | |
1) Constructs the iterator with `stream` as the associated stream and `delim` as the delimiter.
2) Constructs the iterator with `stream` as the associated stream and a null pointer as the delimiter. ### Parameters
| | | |
| --- | --- | --- |
| stream | - | the output stream to be accessed by this iterator |
| delim | - | the null-terminated character string to be inserted into the stream after each output |
### Example
```
#include <iostream>
#include <iterator>
#include <algorithm>
#include <numeric>
int main()
{
std::ostream_iterator<char> oo {std::cout};
std::ostream_iterator<int> i1 {std::cout, ", "};
std::fill_n(i1, 5, -1);
*oo++ = '\n';
std::ostream_iterator<double> i2 {std::cout, "; "};
*i2++ = 3.14;
*i2++ = 2.71;
*oo++ = '\n';
std::common_iterator<std::counted_iterator<std::ostream_iterator<float>>,
std::default_sentinel_t>
first { std::counted_iterator{std::ostream_iterator<float>{std::cout," ~ "}, 5} },
last { std::default_sentinel };
std::iota(first, last, 2.2);
*oo++ = '\n';
}
```
Output:
```
-1, -1, -1, -1, -1,
3.14; 2.71;
2.2 ~ 3.2 ~ 4.2 ~ 5.2 ~ 6.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 |
| --- | --- | --- | --- |
| [P2325R3](https://wg21.link/P2325R3) | C++20 | default constructor was provided as C++20 iteratorsmust be [`default_initializable`](../../concepts/default_initializable "cpp/concepts/default initializable") | removed along with the requirement |
cpp std::ostream_iterator<T,CharT,Traits>::operator* std::ostream\_iterator<T,CharT,Traits>::operator\*
==================================================
| | | |
| --- | --- | --- |
|
```
ostream_iterator& operator*();
```
| | |
Does nothing, this member function is provided to satisfy the requirements of [LegacyOutputIterator](../../named_req/outputiterator "cpp/named req/OutputIterator").
It returns the iterator itself, which makes it possible to use code such as `*iter = value` to output (insert) the value into the underlying stream.
### Parameters
(none).
### Return value
`*this`.
cpp std::ostream_iterator<T,CharT,Traits>::operator= std::ostream\_iterator<T,CharT,Traits>::operator=
=================================================
| | | |
| --- | --- | --- |
|
```
ostream_iterator& operator=( const T& value );
```
| | |
Inserts `value` into the associated stream, then inserts the delimiter, if one was specified at construction time.
If `out_stream` is a pointer to the associated `[std::basic\_ostream](../../io/basic_ostream "cpp/io/basic ostream")` and `delim` is the delimiter specified at the construction of this object, then the effect is equivalent to.
`*out_stream << value; if(delim != 0) *out_stream << delim; return *this;`
### Parameters
| | | |
| --- | --- | --- |
| value | - | the object to insert |
### Return value
`*this`.
### Notes
`T` can be any class with a user-defined operator<<
### Example
```
#include <iostream>
#include <iterator>
int main()
{
std::ostream_iterator<int> i1(std::cout, ", ");
*i1++ = 1; // usual form, used by standard algorithms
*++i1 = 2;
i1 = 3; // neither * nor ++ are necessary
std::ostream_iterator<double> i2(std::cout);
i2 = 3.14;
}
```
Output:
```
1, 2, 3, 3.14
```
cpp std::ostream_iterator<T,CharT,Traits>::operator++ std::ostream\_iterator<T,CharT,Traits>::operator++
==================================================
| | | |
| --- | --- | --- |
|
```
ostream_iterator& operator++();
```
| | |
|
```
ostream_iterator& operator++( int );
```
| | |
Does nothing. These operator overloads are provided to satisfy the requirements of [LegacyOutputIterator](../../named_req/outputiterator "cpp/named req/OutputIterator"). They make it possible for the expressions `*iter++=value` and `*++iter=value` to be used to output (insert) a value into the underlying stream.
### Parameters
(none).
### Return value
`*this`.
cpp std::popcount std::popcount
=============
| Defined in header `[<bit>](../header/bit "cpp/header/bit")` | | |
| --- | --- | --- |
|
```
template< class T >
constexpr int popcount( T x ) noexcept;
```
| | (since C++20) |
Returns the number of 1 bits in the value of `x`.
This overload participates in overload resolution only if `T` is an unsigned integer type (that is, `unsigned char`, `unsigned short`, `unsigned int`, `unsigned long`, `unsigned long long`, or an extended unsigned integer type).
### Parameters
| | | |
| --- | --- | --- |
| x | - | value of unsigned integer type |
### Return value
The number of 1 bits in the value of x.
### Notes
| [Feature-test](../utility/feature_test "cpp/utility/feature test") macro |
| --- |
| [`__cpp_lib_bitops`](../feature_test#Library_features "cpp/feature test") |
### Example
```
#include <bit>
#include <bitset>
#include <cstdint>
#include <iostream>
int main()
{
for (const std::uint8_t i : { 0, 0b11111111, 0b00011101 }) {
std::cout << "popcount( " << std::bitset<8>(i) << " ) = "
<< std::popcount(i) << '\n';
}
}
```
Output:
```
popcount( 00000000 ) = 0
popcount( 11111111 ) = 8
popcount( 00011101 ) = 4
```
### See also
| | |
| --- | --- |
| [countl\_zero](countl_zero "cpp/numeric/countl zero")
(C++20) | counts the number of consecutive 0 bits, starting from the most significant bit (function template) |
| [countl\_one](countl_one "cpp/numeric/countl one")
(C++20) | counts the number of consecutive 1 bits, starting from the most significant bit (function template) |
| [countr\_zero](countr_zero "cpp/numeric/countr zero")
(C++20) | counts the number of consecutive 0 bits, starting from the least significant bit (function template) |
| [countr\_one](countr_one "cpp/numeric/countr one")
(C++20) | counts the number of consecutive 1 bits, starting from the least significant bit (function template) |
| [has\_single\_bit](has_single_bit "cpp/numeric/has single bit")
(C++20) | checks if a number is an integral power of two (function template) |
| [count](../utility/bitset/count "cpp/utility/bitset/count") | returns the number of bits set to `true` (public member function of `std::bitset<N>`) |
| [allanynone](../utility/bitset/all_any_none "cpp/utility/bitset/all any none")
(C++11) | checks if all, any or none of the bits are set to `true` (public member function of `std::bitset<N>`) |
cpp std::lcm std::lcm
========
| Defined in header `[<numeric>](../header/numeric "cpp/header/numeric")` | | |
| --- | --- | --- |
|
```
template< class M, class N >
constexpr std::common_type_t<M, N> lcm( M m, N n );
```
| | (since C++17) |
Computes the least common multiple of the integers `m` and `n`.
### Parameters
| | | |
| --- | --- | --- |
| m, n | - | integer values |
### Return value
If either `m` or `n` is zero, returns zero. Otherwise, returns the least common multiple of `|m|` and `|n|`.
### Remarks
If either `M` or `N` is not an integer type, or if either is (possibly cv-qualified) `bool`, the program is ill-formed.
The behavior is undefined if `|m|`, `|n|`, or the least common multiple of `|m|` and `|n|` is not representable as a value of type `[std::common\_type\_t](http://en.cppreference.com/w/cpp/types/common_type)<M, N>`.
### Exceptions
Throws no exceptions.
### Notes
| [Feature-test](../utility/feature_test "cpp/utility/feature test") macro |
| --- |
| [`__cpp_lib_gcd_lcm`](../feature_test#Library_features "cpp/feature test") |
### Example
```
#include <numeric>
#include <iostream>
#define OUT(...) std::cout << #__VA_ARGS__ << " = " << __VA_ARGS__ << '\n'
constexpr auto lcm(auto x, auto y) {
return std::lcm(x,y);
}
constexpr auto lcm(auto head, auto...tail) {
return std::lcm(head, lcm(tail...));
}
int main() {
constexpr int p {2 * 2 * 3};
constexpr int q {2 * 3 * 3};
static_assert(2 * 2 * 3 * 3 == std::lcm(p, q));
static_assert(225 == std::lcm(45, 75));
OUT(lcm(2*3, 3*4, 4*5));
OUT(lcm(2*3*4, 3*4*5, 4*5*6));
OUT(lcm(2*3*4, 3*4*5, 4*5*6, 5*6*7));
}
```
Output:
```
lcm(2*3, 3*4, 4*5) = 60
lcm(2*3*4, 3*4*5, 4*5*6) = 120
lcm(2*3*4, 3*4*5, 4*5*6, 5*6*7) = 840
```
### See also
| | |
| --- | --- |
| [gcd](gcd "cpp/numeric/gcd")
(C++17) | `constexpr` function template returning the greatest common divisor of two integers (function template) |
cpp Mathematical special functions (since C++17)
Mathematical special functions (since C++17)
============================================
The Mathematical Special Functions library was originally part of Library TR1 ISO/IEC TR 19768:2007, then published as an independent ISO standard, ISO/IEC 29124:2010, and finally merged to ISO C++ as of C++17.
See [Mathematical special functions](https://en.cppreference.com/w/cpp/experimental/special_functions "cpp/experimental/special functions") for the ISO/IEC 29124:2010 version of this library.
### Functions
| Defined in header `[<cmath>](../header/cmath "cpp/header/cmath")` |
| --- |
| [assoc\_laguerreassoc\_laguerrefassoc\_laguerrel](special_functions/assoc_laguerre "cpp/numeric/special functions/assoc laguerre")
(C++17)(C++17)(C++17) | associated Laguerre polynomials (function) |
| [assoc\_legendreassoc\_legendrefassoc\_legendrel](special_functions/assoc_legendre "cpp/numeric/special functions/assoc legendre")
(C++17)(C++17)(C++17) | associated Legendre polynomials (function) |
| [betabetafbetal](special_functions/beta "cpp/numeric/special functions/beta")
(C++17)(C++17)(C++17) | beta function (function) |
| [comp\_ellint\_1comp\_ellint\_1fcomp\_ellint\_1l](special_functions/comp_ellint_1 "cpp/numeric/special functions/comp ellint 1")
(C++17)(C++17)(C++17) | (complete) elliptic integral of the first kind (function) |
| [comp\_ellint\_2comp\_ellint\_2fcomp\_ellint\_2l](special_functions/comp_ellint_2 "cpp/numeric/special functions/comp ellint 2")
(C++17)(C++17)(C++17) | (complete) elliptic integral of the second kind (function) |
| [comp\_ellint\_3comp\_ellint\_3fcomp\_ellint\_3l](special_functions/comp_ellint_3 "cpp/numeric/special functions/comp ellint 3")
(C++17)(C++17)(C++17) | (complete) elliptic integral of the third kind (function) |
| [cyl\_bessel\_icyl\_bessel\_ifcyl\_bessel\_il](special_functions/cyl_bessel_i "cpp/numeric/special functions/cyl bessel i")
(C++17)(C++17)(C++17) | regular modified cylindrical Bessel functions (function) |
| [cyl\_bessel\_jcyl\_bessel\_jfcyl\_bessel\_jl](special_functions/cyl_bessel_j "cpp/numeric/special functions/cyl bessel j")
(C++17)(C++17)(C++17) | cylindrical Bessel functions (of the first kind) (function) |
| [cyl\_bessel\_kcyl\_bessel\_kfcyl\_bessel\_kl](special_functions/cyl_bessel_k "cpp/numeric/special functions/cyl bessel k")
(C++17)(C++17)(C++17) | irregular modified cylindrical Bessel functions (function) |
| [cyl\_neumanncyl\_neumannfcyl\_neumannl](special_functions/cyl_neumann "cpp/numeric/special functions/cyl neumann")
(C++17)(C++17)(C++17) | cylindrical Neumann functions (function) |
| [ellint\_1ellint\_1fellint\_1l](special_functions/ellint_1 "cpp/numeric/special functions/ellint 1")
(C++17)(C++17)(C++17) | (incomplete) elliptic integral of the first kind (function) |
| [ellint\_2ellint\_2fellint\_2l](special_functions/ellint_2 "cpp/numeric/special functions/ellint 2")
(C++17)(C++17)(C++17) | (incomplete) elliptic integral of the second kind (function) |
| [ellint\_3ellint\_3fellint\_3l](special_functions/ellint_3 "cpp/numeric/special functions/ellint 3")
(C++17)(C++17)(C++17) | (incomplete) elliptic integral of the third kind (function) |
| [expintexpintfexpintl](special_functions/expint "cpp/numeric/special functions/expint")
(C++17)(C++17)(C++17) | exponential integral (function) |
| [hermitehermitefhermitel](special_functions/hermite "cpp/numeric/special functions/hermite")
(C++17)(C++17)(C++17) | Hermite polynomials (function) |
| [legendrelegendreflegendrel](special_functions/legendre "cpp/numeric/special functions/legendre")
(C++17)(C++17)(C++17) | Legendre polynomials (function) |
| [laguerrelaguerreflaguerrel](special_functions/laguerre "cpp/numeric/special functions/laguerre")
(C++17)(C++17)(C++17) | Laguerre polynomials (function) |
| [riemann\_zetariemann\_zetafriemann\_zetal](special_functions/riemann_zeta "cpp/numeric/special functions/riemann zeta")
(C++17)(C++17)(C++17) | Riemann zeta function (function) |
| [sph\_besselsph\_besselfsph\_bessell](special_functions/sph_bessel "cpp/numeric/special functions/sph bessel")
(C++17)(C++17)(C++17) | spherical Bessel functions (of the first kind) (function) |
| [sph\_legendresph\_legendrefsph\_legendrel](special_functions/sph_legendre "cpp/numeric/special functions/sph legendre")
(C++17)(C++17)(C++17) | spherical associated Legendre functions (function) |
| [sph\_neumannsph\_neumannfsph\_neumannl](special_functions/sph_neumann "cpp/numeric/special functions/sph neumann")
(C++17)(C++17)(C++17) | spherical Neumann functions (function) |
### Notes
Overloads for math special functions are present in the final draft of ISO/IEC 29124:2010 ([N3060](https://wg21.link/N3060)), but absent in C++17/20 standard. These overloads are not provided by some implementations. We intendedly consider the missing of these overloads a defect in C++17/20. See also [LWG issue 3234](https://cplusplus.github.io/LWG/issue3234).
These functions are unrelated to [special member functions](../language/member_functions#Special_member_functions "cpp/language/member functions") of class types.
| [Feature-test](../utility/feature_test "cpp/utility/feature test") macro | Value | Std |
| --- | --- | --- |
| [`__cpp_lib_math_special_functions`](../feature_test#Library_features "cpp/feature test") | `201603L` | (C++17) |
### References
* C++20 standard (ISO/IEC 14882:2020):
+ 26.8.6 Mathematical special functions [sf.cmath]
* C++17 standard (ISO/IEC 14882:2017):
+ 29.9.5 Mathematical special functions [sf.cmath]
| programming_docs |
cpp Compile-time rational arithmetic (since C++11)
Compile-time rational arithmetic (since C++11)
==============================================
The class template `std::ratio` and associated templates provide compile-time rational arithmetic support. Each instantiation of this template exactly represents any finite rational number.
### Compile-time fractions
| Defined in header `[<ratio>](../header/ratio "cpp/header/ratio")` |
| --- |
| [ratio](ratio/ratio "cpp/numeric/ratio/ratio")
(C++11) | represents exact rational fraction (class template) |
Several convenience typedefs that correspond to the SI ratios are provided by the standard library:
| Defined in header `[<ratio>](../header/ratio "cpp/header/ratio")` |
| --- |
| Type | Definition |
| `yocto` | `[std::ratio](http://en.cppreference.com/w/cpp/numeric/ratio/ratio)<1, 1000000000000000000000000>`, if `[std::intmax\_t](../types/integer "cpp/types/integer")` can represent the denominator |
| `zepto` | `[std::ratio](http://en.cppreference.com/w/cpp/numeric/ratio/ratio)<1, 1000000000000000000000>`, if `[std::intmax\_t](../types/integer "cpp/types/integer")` can represent the denominator |
| `atto` | `[std::ratio](http://en.cppreference.com/w/cpp/numeric/ratio/ratio)<1, 1000000000000000000>` |
| `femto` | `[std::ratio](http://en.cppreference.com/w/cpp/numeric/ratio/ratio)<1, 1000000000000000>` |
| `pico` | `[std::ratio](http://en.cppreference.com/w/cpp/numeric/ratio/ratio)<1, 1000000000000>` |
| `nano` | `[std::ratio](http://en.cppreference.com/w/cpp/numeric/ratio/ratio)<1, 1000000000>` |
| `micro` | `[std::ratio](http://en.cppreference.com/w/cpp/numeric/ratio/ratio)<1, 1000000>` |
| `milli` | `[std::ratio](http://en.cppreference.com/w/cpp/numeric/ratio/ratio)<1, 1000>` |
| `centi` | `[std::ratio](http://en.cppreference.com/w/cpp/numeric/ratio/ratio)<1, 100>` |
| `deci` | `[std::ratio](http://en.cppreference.com/w/cpp/numeric/ratio/ratio)<1, 10>` |
| `deca` | `[std::ratio](http://en.cppreference.com/w/cpp/numeric/ratio/ratio)<10, 1>` |
| `hecto` | `[std::ratio](http://en.cppreference.com/w/cpp/numeric/ratio/ratio)<100, 1>` |
| `kilo` | `[std::ratio](http://en.cppreference.com/w/cpp/numeric/ratio/ratio)<1000, 1>` |
| `mega` | `[std::ratio](http://en.cppreference.com/w/cpp/numeric/ratio/ratio)<1000000, 1>` |
| `giga` | `[std::ratio](http://en.cppreference.com/w/cpp/numeric/ratio/ratio)<1000000000, 1>` |
| `tera` | `[std::ratio](http://en.cppreference.com/w/cpp/numeric/ratio/ratio)<1000000000000, 1>` |
| `peta` | `[std::ratio](http://en.cppreference.com/w/cpp/numeric/ratio/ratio)<1000000000000000, 1>` |
| `exa` | `[std::ratio](http://en.cppreference.com/w/cpp/numeric/ratio/ratio)<1000000000000000000, 1>` |
| `zetta` | `[std::ratio](http://en.cppreference.com/w/cpp/numeric/ratio/ratio)<1000000000000000000000, 1>`, if `[std::intmax\_t](../types/integer "cpp/types/integer")` can represent the numerator |
| `yotta` | `[std::ratio](http://en.cppreference.com/w/cpp/numeric/ratio/ratio)<1000000000000000000000000, 1>`, if `[std::intmax\_t](../types/integer "cpp/types/integer")` can represent the numerator |
### Compile-time rational arithmetic
Several alias templates, that perform arithmetic operations on `ratio` objects at compile-time are provided.
| Defined in header `[<ratio>](../header/ratio "cpp/header/ratio")` |
| --- |
| [ratio\_add](ratio/ratio_add "cpp/numeric/ratio/ratio add")
(C++11) | adds two `ratio` objects at compile-time (alias template) |
| [ratio\_subtract](ratio/ratio_subtract "cpp/numeric/ratio/ratio subtract")
(C++11) | subtracts two `ratio` objects at compile-time (alias template) |
| [ratio\_multiply](ratio/ratio_multiply "cpp/numeric/ratio/ratio multiply")
(C++11) | multiplies two `ratio` objects at compile-time (alias template) |
| [ratio\_divide](ratio/ratio_divide "cpp/numeric/ratio/ratio divide")
(C++11) | divides two `ratio` objects at compile-time (alias template) |
### Compile-time rational comparison
Several class templates, that perform comparison operations on `ratio` objects at compile-time are provided.
| Defined in header `[<ratio>](../header/ratio "cpp/header/ratio")` |
| --- |
| [ratio\_equal](ratio/ratio_equal "cpp/numeric/ratio/ratio equal")
(C++11) | compares two `ratio` objects for equality at compile-time (class template) |
| [ratio\_not\_equal](ratio/ratio_not_equal "cpp/numeric/ratio/ratio not equal")
(C++11) | compares two `ratio` objects for inequality at compile-time (class template) |
| [ratio\_less](ratio/ratio_less "cpp/numeric/ratio/ratio less")
(C++11) | compares two `ratio` objects for *less than* at compile-time (class template) |
| [ratio\_less\_equal](ratio/ratio_less_equal "cpp/numeric/ratio/ratio less equal")
(C++11) | compares two `ratio` objects for *less than or equal to* at compile-time (class template) |
| [ratio\_greater](ratio/ratio_greater "cpp/numeric/ratio/ratio greater")
(C++11) | compares two `ratio` objects for *greater than* at compile-time (class template) |
| [ratio\_greater\_equal](ratio/ratio_greater_equal "cpp/numeric/ratio/ratio greater equal")
(C++11) | compares two `ratio` objects for *greater than or equal to* at compile-time (class template) |
cpp std::rotl std::rotl
=========
| Defined in header `[<bit>](../header/bit "cpp/header/bit")` | | |
| --- | --- | --- |
|
```
template< class T >
[[nodiscard]] constexpr T rotl( T x, int s ) noexcept;
```
| | (since C++20) |
Computes the result of bitwise left-rotating the value of `x` by `s` positions. This operation is also known as a left [circular shift](https://en.wikipedia.org/wiki/Circular_shift "enwiki:Circular shift").
Formally, let `N` be `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::digits`, `r` be `s % N`.
* If `r` is 0, returns `x`;
* if `r` is positive, returns `(x << r) | (x >> (N - r))`;
* if `r` is negative, returns `[std::rotr](http://en.cppreference.com/w/cpp/numeric/rotr)(x, -r)`.
This overload participates in overload resolution only if `T` is an unsigned integer type (that is, `unsigned char`, `unsigned short`, `unsigned int`, `unsigned long`, `unsigned long long`, or an extended unsigned integer type).
### Parameters
| | | |
| --- | --- | --- |
| x | - | value of unsigned integer type |
| s | - | number of positions to shift |
### Return value
The result of bitwise left-rotating `x` by `s` positions.
### Notes
| [Feature-test](../utility/feature_test "cpp/utility/feature test") macro |
| --- |
| [`__cpp_lib_bitops`](../feature_test#Library_features "cpp/feature test") |
### Example
```
#include <bit>
#include <bitset>
#include <cstdint>
#include <iostream>
int main()
{
const std::uint8_t i = 0b00011101;
std::cout << "i = " << std::bitset<8>(i) << '\n';
std::cout << "rotl(i,0) = " << std::bitset<8>(std::rotl(i,0)) << '\n';
std::cout << "rotl(i,1) = " << std::bitset<8>(std::rotl(i,1)) << '\n';
std::cout << "rotl(i,4) = " << std::bitset<8>(std::rotl(i,4)) << '\n';
std::cout << "rotl(i,9) = " << std::bitset<8>(std::rotl(i,9)) << '\n';
std::cout << "rotl(i,-1) = " << std::bitset<8>(std::rotl(i,-1)) << '\n';
}
```
Output:
```
i = 00011101
rotl(i,0) = 00011101
rotl(i,1) = 00111010
rotl(i,4) = 11010001
rotl(i,9) = 00111010
rotl(i,-1) = 10001110
```
### See also
| | |
| --- | --- |
| [rotr](rotr "cpp/numeric/rotr")
(C++20) | computes the result of bitwise right-rotation (function template) |
| [operator<<=operator>>=operator<<operator>>](../utility/bitset/operator_ltltgtgt "cpp/utility/bitset/operator ltltgtgt") | performs binary shift left and shift right (public member function of `std::bitset<N>`) |
cpp std::rotr std::rotr
=========
| Defined in header `[<bit>](../header/bit "cpp/header/bit")` | | |
| --- | --- | --- |
|
```
template< class T >
[[nodiscard]] constexpr T rotr( T x, int s ) noexcept;
```
| | (since C++20) |
Computes the result of bitwise right-rotating the value of `x` by `s` positions. This operation is also known as a right [circular shift](https://en.wikipedia.org/wiki/Circular_shift "enwiki:Circular shift").
Formally, let `N` be `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::digits`, `r` be `s % N`.
* If `r` is 0, returns `x`;
* if `r` is positive, returns `(x >> r) | (x << (N - r))`;
* if `r` is negative, returns `[std::rotl](http://en.cppreference.com/w/cpp/numeric/rotl)(x, -r)`.
This overload participates in overload resolution only if `T` is an unsigned integer type (that is, `unsigned char`, `unsigned short`, `unsigned int`, `unsigned long`, `unsigned long long`, or an extended unsigned integer type).
### Parameters
| | | |
| --- | --- | --- |
| x | - | value of unsigned integer type |
| s | - | number of positions to shift |
### Return value
The result of bitwise right-rotating `x` by `s` positions.
### Notes
| [Feature-test](../utility/feature_test "cpp/utility/feature test") macro |
| --- |
| [`__cpp_lib_bitops`](../feature_test#Library_features "cpp/feature test") |
### Example
```
#include <bit>
#include <bitset>
#include <cstdint>
#include <iostream>
int main()
{
const std::uint8_t i = 0b00011101;
std::cout << "i = " << std::bitset<8>(i) << '\n';
std::cout << "rotr(i,0) = " << std::bitset<8>(std::rotr(i,0)) << '\n';
std::cout << "rotr(i,1) = " << std::bitset<8>(std::rotr(i,1)) << '\n';
std::cout << "rotr(i,9) = " << std::bitset<8>(std::rotr(i,9)) << '\n';
std::cout << "rotr(i,-1) = " << std::bitset<8>(std::rotr(i,-1)) << '\n';
}
```
Output:
```
i = 00011101
rotr(i,0) = 00011101
rotr(i,1) = 10001110
rotr(i,9) = 10001110
rotr(i,-1) = 00111010
```
### See also
| | |
| --- | --- |
| [rotl](rotl "cpp/numeric/rotl")
(C++20) | computes the result of bitwise left-rotation (function template) |
| [operator<<=operator>>=operator<<operator>>](../utility/bitset/operator_ltltgtgt "cpp/utility/bitset/operator ltltgtgt") | performs binary shift left and shift right (public member function of `std::bitset<N>`) |
cpp std::gcd std::gcd
========
| Defined in header `[<numeric>](../header/numeric "cpp/header/numeric")` | | |
| --- | --- | --- |
|
```
template< class M, class N >
constexpr std::common_type_t<M, N> gcd( M m, N n );
```
| | (since C++17) |
Computes the greatest common divisor of the integers `m` and `n`.
### Parameters
| | | |
| --- | --- | --- |
| m, n | - | integer values |
### Return value
If both `m` and `n` are zero, returns zero. Otherwise, returns the greatest common divisor of `|m|` and `|n|`.
### Remarks
If either `M` or `N` is not an integer type, or if either is (possibly cv-qualified) `bool`, the program is ill-formed.
If either `|m|` or `|n|` is not representable as a value of type `[std::common\_type\_t](http://en.cppreference.com/w/cpp/types/common_type)<M, N>`, the behavior is undefined.
### Exceptions
Throws no exceptions.
### Notes
| [Feature-test](../utility/feature_test "cpp/utility/feature test") macro |
| --- |
| [`__cpp_lib_gcd_lcm`](../feature_test#Library_features "cpp/feature test") |
### Example
```
#include <numeric>
int main() {
constexpr int p {2 * 2 * 3};
constexpr int q {2 * 3 * 3};
static_assert(2 * 3 == std::gcd(p, q));
}
```
### See also
| | |
| --- | --- |
| [lcm](lcm "cpp/numeric/lcm")
(C++17) | `constexpr` function template returning the least common multiple of two integers (function template) |
cpp std::byteswap std::byteswap
=============
| Defined in header `[<bit>](../header/bit "cpp/header/bit")` | | |
| --- | --- | --- |
|
```
template< class T >
constexpr T byteswap( T n ) noexcept;
```
| | (since C++23) |
Reverses the bytes in the given integer value `n`.
`std::byteswap` participates in overload resolution only if `T` satisfies [`integral`](../concepts/integral "cpp/concepts/integral"), i.e., `T` is an integer type. The program is ill-formed if `T` has padding bits.
### Parameters
| | | |
| --- | --- | --- |
| n | - | integer value |
### Return value
An integer value of type `T` whose object representation comprises the bytes of that of `n` in reversed order.
### Notes
This function is useful for processing data of different endianness.
| [Feature-test](../utility/feature_test "cpp/utility/feature test") macro | Value | Std |
| --- | --- | --- |
| [`__cpp_lib_byteswap`](../feature_test#Library_features "cpp/feature test") | `202110L` | (C++23) |
### Possible implementation
| |
| --- |
|
```
template<std::integral T>
constexpr T byteswap(T value) noexcept
{
static_assert(std::has_unique_object_representations_v<T>,
"T may not have padding bits");
auto value_representation = std::bit_cast<std::array<std::byte, sizeof(T)>>(value);
std::ranges::reverse(value_representation);
return std::bit_cast<T>(value_representation);
}
```
|
### Example
```
#include <bit>
#include <cstdint>
#include <concepts>
#include <iostream>
#include <iomanip>
template <std::integral T>
void dump(T v, char term = '\n') {
std::cout << std::hex << std::uppercase << std::setfill('0')
<< std::setw(sizeof(T) * 2) << v << " : ";
for (std::size_t i{}; i != sizeof(T); ++i, v >>= 8) {
std::cout << std::setw(2) << static_cast<unsigned>(T(0xFF) & v) << ' ';
}
std::cout << std::dec << term;
}
int main()
{
static_assert(std::byteswap('a') == 'a');
std::cout << "byteswap for U16:\n";
constexpr auto x = std::uint16_t(0xCAFE);
dump(x);
dump(std::byteswap(x));
std::cout << "\nbyteswap for U32:\n";
constexpr auto y = std::uint32_t(0xDEADBEEFu);
dump(y);
dump(std::byteswap(y));
std::cout << "\nbyteswap for U64:\n";
constexpr auto z = std::uint64_t{0x0123456789ABCDEFull};
dump(z);
dump(std::byteswap(z));
}
```
Possible output:
```
byteswap for U16:
CAFE : FE CA
FECA : CA FE
byteswap for U32:
DEADBEEF : EF BE AD DE
EFBEADDE : DE AD BE EF
byteswap for U64:
0123456789ABCDEF : EF CD AB 89 67 45 23 01
EFCDAB8967452301 : 01 23 45 67 89 AB CD EF
```
### See also
| | |
| --- | --- |
| [endian](../types/endian "cpp/types/endian")
(C++20) | indicates the endianness of scalar types (enum) |
| [rotl](rotl "cpp/numeric/rotl")
(C++20) | computes the result of bitwise left-rotation (function template) |
| [rotr](rotr "cpp/numeric/rotr")
(C++20) | computes the result of bitwise right-rotation (function template) |
cpp std::midpoint std::midpoint
=============
| Defined in header `[<numeric>](../header/numeric "cpp/header/numeric")` | | |
| --- | --- | --- |
|
```
template< class T >
constexpr T midpoint( T a, T b ) noexcept;
```
| (1) | (since C++20) |
|
```
template< class T >
constexpr T* midpoint( T* a, T* b );
```
| (2) | (since C++20) |
Computes the midpoint of the integers, floating-points, or pointers `a` and `b`.
1) This overload participates in overload resolution only if `T` is an arithmetic type other than `bool`.
2) This overload participates in overload resolution only if `T` is an object type. Use of this overload is ill-formed if `T` is an [incomplete type](../language/type#Incomplete_type "cpp/language/type"). ### Parameters
| | | |
| --- | --- | --- |
| a, b | - | integers, floating-points, or pointer values |
### Return value
1) Half the sum of `a` and `b`. No overflow occurs. If `a` and `b` have integer type and the sum is odd, the result is rounded towards `a`. If `a` and `b` have floating-point type, at most one inexact operation occurs.
2) If `a` and `b` point to, respectively, `x[i]` and `x[j]` of the same array object `x` (for the purpose of [pointer arithmetic](../language/operator_arithmetic#Additive_operators "cpp/language/operator arithmetic")), returns a pointer to `x[i+(j-i)/2]` (or, equivalently `x[std::midpoint(i, j)]`) where the division rounds towards zero. If `a` and `b` do not point to elements of the same array object, the behavior is undefined. ### Exceptions
Throws no exceptions.
### Notes
Overload (2) can be simply implemented as `return a + (b - a) / 2;` on common platforms. However, such implementation is not guaranteed to be portable, because there may be some platforms where creating an array with number of elements greater than `[PTRDIFF\_MAX](../types/climits "cpp/types/climits")` is possible, and `b - a` may result in undefined behavior even if both `b` and `a` point to elements in the same array.
| [Feature-test](../utility/feature_test "cpp/utility/feature test") macro |
| --- |
| [`__cpp_lib_interpolate`](../feature_test#Library_features "cpp/feature test") |
### Example
```
#include <cstdint>
#include <limits>
#include <numeric>
#include <iostream>
int main()
{
std::uint32_t a = std::numeric_limits<std::uint32_t>::max();
std::uint32_t b = std::numeric_limits<std::uint32_t>::max() - 2;
std::cout << "a: " << a << '\n'
<< "b: " << b << '\n'
<< "Incorrect (overflow and wrapping): " << (a + b) / 2 << '\n'
<< "Correct: " << std::midpoint(a, b) << "\n\n";
auto on_pointers = [](int i, int j) {
char const* text = "0123456789";
char const* p = text + i;
char const* q = text + j;
std::cout << "std::midpoint('" << *p << "', '" << *q << "'): '"
<< *std::midpoint(p, q) << "'\n";
};
on_pointers(2, 4);
on_pointers(2, 5);
on_pointers(5, 2);
on_pointers(2, 6);
}
```
Output:
```
a: 4294967295
b: 4294967293
Incorrect (overflow and wrapping): 2147483646
Correct: 4294967294
std::midpoint('2', '4'): '3'
std::midpoint('2', '5'): '3'
std::midpoint('5', '2'): '4'
std::midpoint('2', '6'): '4'
```
### References
* C++20 standard (ISO/IEC 14882:2020):
+ 25.10.15 Midpoint [numeric.ops.midpoint]
### See also
| | |
| --- | --- |
| [lerp](lerp "cpp/numeric/lerp")
(C++20) | linear interpolation function (function) |
cpp std::countl_zero std::countl\_zero
=================
| Defined in header `[<bit>](../header/bit "cpp/header/bit")` | | |
| --- | --- | --- |
|
```
template< class T >
constexpr int countl_zero( T x ) noexcept;
```
| | (since C++20) |
Returns the number of consecutive 0 bits in the value of `x`, starting from the most significant bit ("left").
This overload participates in overload resolution only if `T` is an unsigned integer type (that is, `unsigned char`, `unsigned short`, `unsigned int`, `unsigned long`, `unsigned long long`, or an extended unsigned integer type).
### Parameters
| | | |
| --- | --- | --- |
| x | - | value of unsigned integer type |
### Return value
The number of consecutive 0 bits in the value of `x`, starting from the most significant bit.
### Notes
| [Feature-test](../utility/feature_test "cpp/utility/feature test") macro |
| --- |
| [`__cpp_lib_bitops`](../feature_test#Library_features "cpp/feature test") |
### Example
```
#include <bit>
#include <bitset>
#include <cstdint>
#include <iostream>
int main()
{
for (const std::uint8_t i : { 0, 0b11111111, 0b11110000, 0b00011110 }) {
std::cout << "countl_zero( " << std::bitset<8>(i) << " ) = "
<< std::countl_zero(i) << '\n';
}
}
```
Output:
```
countl_zero( 00000000 ) = 8
countl_zero( 11111111 ) = 0
countl_zero( 11110000 ) = 0
countl_zero( 00011110 ) = 3
```
### See also
| | |
| --- | --- |
| [countl\_one](countl_one "cpp/numeric/countl one")
(C++20) | counts the number of consecutive 1 bits, starting from the most significant bit (function template) |
| [countr\_zero](countr_zero "cpp/numeric/countr zero")
(C++20) | counts the number of consecutive 0 bits, starting from the least significant bit (function template) |
| [countr\_one](countr_one "cpp/numeric/countr one")
(C++20) | counts the number of consecutive 1 bits, starting from the least significant bit (function template) |
| [popcount](popcount "cpp/numeric/popcount")
(C++20) | counts the number of 1 bits in an unsigned integer (function template) |
| [allanynone](../utility/bitset/all_any_none "cpp/utility/bitset/all any none")
(C++11) | checks if all, any or none of the bits are set to `true` (public member function of `std::bitset<N>`) |
| programming_docs |
cpp std::lerp std::lerp
=========
| Defined in header `[<cmath>](../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
|
```
constexpr float lerp( float a, float b, float t ) noexcept;
```
| (1) | (since C++20) |
|
```
constexpr double lerp( double a, double b, double t ) noexcept;
```
| (2) | (since C++20) |
|
```
constexpr long double lerp( long double a, long double b, long double t ) noexcept;
```
| (3) | (since C++20) |
|
```
constexpr Promoted lerp( Arithmetic1 a, Arithmetic2 b, Arithmetic3 t ) noexcept;
```
| (4) | (since C++20) |
1-3) Computes the linear [interpolation](https://en.wikipedia.org/wiki/Linear_interpolation "enwiki:Linear interpolation") between `a` and `b`, if the parameter `t` is inside `[0, 1]` (the linear [extrapolation](https://en.wikipedia.org/wiki/Extrapolation#Linear "enwiki:Extrapolation") otherwise), i.e. the result of \(a+t(bโa)\)a+t(bโa) with accounting for floating-point calculation imprecision.
4) A set of overloads or a function template for all combinations of arguments of [arithmetic type](../types/is_arithmetic "cpp/types/is arithmetic") not covered by 1-3). If any argument has [integral type](../types/is_integral "cpp/types/is integral"), it is cast to `double`. If any other argument is `long double`, then the return type is `long double`, otherwise it is `double`. ### Parameters
| | | |
| --- | --- | --- |
| a, b, t | - | values of floating-point or [integral types](../types/is_integral "cpp/types/is integral") |
### Return value
\(a+t(bโa)\)a+t(bโa).
When `[isfinite(a)](math/isfinite "cpp/numeric/math/isfinite")` and `[isfinite(b)](math/isfinite "cpp/numeric/math/isfinite")`, the following properties are guaranteed:
* If `t == 0`, the result is equal to `a`.
* If `t == 1`, the result is equal to `b`.
* If `t >= 0 && t <= 1`, the result is finite.
* If `isfinite(t) && a == b`, the result is equal to `a`.
* If `isfinite(t) || (b - aย != 0` and `[isinf(t)](math/isinf "cpp/numeric/math/isinf")``)`, the result is not [`NaN`](math/nan "cpp/numeric/math/NAN").
Let `CMP(x,y)` be `1` if `x > y`, `-1` if `x < y`, and `0` otherwise. For any `t1` and `t2`, the product of `CMP(lerp(a, b, t2), lerp(a, b, t1))`, `CMP(t2, t1)`, and `CMP(b, a)` is non-negative. (That is, `lerp` is monotonic.).
### Notes
`lerp` is available in the global namespace when `<math.h>` is included, even if it is not a part of C.
| [Feature-test](../utility/feature_test "cpp/utility/feature test") macro |
| --- |
| [`__cpp_lib_interpolate`](../feature_test#Library_features "cpp/feature test") |
### Example
```
#include <cmath>
#include <cassert>
#include <iostream>
float naive_lerp(float a, float b, float t)
{
return a + t * (b - a);
}
int main()
{
std::cout << std::boolalpha;
const float a = 1e8f, b = 1.0f;
const float midpoint = std::lerp(a, b, 0.5f);
std::cout << "a = " << a << ", " << "b = " << b << '\n'
<< "midpoint = " << midpoint << '\n';
std::cout << "std::lerp is exact: "
<< (a == std::lerp(a, b, 0.0f)) << ' '
<< (b == std::lerp(a, b, 1.0f)) << '\n';
std::cout << "naive_lerp is exact: "
<< (a == naive_lerp(a, b, 0.0f)) << ' '
<< (b == naive_lerp(a, b, 1.0f)) << '\n';
std::cout << "std::lerp(a, b, 1.0f) = " << std::lerp(a, b, 1.0f) << '\n'
<< "naive_lerp(a, b, 1.0f) = " << naive_lerp(a, b, 1.0f) << '\n';
assert(not std::isnan(std::lerp(a, b, INFINITY))); // lerp here can be -inf
std::cout << "Extrapolation demo, given std::lerp(5, 10, t):\n";
for (auto t{-2.0}; t <= 2.0; t += 0.5)
std::cout << std::lerp(5.0, 10.0, t) << ' ';
std::cout << '\n';
}
```
Possible output:
```
a = 1e+08, b = 1
midpoint = 5e+07
std::lerp is exact?: true true
naive_lerp is exact?: true false
std::lerp(a, b, 1.0f) = 1
naive_lerp(a, b, 1.0f) = 0
Extrapolation demo, given std::lerp(5, 10, t):
-5 -2.5 0 2.5 5 7.5 10 12.5 15
```
### See also
| | |
| --- | --- |
| [midpoint](midpoint "cpp/numeric/midpoint")
(C++20) | midpoint between two numbers or pointers (function template) |
cpp Pseudo-random number generation Pseudo-random number generation
===============================
The random number library provides classes that generate random and pseudo-random numbers. These classes include:
* Uniform random bit generators (URBGs), which include both random number engines, which are pseudo-random number generators that generate integer sequences with a uniform distribution, and true random number generators if available;
* Random number distributions (e.g. [uniform](random/uniform_int_distribution "cpp/numeric/random/uniform int distribution"), [normal](random/normal_distribution "cpp/numeric/random/normal distribution"), or [poisson distributions](random/poisson_distribution "cpp/numeric/random/poisson distribution")) which convert the output of URBGs into various statistical distributions
URBGs and distributions are designed to be used together to produce random values. All of the random number engines may be specifically seeded, serialized, and deserialized for use with repeatable simulators.
### Uniform random bit generators
A *uniform random bit generator* is a function object returning unsigned integer values such that each value in the range of possible results has (ideally) equal probability of being returned.
All uniform random bit generators meet the [UniformRandomBitGenerator](../named_req/uniformrandombitgenerator "cpp/named req/UniformRandomBitGenerator") requirements. C++20 also defines a [`uniform_random_bit_generator`](random/uniform_random_bit_generator "cpp/numeric/random/uniform random bit generator") concept.
| Defined in header `[<random>](../header/random "cpp/header/random")` |
| --- |
| [uniform\_random\_bit\_generator](random/uniform_random_bit_generator "cpp/numeric/random/uniform random bit generator")
(C++20) | specifies that a type qualifies as a uniform random bit generator (concept) |
#### Random number engines
Random number engines generate pseudo-random numbers using seed data as entropy source. Several different classes of pseudo-random number generation algorithms are implemented as templates that can be customized.
The choice of which engine to use involves a number of tradeoffs: the linear congruential engine is moderately fast and has a very small storage requirement for state. The lagged Fibonacci generators are very fast even on processors without advanced arithmetic instruction sets, at the expense of greater state storage and sometimes less desirable spectral characteristics. The Mersenne twister is slower and has greater state storage requirements but with the right parameters has the longest non-repeating sequence with the most desirable spectral characteristics (for a given definition of desirable).
| Defined in header `[<random>](../header/random "cpp/header/random")` |
| --- |
| [linear\_congruential\_engine](random/linear_congruential_engine "cpp/numeric/random/linear congruential engine")
(C++11) | implements [linear congruential](https://en.wikipedia.org/wiki/Linear_congruential_generator "enwiki:Linear congruential generator") algorithm (class template) |
| [mersenne\_twister\_engine](random/mersenne_twister_engine "cpp/numeric/random/mersenne twister engine")
(C++11) | implements [Mersenne twister](https://en.wikipedia.org/wiki/Mersenne_twister "enwiki:Mersenne twister") algorithm (class template) |
| [subtract\_with\_carry\_engine](random/subtract_with_carry_engine "cpp/numeric/random/subtract with carry engine")
(C++11) | implements a subtract-with-carry ( [lagged Fibonacci](https://en.wikipedia.org/wiki/Lagged_Fibonacci_generator "enwiki:Lagged Fibonacci generator")) algorithm (class template) |
#### Random number engine adaptors
Random number engine adaptors generate pseudo-random numbers using another random number engine as entropy source. They are generally used to alter the spectral characteristics of the underlying engine.
| Defined in header `[<random>](../header/random "cpp/header/random")` |
| --- |
| [discard\_block\_engine](random/discard_block_engine "cpp/numeric/random/discard block engine")
(C++11) | discards some output of a random number engine (class template) |
| [independent\_bits\_engine](random/independent_bits_engine "cpp/numeric/random/independent bits engine")
(C++11) | packs the output of a random number engine into blocks of a specified number of bits (class template) |
| [shuffle\_order\_engine](random/shuffle_order_engine "cpp/numeric/random/shuffle order engine")
(C++11) | delivers the output of a random number engine in a different order (class template) |
#### Predefined random number generators
Several specific popular algorithms are predefined.
| Defined in header `[<random>](../header/random "cpp/header/random")` |
| --- |
| Type | Definition |
| `minstd_rand0`(C++11) | `[std::linear\_congruential\_engine](http://en.cppreference.com/w/cpp/numeric/random/linear_congruential_engine)<[std::uint\_fast32\_t](http://en.cppreference.com/w/cpp/types/integer), 16807, 0, 2147483647>` Discovered in 1969 by Lewis, Goodman and Miller, adopted as "Minimal standard" in 1988 by Park and Miller. |
| `minstd_rand`(C++11) | `[std::linear\_congruential\_engine](http://en.cppreference.com/w/cpp/numeric/random/linear_congruential_engine)<[std::uint\_fast32\_t](http://en.cppreference.com/w/cpp/types/integer), 48271, 0, 2147483647>` Newer "Minimum standard", recommended by Park, Miller, and Stockmeyer in 1993. |
| `mt19937`(C++11) | `[std::mersenne\_twister\_engine](http://en.cppreference.com/w/cpp/numeric/random/mersenne_twister_engine)<[std::uint\_fast32\_t](http://en.cppreference.com/w/cpp/types/integer), 32, 624, 397, 31, 0x9908b0df, 11, 0xffffffff, 7, 0x9d2c5680, 15, 0xefc60000, 18, 1812433253>` 32-bit Mersenne Twister by Matsumoto and Nishimura, 1998. |
| `mt19937_64`(C++11) | `[std::mersenne\_twister\_engine](http://en.cppreference.com/w/cpp/numeric/random/mersenne_twister_engine)<[std::uint\_fast64\_t](http://en.cppreference.com/w/cpp/types/integer), 64, 312, 156, 31, 0xb5026f5aa96619e9, 29, 0x5555555555555555, 17, 0x71d67fffeda60000, 37, 0xfff7eee000000000, 43, 6364136223846793005>` 64-bit Mersenne Twister by Matsumoto and Nishimura, 2000. |
| `ranlux24_base`(C++11) | `[std::subtract\_with\_carry\_engine](http://en.cppreference.com/w/cpp/numeric/random/subtract_with_carry_engine)<[std::uint\_fast32\_t](http://en.cppreference.com/w/cpp/types/integer), 24, 10, 24>` |
| `ranlux48_base`(C++11) | `[std::subtract\_with\_carry\_engine](http://en.cppreference.com/w/cpp/numeric/random/subtract_with_carry_engine)<[std::uint\_fast64\_t](http://en.cppreference.com/w/cpp/types/integer), 48, 5, 12>` |
| `ranlux24`(C++11) | `[std::discard\_block\_engine](http://en.cppreference.com/w/cpp/numeric/random/discard_block_engine)<[std::ranlux24\_base](http://en.cppreference.com/w/cpp/numeric/random/subtract_with_carry_engine), 223, 23>` 24-bit RANLUX generator by Martin Lรผscher and Fred James, 1994. |
| `ranlux48`(C++11) | `[std::discard\_block\_engine](http://en.cppreference.com/w/cpp/numeric/random/discard_block_engine)<[std::ranlux48\_base](http://en.cppreference.com/w/cpp/numeric/random/subtract_with_carry_engine), 389, 11>` 48-bit RANLUX generator by Martin Lรผscher and Fred James, 1994. |
| `knuth_b`(C++11) | `[std::shuffle\_order\_engine](http://en.cppreference.com/w/cpp/numeric/random/shuffle_order_engine)<[std::minstd\_rand0](http://en.cppreference.com/w/cpp/numeric/random/linear_congruential_engine), 256>` |
| `default_random_engine`(C++11) | *implementation-defined* |
#### Non-deterministic random numbers
`[std::random\_device](random/random_device "cpp/numeric/random/random device")` is a non-deterministic uniform random bit generator, although implementations are allowed to implement `[std::random\_device](random/random_device "cpp/numeric/random/random device")` using a pseudo-random number engine if there is no support for non-deterministic random number generation.
| | |
| --- | --- |
| [random\_device](random/random_device "cpp/numeric/random/random device")
(C++11) | non-deterministic random number generator using hardware entropy source (class) |
### Random number distributions
A random number distribution post-processes the output of a URBG in such a way that resulting output is distributed according to a defined statistical probability density function.
Random number distributions satisfy [RandomNumberDistribution](../named_req/randomnumberdistribution "cpp/named req/RandomNumberDistribution").
| Defined in header `[<random>](../header/random "cpp/header/random")` |
| --- |
| Uniform distributions |
| [uniform\_int\_distribution](random/uniform_int_distribution "cpp/numeric/random/uniform int distribution")
(C++11) | produces integer values evenly distributed across a range (class template) |
| [uniform\_real\_distribution](random/uniform_real_distribution "cpp/numeric/random/uniform real distribution")
(C++11) | produces real values evenly distributed across a range (class template) |
| Bernoulli distributions |
| [bernoulli\_distribution](random/bernoulli_distribution "cpp/numeric/random/bernoulli distribution")
(C++11) | produces `bool` values on a [Bernoulli distribution](https://en.wikipedia.org/wiki/Bernoulli_distribution "enwiki:Bernoulli distribution"). (class) |
| [binomial\_distribution](random/binomial_distribution "cpp/numeric/random/binomial distribution")
(C++11) | produces integer values on a [binomial distribution](https://en.wikipedia.org/wiki/Binomial_distribution "enwiki:Binomial distribution"). (class template) |
| [negative\_binomial\_distribution](random/negative_binomial_distribution "cpp/numeric/random/negative binomial distribution")
(C++11) | produces integer values on a [negative binomial distribution](https://en.wikipedia.org/wiki/Negative_binomial_distribution "enwiki:Negative binomial distribution"). (class template) |
| [geometric\_distribution](random/geometric_distribution "cpp/numeric/random/geometric distribution")
(C++11) | produces integer values on a [geometric distribution](https://en.wikipedia.org/wiki/Geometric_distribution "enwiki:Geometric distribution"). (class template) |
| Poisson distributions |
| [poisson\_distribution](random/poisson_distribution "cpp/numeric/random/poisson distribution")
(C++11) | produces integer values on a [poisson distribution](https://en.wikipedia.org/wiki/Poisson_distribution "enwiki:Poisson distribution"). (class template) |
| [exponential\_distribution](random/exponential_distribution "cpp/numeric/random/exponential distribution")
(C++11) | produces real values on an [exponential distribution](https://en.wikipedia.org/wiki/Exponential_distribution "enwiki:Exponential distribution"). (class template) |
| [gamma\_distribution](random/gamma_distribution "cpp/numeric/random/gamma distribution")
(C++11) | produces real values on an [gamma distribution](https://en.wikipedia.org/wiki/Gamma_distribution "enwiki:Gamma distribution"). (class template) |
| [weibull\_distribution](random/weibull_distribution "cpp/numeric/random/weibull distribution")
(C++11) | produces real values on a [Weibull distribution](https://en.wikipedia.org/wiki/Weibull_distribution "enwiki:Weibull distribution"). (class template) |
| [extreme\_value\_distribution](random/extreme_value_distribution "cpp/numeric/random/extreme value distribution")
(C++11) | produces real values on an [extreme value distribution](https://en.wikipedia.org/wiki/Generalized_extreme_value_distribution "enwiki:Generalized extreme value distribution"). (class template) |
| Normal distributions |
| [normal\_distribution](random/normal_distribution "cpp/numeric/random/normal distribution")
(C++11) | produces real values on a [standard normal (Gaussian) distribution](https://en.wikipedia.org/wiki/Normal_distribution "enwiki:Normal distribution"). (class template) |
| [lognormal\_distribution](random/lognormal_distribution "cpp/numeric/random/lognormal distribution")
(C++11) | produces real values on a [lognormal distribution](https://en.wikipedia.org/wiki/Lognormal_distribution "enwiki:Lognormal distribution"). (class template) |
| [chi\_squared\_distribution](random/chi_squared_distribution "cpp/numeric/random/chi squared distribution")
(C++11) | produces real values on a [chi-squared distribution](https://en.wikipedia.org/wiki/Chi-squared_distribution "enwiki:Chi-squared distribution"). (class template) |
| [cauchy\_distribution](random/cauchy_distribution "cpp/numeric/random/cauchy distribution")
(C++11) | produces real values on a [Cauchy distribution](https://en.wikipedia.org/wiki/Cauchy_distribution "enwiki:Cauchy distribution"). (class template) |
| [fisher\_f\_distribution](random/fisher_f_distribution "cpp/numeric/random/fisher f distribution")
(C++11) | produces real values on a [Fisher's F-distribution](https://en.wikipedia.org/wiki/F-distribution "enwiki:F-distribution"). (class template) |
| [student\_t\_distribution](random/student_t_distribution "cpp/numeric/random/student t distribution")
(C++11) | produces real values on a [Student's t-distribution](https://en.wikipedia.org/wiki/Student%27s_t-distribution "enwiki:Student's t-distribution"). (class template) |
| Sampling distributions |
| [discrete\_distribution](random/discrete_distribution "cpp/numeric/random/discrete distribution")
(C++11) | produces random integers on a discrete distribution. (class template) |
| [piecewise\_constant\_distribution](random/piecewise_constant_distribution "cpp/numeric/random/piecewise constant distribution")
(C++11) | produces real values distributed on constant subintervals. (class template) |
| [piecewise\_linear\_distribution](random/piecewise_linear_distribution "cpp/numeric/random/piecewise linear distribution")
(C++11) | produces real values distributed on defined subintervals. (class template) |
### Utilities
| Defined in header `[<random>](../header/random "cpp/header/random")` |
| --- |
| [generate\_canonical](random/generate_canonical "cpp/numeric/random/generate canonical")
(C++11) | evenly distributes real values of given precision across [0, 1) (function template) |
| [seed\_seq](random/seed_seq "cpp/numeric/random/seed seq")
(C++11) | general-purpose bias-eliminating scrambled seed sequence generator (class) |
### C random library
In addition to the engines and distributions described above, the functions and constants from the C random library are also available though not recommended:
| Defined in header `[<cstdlib>](../header/cstdlib "cpp/header/cstdlib")` |
| --- |
| [rand](random/rand "cpp/numeric/random/rand") | generates a pseudo-random number (function) |
| [srand](random/srand "cpp/numeric/random/srand") | seeds pseudo-random number generator (function) |
| [RAND\_MAX](random/rand_max "cpp/numeric/random/RAND MAX") | maximum possible value generated by `[std::rand](random/rand "cpp/numeric/random/rand")` (macro constant) |
### Example
```
#include <iostream>
#include <iomanip>
#include <string>
#include <map>
#include <random>
#include <cmath>
int main()
{
// Seed with a real random value, if available
std::random_device r;
// Choose a random mean between 1 and 6
std::default_random_engine e1(r());
std::uniform_int_distribution<int> uniform_dist(1, 6);
int mean = uniform_dist(e1);
std::cout << "Randomly-chosen mean: " << mean << '\n';
// Generate a normal distribution around that mean
std::seed_seq seed2{r(), r(), r(), r(), r(), r(), r(), r()};
std::mt19937 e2(seed2);
std::normal_distribution<> normal_dist(mean, 2);
std::map<int, int> hist;
for (int n = 0; n < 10000; ++n) {
++hist[std::round(normal_dist(e2))];
}
std::cout << "Normal distribution around " << mean << ":\n";
for (auto p : hist) {
std::cout << std::fixed << std::setprecision(1) << std::setw(2)
<< p.first << ' ' << std::string(p.second/200, '*') << '\n';
}
}
```
Possible output:
```
Randomly-chosen mean: 4
Normal distribution around 4:
-4
-3
-2
-1
0 *
1 ***
2 ******
3 ********
4 *********
5 ********
6 ******
7 ***
8 *
9
10
11
12
```
### See also
| |
| --- |
| [C documentation](https://en.cppreference.com/w/c/numeric/random "c/numeric/random") for Pseudo-random number generation |
| programming_docs |
cpp std::has_single_bit std::has\_single\_bit
=====================
| Defined in header `[<bit>](../header/bit "cpp/header/bit")` | | |
| --- | --- | --- |
|
```
template< class T >
constexpr bool has_single_bit( T x ) noexcept;
```
| | (since C++20) |
Checks if `x` is an integral power of two.
This overload participates in overload resolution only if `T` is an unsigned integer type (that is, `unsigned char`, `unsigned short`, `unsigned int`, `unsigned long`, `unsigned long long`, or an extended unsigned integer type).
### Parameters
| | | |
| --- | --- | --- |
| x | - | value of unsigned integer type |
### Return value
`true` if `x` is an integral power of two; otherwise `false`.
### Notes
| [Feature-test](../utility/feature_test "cpp/utility/feature test") macro |
| --- |
| [`__cpp_lib_int_pow2`](../feature_test#Library_features "cpp/feature test") |
### Possible implementation
| First version |
| --- |
|
```
template <std::unsigned_integral T>
requires !std::same_as<T, bool> && !std::same_as<T, char> &&
!std::same_as<T, char8_t> && !std::same_as<T, char16_t> &&
!std::same_as<T, char32_t> && !std::same_as<T, wchar_t>
constexpr bool has_single_bit(T x) noexcept
{
return x != 0 && (x & (x - 1)) == 0;
}
```
|
| Second version |
|
```
template <std::unsigned_integral T>
requires !std::same_as<T, bool> && !std::same_as<T, char> &&
!std::same_as<T, char8_t> && !std::same_as<T, char16_t> &&
!std::same_as<T, char32_t> && !std::same_as<T, wchar_t>
constexpr bool has_single_bit(T x) noexcept
{
return std::popcount(x) == 1;
}
```
|
### Example
```
#include <bit>
#include <bitset>
#include <iostream>
int main()
{
std::cout << std::boolalpha;
for (auto i = 0u; i < 10u; ++i) {
std::cout << "has_single_bit( " << std::bitset<4>(i) << " ) = "
<< std::has_single_bit(i) // `ispow2` before P1956R1
<< '\n';
}
}
```
Output:
```
has_single_bit( 0000 ) = false
has_single_bit( 0001 ) = true
has_single_bit( 0010 ) = true
has_single_bit( 0011 ) = false
has_single_bit( 0100 ) = true
has_single_bit( 0101 ) = false
has_single_bit( 0110 ) = false
has_single_bit( 0111 ) = false
has_single_bit( 1000 ) = true
has_single_bit( 1001 ) = false
```
### See also
| | |
| --- | --- |
| [popcount](popcount "cpp/numeric/popcount")
(C++20) | counts the number of 1 bits in an unsigned integer (function template) |
| [count](../utility/bitset/count "cpp/utility/bitset/count") | returns the number of bits set to `true` (public member function of `std::bitset<N>`) |
| [test](../utility/bitset/test "cpp/utility/bitset/test") | accesses specific bit (public member function of `std::bitset<N>`) |
cpp std::bit_width std::bit\_width
===============
| Defined in header `[<bit>](../header/bit "cpp/header/bit")` | | |
| --- | --- | --- |
|
```
template< class T >
constexpr int bit_width( T x ) noexcept;
```
| | (since C++20) |
If `x` is not zero, calculates the number of bits needed to store the value `x`, that is, \(1 + \lfloor \log\_2(x) \rfloor\)1 + floor(log
2(x)). If `x` is zero, returns zero.
This overload participates in overload resolution only if `T` is an unsigned integer type (that is, `unsigned char`, `unsigned short`, `unsigned int`, `unsigned long`, `unsigned long long`, or an extended unsigned integer type).
### Parameters
| | | |
| --- | --- | --- |
| x | - | unsigned integer value |
### Return value
Zero if `x` is zero; otherwise, one plus the base-2 logarithm of `x`, with any fractional part discarded.
### Notes
This function is equivalent to `return [std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::digits - [std::countl\_zero](http://en.cppreference.com/w/cpp/numeric/countl_zero)(x);`.
| [Feature-test](../utility/feature_test "cpp/utility/feature test") macro |
| --- |
| [`__cpp_lib_int_pow2`](../feature_test#Library_features "cpp/feature test") |
### Example
```
#include <bit>
#include <bitset>
#include <iostream>
int main()
{
for (unsigned x{0}; x != 8; ++x)
{
std::cout
<< "bit_width( "
<< std::bitset<4>{x} << " ) = "
<< std::bit_width(x) << '\n';
}
}
```
Output:
```
bit_width( 0000 ) = 0
bit_width( 0001 ) = 1
bit_width( 0010 ) = 2
bit_width( 0011 ) = 2
bit_width( 0100 ) = 3
bit_width( 0101 ) = 3
bit_width( 0110 ) = 3
bit_width( 0111 ) = 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 3656](https://cplusplus.github.io/LWG/issue3656) | C++20 | the return type of `bit_width` is the same as the type of its function argument | made it `int` |
### See also
| | |
| --- | --- |
| [countl\_zero](countl_zero "cpp/numeric/countl zero")
(C++20) | counts the number of consecutive 0 bits, starting from the most significant bit (function template) |
cpp std::countr_one std::countr\_one
================
| Defined in header `[<bit>](../header/bit "cpp/header/bit")` | | |
| --- | --- | --- |
|
```
template< class T >
constexpr int countr_one( T x ) noexcept;
```
| | (since C++20) |
Returns the number of consecutive 1 bits in the value of `x`, starting from the least significant bit ("right").
This overload participates in overload resolution only if `T` is an unsigned integer type (that is, `unsigned char`, `unsigned short`, `unsigned int`, `unsigned long`, `unsigned long long`, or an extended unsigned integer type).
### Parameters
| | | |
| --- | --- | --- |
| x | - | value of unsigned integer type |
### Return value
The number of consecutive 1 bits in the value of `x`, starting from the least significant bit.
### Notes
| [Feature-test](../utility/feature_test "cpp/utility/feature test") macro |
| --- |
| [`__cpp_lib_bitops`](../feature_test#Library_features "cpp/feature test") |
### Example
```
#include <bit>
#include <bitset>
#include <cstdint>
#include <iostream>
int main()
{
for (const std::uint8_t i : { 0, 0b11111111, 0b11111110, 0b11100011 }) {
std::cout << "countr_one( " << std::bitset<8>(i) << " ) = "
<< std::countr_one(i) << '\n';
}
}
```
Output:
```
countr_one( 00000000 ) = 0
countr_one( 11111111 ) = 8
countr_one( 11111110 ) = 0
countr_one( 11100011 ) = 2
```
### See also
| | |
| --- | --- |
| [countl\_zero](countl_zero "cpp/numeric/countl zero")
(C++20) | counts the number of consecutive 0 bits, starting from the most significant bit (function template) |
| [countl\_one](countl_one "cpp/numeric/countl one")
(C++20) | counts the number of consecutive 1 bits, starting from the most significant bit (function template) |
| [countr\_zero](countr_zero "cpp/numeric/countr zero")
(C++20) | counts the number of consecutive 0 bits, starting from the least significant bit (function template) |
| [popcount](popcount "cpp/numeric/popcount")
(C++20) | counts the number of 1 bits in an unsigned integer (function template) |
| [has\_single\_bit](has_single_bit "cpp/numeric/has single bit")
(C++20) | checks if a number is an integral power of two (function template) |
| [count](../utility/bitset/count "cpp/utility/bitset/count") | returns the number of bits set to `true` (public member function of `std::bitset<N>`) |
| [allanynone](../utility/bitset/all_any_none "cpp/utility/bitset/all any none")
(C++11) | checks if all, any or none of the bits are set to `true` (public member function of `std::bitset<N>`) |
cpp std::countl_one std::countl\_one
================
| Defined in header `[<bit>](../header/bit "cpp/header/bit")` | | |
| --- | --- | --- |
|
```
template< class T >
constexpr int countl_one( T x ) noexcept;
```
| | (since C++20) |
Returns the number of consecutive 1 ("one") bits in the value of `x`, starting from the most significant bit ("left").
This overload participates in overload resolution only if `T` is an unsigned integer type (that is, `unsigned char`, `unsigned short`, `unsigned int`, `unsigned long`, `unsigned long long`, or an extended unsigned integer type).
### Parameters
| | | |
| --- | --- | --- |
| x | - | value of unsigned integer type |
### Return value
The number of consecutive 1 bits in the value of `x`, starting from the most significant bit.
### Notes
| [Feature-test](../utility/feature_test "cpp/utility/feature test") macro |
| --- |
| [`__cpp_lib_bitops`](../feature_test#Library_features "cpp/feature test") |
### Example
```
#include <bit>
#include <bitset>
#include <cstdint>
#include <iostream>
int main()
{
for (const std::uint8_t i : { 0, 0b11111111, 0b01111111, 0b11100011 }) {
std::cout << "countl_one( " << std::bitset<8>(i) << " ) = "
<< std::countl_one(i) << '\n';
}
}
```
Output:
```
countl_one( 00000000 ) = 0
countl_one( 11111111 ) = 8
countl_one( 01111111 ) = 0
countl_one( 11100011 ) = 3
```
### See also
| | |
| --- | --- |
| [countl\_zero](countl_zero "cpp/numeric/countl zero")
(C++20) | counts the number of consecutive 0 bits, starting from the most significant bit (function template) |
| [countr\_zero](countr_zero "cpp/numeric/countr zero")
(C++20) | counts the number of consecutive 0 bits, starting from the least significant bit (function template) |
| [countr\_one](countr_one "cpp/numeric/countr one")
(C++20) | counts the number of consecutive 1 bits, starting from the least significant bit (function template) |
| [popcount](popcount "cpp/numeric/popcount")
(C++20) | counts the number of 1 bits in an unsigned integer (function template) |
| [has\_single\_bit](has_single_bit "cpp/numeric/has single bit")
(C++20) | checks if a number is an integral power of two (function template) |
| [count](../utility/bitset/count "cpp/utility/bitset/count") | returns the number of bits set to `true` (public member function of `std::bitset<N>`) |
| [allanynone](../utility/bitset/all_any_none "cpp/utility/bitset/all any none")
(C++11) | checks if all, any or none of the bits are set to `true` (public member function of `std::bitset<N>`) |
cpp std::countr_zero std::countr\_zero
=================
| Defined in header `[<bit>](../header/bit "cpp/header/bit")` | | |
| --- | --- | --- |
|
```
template< class T >
constexpr int countr_zero( T x ) noexcept;
```
| | (since C++20) |
Returns the number of consecutive 0 bits in the value of `x`, starting from the least significant bit ("right").
This overload participates in overload resolution only if `T` is an unsigned integer type (that is, `unsigned char`, `unsigned short`, `unsigned int`, `unsigned long`, `unsigned long long`, or an extended unsigned integer type).
### Parameters
| | | |
| --- | --- | --- |
| x | - | value of unsigned integer type |
### Return value
The number of consecutive 0 bits in the value of `x`, starting from the least significant bit.
### Notes
| [Feature-test](../utility/feature_test "cpp/utility/feature test") macro |
| --- |
| [`__cpp_lib_bitops`](../feature_test#Library_features "cpp/feature test") |
### Example
```
#include <bit>
#include <bitset>
#include <cstdint>
#include <iostream>
int main()
{
for (const std::uint8_t i : { 0, 0b11111111, 0b00011100, 0b00011101 }) {
std::cout << "countr_zero( " << std::bitset<8>(i) << " ) = "
<< std::countr_zero(i) << '\n';
}
}
```
Output:
```
countr_zero( 00000000 ) = 8
countr_zero( 11111111 ) = 0
countr_zero( 00011100 ) = 2
countr_zero( 00011101 ) = 0
```
### See also
| | |
| --- | --- |
| [countl\_zero](countl_zero "cpp/numeric/countl zero")
(C++20) | counts the number of consecutive 0 bits, starting from the most significant bit (function template) |
| [countl\_one](countl_one "cpp/numeric/countl one")
(C++20) | counts the number of consecutive 1 bits, starting from the most significant bit (function template) |
| [countr\_one](countr_one "cpp/numeric/countr one")
(C++20) | counts the number of consecutive 1 bits, starting from the least significant bit (function template) |
| [popcount](popcount "cpp/numeric/popcount")
(C++20) | counts the number of 1 bits in an unsigned integer (function template) |
| [allanynone](../utility/bitset/all_any_none "cpp/utility/bitset/all any none")
(C++11) | checks if all, any or none of the bits are set to `true` (public member function of `std::bitset<N>`) |
cpp std::bit_floor std::bit\_floor
===============
| Defined in header `[<bit>](../header/bit "cpp/header/bit")` | | |
| --- | --- | --- |
|
```
template< class T >
constexpr T bit_floor( T x ) noexcept;
```
| | (since C++20) |
If `x` is not zero, calculates the largest integral power of two that is not greater than `x`. If `x` is zero, returns zero.
This overload participates in overload resolution only if `T` is an unsigned integer type (that is, `unsigned char`, `unsigned short`, `unsigned int`, `unsigned long`, `unsigned long long`, or an extended unsigned integer type).
### Parameters
| | | |
| --- | --- | --- |
| x | - | unsigned integer value |
### Return value
Zero if `x` is zero; otherwise, the largest integral power of two that is not greater than `x`.
### Notes
| [Feature-test](../utility/feature_test "cpp/utility/feature test") macro |
| --- |
| [`__cpp_lib_int_pow2`](../feature_test#Library_features "cpp/feature test") |
### Possible implementation
| |
| --- |
|
```
template <std::unsigned_integral T>
requires !std::same_as<T, bool> && !std::same_as<T, char> &&
!std::same_as<T, char8_t> && !std::same_as<T, char16_t> &&
!std::same_as<T, char32_t> && !std::same_as<T, wchar_t>
constexpr T bit_floor(T x) noexcept
{
if (x != 0)
return T{1} << (std::bit_width(x) - 1);
return 0;
}
```
|
### Example
```
#include <bit>
#include <bitset>
#include <iostream>
int main()
{
using bin = std::bitset<8>;
for (unsigned x = 0; x != 10; ++x)
{
auto const z = std::bit_floor(x); // `floor2` before P1956R1
std::cout << "bit_floor( " << bin(x) << " ) = " << bin(z) << '\n';
}
}
```
Output:
```
bit_floor( 00000000 ) = 00000000
bit_floor( 00000001 ) = 00000001
bit_floor( 00000010 ) = 00000010
bit_floor( 00000011 ) = 00000010
bit_floor( 00000100 ) = 00000100
bit_floor( 00000101 ) = 00000100
bit_floor( 00000110 ) = 00000100
bit_floor( 00000111 ) = 00000100
bit_floor( 00001000 ) = 00001000
bit_floor( 00001001 ) = 00001000
```
### See also
| | |
| --- | --- |
| [bit\_ceil](bit_ceil "cpp/numeric/bit ceil")
(C++20) | finds the smallest integral power of two not less than the given value (function template) |
| [rotr](rotr "cpp/numeric/rotr")
(C++20) | computes the result of bitwise right-rotation (function template) |
| [bit\_width](bit_width "cpp/numeric/bit width")
(C++20) | finds the smallest number of bits needed to represent the given value (function template) |
| [has\_single\_bit](has_single_bit "cpp/numeric/has single bit")
(C++20) | checks if a number is an integral power of two (function template) |
cpp std::valarray std::valarray
=============
| Defined in header `[<valarray>](../header/valarray "cpp/header/valarray")` | | |
| --- | --- | --- |
|
```
template< class T >
class valarray;
```
| | |
`std::valarray` is the class for representing and manipulating arrays of values. It supports element-wise mathematical operations and various forms of generalized subscript operators, slicing and indirect access.
### Notes
`std::valarray` and helper classes are defined to be free of certain forms of aliasing, thus allowing operations on these classes to be optimized similar to the effect of the keyword [restrict](https://en.cppreference.com/w/c/language/restrict "c/language/restrict") in the C programming language. In addition, functions and operators that take `valarray` arguments are allowed to return proxy objects to make it possible for the compiler to optimize an expression such as `v1 = a*v2 + v3;` as a single loop that executes `v1[i] = a*v2[i] + v3[i];` avoiding any temporaries or multiple passes. However, [expression templates](https://en.wikipedia.org/wiki/Expression_templates "enwiki:Expression templates") make the same optimization technique available for any C++ container, and the majority of numeric libraries prefer expression templates to valarrays for flexibility. Some C++ standard library implementations use expression templates to implement efficient operations on `std::valarray` (e.g. GNU libstdc++ and LLVM libc++). Only rarely are valarrays optimized any further, as in e.g. [Intel Integrated Performance Primitives](https://software.intel.com/en-us/node/684140).
### Template parameters
| | | |
| --- | --- | --- |
| T | - | the type of the elements. The type must meet the [NumericType](../named_req/numerictype "cpp/named req/NumericType") requirements |
### Member types
| Member type | Definition |
| --- | --- |
| `value_type` | `T` |
### Member functions
| | |
| --- | --- |
| [(constructor)](valarray/valarray "cpp/numeric/valarray/valarray") | constructs new numeric array (public member function) |
| [(destructor)](valarray/~valarray "cpp/numeric/valarray/~valarray") | destructs the numeric array (public member function) |
| [operator=](valarray/operator= "cpp/numeric/valarray/operator=") | assigns the contents (public member function) |
| [operator[]](valarray/operator_at "cpp/numeric/valarray/operator at") | get/set valarray element, slice, or mask (public member function) |
| [operator+operator-operator~operator!](valarray/operator_arith "cpp/numeric/valarray/operator arith") | applies a unary arithmetic operator to each element of the valarray (public member function) |
| [operator+=operator-=operator\*=operator/=operator%=operator&=operator|=operator^=operator<<=operator>>=](valarray/operator_arith2 "cpp/numeric/valarray/operator arith2") | applies compound assignment operator to each element of the valarray (public member function) |
| [swap](valarray/swap "cpp/numeric/valarray/swap") | swaps with another valarray (public member function) |
| [size](valarray/size "cpp/numeric/valarray/size") | returns the size of valarray (public member function) |
| [resize](valarray/resize "cpp/numeric/valarray/resize") | changes the size of valarray (public member function) |
| [sum](valarray/sum "cpp/numeric/valarray/sum") | calculates the sum of all elements (public member function) |
| [min](valarray/min "cpp/numeric/valarray/min") | returns the smallest element (public member function) |
| [max](valarray/max "cpp/numeric/valarray/max") | returns the largest element (public member function) |
| [shift](valarray/shift "cpp/numeric/valarray/shift") | zero-filling shift the elements of the valarray (public member function) |
| [cshift](valarray/cshift "cpp/numeric/valarray/cshift") | circular shift of the elements of the valarray (public member function) |
| [apply](valarray/apply "cpp/numeric/valarray/apply") | applies a function to every element of a valarray (public member function) |
### Non-member functions
| | |
| --- | --- |
| [std::swap(std::valarray)](valarray/swap2 "cpp/numeric/valarray/swap2")
(C++11) | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) |
| [std::begin(std::valarray)](valarray/begin2 "cpp/numeric/valarray/begin2")
(C++11) | overloads `[std::begin](../iterator/begin "cpp/iterator/begin")` (function template) |
| [std::end(std::valarray)](valarray/end2 "cpp/numeric/valarray/end2")
(C++11) | specializes `[std::end](../iterator/end "cpp/iterator/end")` (function template) |
| [operator+operator-operator\*operator/operator%operator&operator|operator^operator<<operator>>operator&&operator||](valarray/operator_arith3 "cpp/numeric/valarray/operator arith3") | applies binary operators to each element of two valarrays, or a valarray and a value (function template) |
| [operator==operator!=operator<operator<=operator>operator>=](valarray/operator_cmp "cpp/numeric/valarray/operator cmp") | compares two valarrays or a valarray with a value (function template) |
| [abs(std::valarray)](valarray/abs "cpp/numeric/valarray/abs") | applies the function `abs` to each element of valarray (function template) |
| Exponential functions |
| [exp(std::valarray)](valarray/exp "cpp/numeric/valarray/exp") | applies the function `[std::exp](math/exp "cpp/numeric/math/exp")` to each element of valarray (function template) |
| [log(std::valarray)](valarray/log "cpp/numeric/valarray/log") | applies the function `[std::log](math/log "cpp/numeric/math/log")` to each element of valarray (function template) |
| [log10(std::valarray)](valarray/log10 "cpp/numeric/valarray/log10") | applies the function `[std::log10](math/log10 "cpp/numeric/math/log10")` to each element of valarray (function template) |
| Power functions |
| [pow(std::valarray)](valarray/pow "cpp/numeric/valarray/pow") | applies the function `[std::pow](math/pow "cpp/numeric/math/pow")` to two valarrays or a valarray and a value (function template) |
| [sqrt(std::valarray)](valarray/sqrt "cpp/numeric/valarray/sqrt") | applies the function `[std::sqrt](math/sqrt "cpp/numeric/math/sqrt")` to each element of valarray (function template) |
| Trigonometric functions |
| [sin(std::valarray)](valarray/sin "cpp/numeric/valarray/sin") | applies the function `[std::sin](math/sin "cpp/numeric/math/sin")` to each element of valarray (function template) |
| [cos(std::valarray)](valarray/cos "cpp/numeric/valarray/cos") | applies the function `[std::cos](math/cos "cpp/numeric/math/cos")` to each element of valarray (function template) |
| [tan(std::valarray)](valarray/tan "cpp/numeric/valarray/tan") | applies the function `[std::tan](math/tan "cpp/numeric/math/tan")` to each element of valarray (function template) |
| [asin(std::valarray)](valarray/asin "cpp/numeric/valarray/asin") | applies the function `[std::asin](math/asin "cpp/numeric/math/asin")` to each element of valarray (function template) |
| [acos(std::valarray)](valarray/acos "cpp/numeric/valarray/acos") | applies the function `[std::acos](math/acos "cpp/numeric/math/acos")` to each element of valarray (function template) |
| [atan(std::valarray)](valarray/atan "cpp/numeric/valarray/atan") | applies the function `[std::atan](math/atan "cpp/numeric/math/atan")` to each element of valarray (function template) |
| [atan2(std::valarray)](valarray/atan2 "cpp/numeric/valarray/atan2") | applies the function `[std::atan2](math/atan2 "cpp/numeric/math/atan2")` to a valarray and a value (function template) |
| Hyperbolic functions |
| [sinh(std::valarray)](valarray/sinh "cpp/numeric/valarray/sinh") | applies the function `[std::sinh](math/sinh "cpp/numeric/math/sinh")` to each element of valarray (function template) |
| [cosh(std::valarray)](valarray/cosh "cpp/numeric/valarray/cosh") | applies the function `[std::cosh](math/cosh "cpp/numeric/math/cosh")` to each element of valarray (function template) |
| [tanh(std::valarray)](valarray/tanh "cpp/numeric/valarray/tanh") | applies the function `[std::tanh](math/tanh "cpp/numeric/math/tanh")` to each element of valarray (function template) |
### Helper classes
| | |
| --- | --- |
| [slice](valarray/slice "cpp/numeric/valarray/slice") | BLAS-like slice of a valarray: starting index, length, stride (class) |
| [slice\_array](valarray/slice_array "cpp/numeric/valarray/slice array") | proxy to a subset of a valarray after applying a slice (class template) |
| [gslice](valarray/gslice "cpp/numeric/valarray/gslice") | generalized slice of a valarray: starting index, set of lengths, set of strides (class) |
| [gslice\_array](valarray/gslice_array "cpp/numeric/valarray/gslice array") | proxy to a subset of a valarray after applying a gslice (class template) |
| [mask\_array](valarray/mask_array "cpp/numeric/valarray/mask array") | proxy to a subset of a valarray after applying a boolean mask `operator[]` (class template) |
| [indirect\_array](valarray/indirect_array "cpp/numeric/valarray/indirect array") | proxy to a subset of a valarray after applying indirect `operator[]` (class template) |
### [Deduction guides](valarray/deduction_guides "cpp/numeric/valarray/deduction guides")(since C++17)
| programming_docs |
cpp Common mathematical functions Common mathematical functions
=============================
### Functions
| Defined in header `[<cstdlib>](../header/cstdlib "cpp/header/cstdlib")` |
| --- |
| [abs(int)labsllabs](math/abs "cpp/numeric/math/abs")
(C++11) | computes absolute value of an integral value (\(\small{|x|}\)|x|) (function) |
| [div(int)ldivlldiv](math/div "cpp/numeric/math/div")
(C++11) | computes quotient and remainder of integer division (function) |
| Defined in header `[<cinttypes>](../header/cinttypes "cpp/header/cinttypes")` |
| [abs(std::intmax\_t)imaxabs](math/abs "cpp/numeric/math/abs")
(C++11)(C++11) | computes absolute value of an integral value (\(\small{|x|}\)|x|) (function) |
| [div(std::intmax\_t)imaxdiv](math/div "cpp/numeric/math/div")
(C++11)(C++11) | computes quotient and remainder of integer division (function) |
| Defined in header `[<cmath>](../header/cmath "cpp/header/cmath")` |
| Basic operations |
| [abs(float)fabsfabsffabsl](math/fabs "cpp/numeric/math/fabs")
(C++11)(C++11) | absolute value of a floating point value (\(\small{|x|}\)|x|) (function) |
| [fmodfmodffmodl](math/fmod "cpp/numeric/math/fmod")
(C++11)(C++11) | remainder of the floating point division operation (function) |
| [remainderremainderfremainderl](math/remainder "cpp/numeric/math/remainder")
(C++11)(C++11)(C++11) | signed remainder of the division operation (function) |
| [remquoremquofremquol](math/remquo "cpp/numeric/math/remquo")
(C++11)(C++11)(C++11) | signed remainder as well as the three last bits of the division operation (function) |
| [fmafmaffmal](math/fma "cpp/numeric/math/fma")
(C++11)(C++11)(C++11) | fused multiply-add operation (function) |
| [fmaxfmaxffmaxl](math/fmax "cpp/numeric/math/fmax")
(C++11)(C++11)(C++11) | larger of two floating-point values (function) |
| [fminfminffminl](math/fmin "cpp/numeric/math/fmin")
(C++11)(C++11)(C++11) | smaller of two floating point values (function) |
| [fdimfdimffdiml](math/fdim "cpp/numeric/math/fdim")
(C++11)(C++11)(C++11) | positive difference of two floating point values (\({\small\max{(0, x-y)} }\)max(0, x-y)) (function) |
| [nannanfnanl](math/nan "cpp/numeric/math/nan")
(C++11)(C++11)(C++11) | not-a-number (NaN) (function) |
| Exponential functions |
| [expexpfexpl](math/exp "cpp/numeric/math/exp")
(C++11)(C++11) | returns *e* raised to the given power (\({\small e^x}\)ex) (function) |
| [exp2exp2fexp2l](math/exp2 "cpp/numeric/math/exp2")
(C++11)(C++11)(C++11) | returns *2* raised to the given power (\({\small 2^x}\)2x) (function) |
| [expm1expm1fexpm1l](math/expm1 "cpp/numeric/math/expm1")
(C++11)(C++11)(C++11) | returns *e* raised to the given power, minus one (\({\small e^x-1}\)ex-1) (function) |
| [loglogflogl](math/log "cpp/numeric/math/log")
(C++11)(C++11) | computes natural (base *e*) logarithm (\({\small \ln{x} }\)ln(x)) (function) |
| [log10log10flog10l](math/log10 "cpp/numeric/math/log10")
(C++11)(C++11) | computes common (base *10*) logarithm (\({\small \log\_{10}{x} }\)log10(x)) (function) |
| [log2log2flog2l](math/log2 "cpp/numeric/math/log2")
(C++11)(C++11)(C++11) | base 2 logarithm of the given number (\({\small \log\_{2}{x} }\)log2(x)) (function) |
| [log1plog1pflog1pl](math/log1p "cpp/numeric/math/log1p")
(C++11)(C++11)(C++11) | natural logarithm (to base *e*) of 1 plus the given number (\({\small \ln{(1+x)} }\)ln(1+x)) (function) |
| Power functions |
| [powpowfpowl](math/pow "cpp/numeric/math/pow")
(C++11)(C++11) | raises a number to the given power (\(\small{x^y}\)xy) (function) |
| [sqrtsqrtfsqrtl](math/sqrt "cpp/numeric/math/sqrt")
(C++11)(C++11) | computes square root (\(\small{\sqrt{x} }\)โx) (function) |
| [cbrtcbrtfcbrtl](math/cbrt "cpp/numeric/math/cbrt")
(C++11)(C++11)(C++11) | computes cubic root (\(\small{\sqrt[3]{x} }\)3โx) (function) |
| [hypothypotfhypotl](math/hypot "cpp/numeric/math/hypot")
(C++11)(C++11)(C++11) | computes square root of the sum of the squares of two or three (C++17) given numbers (\(\scriptsize{\sqrt{x^2+y^2} }\)โx2+y2), (\(\scriptsize{\sqrt{x^2+y^2+z^2} }\)โx2+y2+z2) (function) |
| Trigonometric functions |
| [sinsinfsinl](math/sin "cpp/numeric/math/sin")
(C++11)(C++11) | computes sine (\({\small\sin{x} }\)sin(x)) (function) |
| [coscosfcosl](math/cos "cpp/numeric/math/cos")
(C++11)(C++11) | computes cosine (\({\small\cos{x} }\)cos(x)) (function) |
| [tantanftanl](math/tan "cpp/numeric/math/tan")
(C++11)(C++11) | computes tangent (\({\small\tan{x} }\)tan(x)) (function) |
| [asinasinfasinl](math/asin "cpp/numeric/math/asin")
(C++11)(C++11) | computes arc sine (\({\small\arcsin{x} }\)arcsin(x)) (function) |
| [acosacosfacosl](math/acos "cpp/numeric/math/acos")
(C++11)(C++11) | computes arc cosine (\({\small\arccos{x} }\)arccos(x)) (function) |
| [atanatanfatanl](math/atan "cpp/numeric/math/atan")
(C++11)(C++11) | computes arc tangent (\({\small\arctan{x} }\)arctan(x)) (function) |
| [atan2atan2fatan2l](math/atan2 "cpp/numeric/math/atan2")
(C++11)(C++11) | arc tangent, using signs to determine quadrants (function) |
| Hyperbolic functions |
| [sinhsinhfsinhl](math/sinh "cpp/numeric/math/sinh")
(C++11)(C++11) | computes hyperbolic sine (\({\small\sinh{x} }\)sinh(x)) (function) |
| [coshcoshfcoshl](math/cosh "cpp/numeric/math/cosh")
(C++11)(C++11) | computes hyperbolic cosine (\({\small\cosh{x} }\)cosh(x)) (function) |
| [tanhtanhftanhl](math/tanh "cpp/numeric/math/tanh")
(C++11)(C++11) | computes hyperbolic tangent (\({\small\tanh{x} }\)tanh(x)) (function) |
| [asinhasinhfasinhl](math/asinh "cpp/numeric/math/asinh")
(C++11)(C++11)(C++11) | computes the inverse hyperbolic sine (\({\small\operatorname{arsinh}{x} }\)arsinh(x)) (function) |
| [acoshacoshfacoshl](math/acosh "cpp/numeric/math/acosh")
(C++11)(C++11)(C++11) | computes the inverse hyperbolic cosine (\({\small\operatorname{arcosh}{x} }\)arcosh(x)) (function) |
| [atanhatanhfatanhl](math/atanh "cpp/numeric/math/atanh")
(C++11)(C++11)(C++11) | computes the inverse hyperbolic tangent (\({\small\operatorname{artanh}{x} }\)artanh(x)) (function) |
| Error and gamma functions |
| [erferfferfl](math/erf "cpp/numeric/math/erf")
(C++11)(C++11)(C++11) | error function (function) |
| [erfcerfcferfcl](math/erfc "cpp/numeric/math/erfc")
(C++11)(C++11)(C++11) | complementary error function (function) |
| [tgammatgammaftgammal](math/tgamma "cpp/numeric/math/tgamma")
(C++11)(C++11)(C++11) | gamma function (function) |
| [lgammalgammaflgammal](math/lgamma "cpp/numeric/math/lgamma")
(C++11)(C++11)(C++11) | natural logarithm of the gamma function (function) |
| Nearest integer floating point operations |
| [ceilceilfceill](math/ceil "cpp/numeric/math/ceil")
(C++11)(C++11) | nearest integer not less than the given value (function) |
| [floorfloorffloorl](math/floor "cpp/numeric/math/floor")
(C++11)(C++11) | nearest integer not greater than the given value (function) |
| [trunctruncftruncl](math/trunc "cpp/numeric/math/trunc")
(C++11)(C++11)(C++11) | nearest integer not greater in magnitude than the given value (function) |
| [roundroundfroundllroundlroundflroundlllroundllroundfllroundl](math/round "cpp/numeric/math/round")
(C++11)(C++11)(C++11)(C++11)(C++11)(C++11)(C++11)(C++11)(C++11) | nearest integer, rounding away from zero in halfway cases (function) |
| [nearbyintnearbyintfnearbyintl](math/nearbyint "cpp/numeric/math/nearbyint")
(C++11)(C++11)(C++11) | nearest integer using current rounding mode (function) |
| [rintrintfrintllrintlrintflrintlllrintllrintfllrintl](math/rint "cpp/numeric/math/rint")
(C++11)(C++11)(C++11)(C++11)(C++11)(C++11)(C++11)(C++11)(C++11) | nearest integer using current rounding mode with exception if the result differs (function) |
| Floating point manipulation functions |
| [frexpfrexpffrexpl](math/frexp "cpp/numeric/math/frexp")
(C++11)(C++11) | decomposes a number into significand and a power of `2` (function) |
| [ldexpldexpfldexpl](math/ldexp "cpp/numeric/math/ldexp")
(C++11)(C++11) | multiplies a number by `2` raised to a power (function) |
| [modfmodffmodfl](math/modf "cpp/numeric/math/modf")
(C++11)(C++11) | decomposes a number into integer and fractional parts (function) |
| [scalbnscalbnfscalbnlscalblnscalblnfscalblnl](math/scalbn "cpp/numeric/math/scalbn")
(C++11)(C++11)(C++11)(C++11)(C++11)(C++11) | multiplies a number by `[FLT\_RADIX](../types/climits "cpp/types/climits")` raised to a power (function) |
| [ilogbilogbfilogbl](math/ilogb "cpp/numeric/math/ilogb")
(C++11)(C++11)(C++11) | extracts exponent of the number (function) |
| [logblogbflogbl](math/logb "cpp/numeric/math/logb")
(C++11)(C++11)(C++11) | extracts exponent of the number (function) |
| [nextafternextafterfnextafterlnexttowardnexttowardfnexttowardl](math/nextafter "cpp/numeric/math/nextafter")
(C++11)(C++11) (C++11)(C++11)(C++11)(C++11) | next representable floating point value towards the given value (function) |
| [copysigncopysignfcopysignl](math/copysign "cpp/numeric/math/copysign")
(C++11)(C++11)(C++11) | copies the sign of a floating point value (function) |
| Classification and comparison |
| [fpclassify](math/fpclassify "cpp/numeric/math/fpclassify")
(C++11) | categorizes the given floating-point value (function) |
| [isfinite](math/isfinite "cpp/numeric/math/isfinite")
(C++11) | checks if the given number has finite value (function) |
| [isinf](math/isinf "cpp/numeric/math/isinf")
(C++11) | checks if the given number is infinite (function) |
| [isnan](math/isnan "cpp/numeric/math/isnan")
(C++11) | checks if the given number is NaN (function) |
| [isnormal](math/isnormal "cpp/numeric/math/isnormal")
(C++11) | checks if the given number is normal (function) |
| [signbit](math/signbit "cpp/numeric/math/signbit")
(C++11) | checks if the given number is negative (function) |
| [isgreater](math/isgreater "cpp/numeric/math/isgreater")
(C++11) | checks if the first floating-point argument is greater than the second (function) |
| [isgreaterequal](math/isgreaterequal "cpp/numeric/math/isgreaterequal")
(C++11) | checks if the first floating-point argument is greater or equal than the second (function) |
| [isless](math/isless "cpp/numeric/math/isless")
(C++11) | checks if the first floating-point argument is less than the second (function) |
| [islessequal](math/islessequal "cpp/numeric/math/islessequal")
(C++11) | checks if the first floating-point argument is less or equal than the second (function) |
| [islessgreater](math/islessgreater "cpp/numeric/math/islessgreater")
(C++11) | checks if the first floating-point argument is less or greater than the second (function) |
| [isunordered](math/isunordered "cpp/numeric/math/isunordered")
(C++11) | checks if two floating-point values are unordered (function) |
### Types
| Defined in header `[<cstdlib>](../header/cstdlib "cpp/header/cstdlib")` |
| --- |
| [div\_t](math/div "cpp/numeric/math/div") | structure type, return of the `[std::div](http://en.cppreference.com/w/cpp/numeric/math/div)` function (typedef) |
| [ldiv\_t](math/div "cpp/numeric/math/div") | structure type, return of the `[std::ldiv](http://en.cppreference.com/w/cpp/numeric/math/div)` function (typedef) |
| [lldiv\_t](math/div "cpp/numeric/math/div")
(C++11) | structure type, return of the `[std::lldiv](http://en.cppreference.com/w/cpp/numeric/math/div)` function (typedef) |
| Defined in header `[<cinttypes>](../header/cinttypes "cpp/header/cinttypes")` |
| [imaxdiv\_t](math/div "cpp/numeric/math/div")
(C++11) | structure type, return of the `[std::imaxdiv](http://en.cppreference.com/w/cpp/numeric/math/div)` function (typedef) |
| Defined in header `[<cmath>](../header/cmath "cpp/header/cmath")` |
| float\_t
(C++11) | most efficient floating-point type at least as wide as `float` (typedef) |
| double\_t
(C++11) | most efficient floating-point type at least as wide as `double` (typedef) |
### Macro constants
| Defined in header `[<cmath>](../header/cmath "cpp/header/cmath")` |
| --- |
| [HUGE\_VALFHUGE\_VALHUGE\_VALL](math/huge_val "cpp/numeric/math/HUGE VAL")
(C++11)(C++11) | indicates the overflow value for `float`, `double` and `long double` respectively (macro constant) |
| [INFINITY](math/infinity "cpp/numeric/math/INFINITY")
(C++11) | evaluates to positive infinity or the value guaranteed to overflow a `float` (macro constant) |
| [NAN](math/nan "cpp/numeric/math/NAN")
(C++11) | evaluates to a quiet NaN of type `float` (macro constant) |
| [math\_errhandlingMATH\_ERRNOMATH\_ERREXCEPT](math/math_errhandling "cpp/numeric/math/math errhandling")
(C++11)(C++11)(C++11) | defines the error handling mechanism used by the common mathematical functions (macro constant) |
| Classification |
| [FP\_NORMALFP\_SUBNORMALFP\_ZEROFP\_INFINITEFP\_NAN](math/fp_categories "cpp/numeric/math/FP categories")
(C++11)(C++11)(C++11)(C++11)(C++11) | indicates a floating-point category (macro constant) |
### Notes
| [Feature-test](../utility/feature_test "cpp/utility/feature test") macro | Value | Std |
| --- | --- | --- |
| [`__cpp_lib_constexpr_cmath`](../feature_test#Library_features "cpp/feature test") | `202202L` | (C++23) |
### See also
| |
| --- |
| **[Mathematical special functions](special_functions "cpp/numeric/special functions")** |
| [C documentation](https://en.cppreference.com/w/c/numeric/math "c/numeric/math") for Common mathematical functions |
cpp std::bit_cast std::bit\_cast
==============
| Defined in header `[<bit>](../header/bit "cpp/header/bit")` | | |
| --- | --- | --- |
|
```
template< class To, class From >
constexpr To bit_cast( const From& from ) noexcept;
```
| | (since C++20) |
Obtain a value of type `To` by reinterpreting the object representation of `From`. Every bit in the value representation of the returned `To` object is equal to the corresponding bit in the object representation of `from`. The values of padding bits in the returned `To` object are unspecified.
If there is no value of type `To` corresponding to the value representation produced, the behavior is undefined. If there are multiple such values, which value is produced is unspecified.
A bit in the value representation of the result is *indeterminate* if it.
* does not correspond to a bit in the value representation of `From` (i.e. it corresponds to a padding bit), or
* corresponds to a bit of an object that is not within its [lifetime](../language/lifetime "cpp/language/lifetime"), or
* has an [indeterminate value](../language/default_initialization "cpp/language/default initialization").
For each bit in the value representation of the result that is indeterminate, the smallest object containing that bit has an indeterminate value; the behavior is undefined unless that object is of `unsigned char` or `std::byte` type. The result does not otherwise contain any indeterminate values.
This overload participates in overload resolution only if `sizeof(To) == sizeof(From)` and both `To` and `From` are [TriviallyCopyable](../named_req/triviallycopyable "cpp/named req/TriviallyCopyable") types.
This function template is `constexpr` if and only if each of `To`, `From` and the types of all subobjects of `To` and `From`:
* is not a union type;
* is not a pointer type;
* is not a pointer to member type;
* is not a volatile-qualified type; and
* has no non-static data member of reference type.
### Parameters
| | | |
| --- | --- | --- |
| from | - | the source of bits for the return value |
### Return value
An object of type `To` whose value representation is as described above.
### Possible implementation
To implement `std::bit_cast`, `[std::memcpy](../string/byte/memcpy "cpp/string/byte/memcpy")` can be used, when it is needed, to interpret the object representation as one of another type:
```
template <class To, class From>
std::enable_if_t<
sizeof(To) == sizeof(From) &&
std::is_trivially_copyable_v<From> &&
std::is_trivially_copyable_v<To>,
To>
// constexpr support needs compiler magic
bit_cast(const From& src) noexcept
{
static_assert(std::is_trivially_constructible_v<To>,
"This implementation additionally requires "
"destination type to be trivially constructible");
To dst;
std::memcpy(&dst, &src, sizeof(To));
return dst;
}
```
### Notes
[`reinterpret_cast`](../language/reinterpret_cast "cpp/language/reinterpret cast") (or equivalent [explicit cast](../language/explicit_cast "cpp/language/explicit cast")) between pointer or reference types shall not be used to reinterpret object representation in most cases because of the [type aliasing rule](../language/reinterpret_cast#Type_aliasing "cpp/language/reinterpret cast").
| [Feature-test](../utility/feature_test "cpp/utility/feature test") macro |
| --- |
| [`__cpp_lib_bit_cast`](../feature_test#Library_features "cpp/feature test") |
### Example
```
#include <cstdint>
#include <bit>
#include <iostream>
constexpr double f64v = 19880124.0;
constexpr auto u64v = std::bit_cast<std::uint64_t>(f64v);
static_assert( std::bit_cast<double>(u64v) == f64v ); // round-trip
constexpr std::uint64_t u64v2 = 0x3fe9000000000000ull;
constexpr auto f64v2 = std::bit_cast<double>(u64v2);
static_assert( std::bit_cast<std::uint64_t>(f64v2) == u64v2 ); // round-trip
int main()
{
std::cout
<< "std::bit_cast<std::uint64_t>(" << std::fixed << f64v << ") == 0x"
<< std::hex << u64v << '\n'
<< "std::bit_cast<double>(0x" << std::hex << u64v2 << ") == "
<< std::fixed << f64v2 << '\n';
}
```
Possible output:
```
std::bit_cast<std::uint64_t>(19880124.000000) == 0x4172f58bc0000000
std::bit_cast<double>(0x3fe9000000000000) == 0.781250
```
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [CWG 2482](https://cplusplus.github.io/CWG/issues/2482.html) | C++20 | it was unspecified whether UB would occur when involving indeterminate bits | specified |
cpp Floating-point environment Floating-point environment
==========================
The floating-point environment is the set of floating-point status flags and control modes supported by the implementation. It is thread-local. Each thread inherits the initial state of its floating-point environment from the parent thread. Floating-point operations modify the floating-point status flags to indicate abnormal results or auxiliary information. The state of floating-point control modes affects the outcomes of some floating-point operations.
The floating-point environment access and modification is only meaningful when [`#pragma STDC FENV_ACCESS`](../preprocessor/impl "cpp/preprocessor/impl") is supported and is set to `ON`. Otherwise the implementation is free to assume that floating-point control modes are always the default ones and that floating-point status flags are never tested or modified. In practice, few current compilers, such as HP aCC, Oracle Studio, or IBM XL, support the `#pragma` explicitly, but most compilers allow meaningful access to the floating-point environment anyway.
### Types
| Defined in header `[<cfenv>](../header/cfenv "cpp/header/cfenv")` |
| --- |
| `fenv_t` | The type representing the entire floating-point environment |
| `fexcept_t` | The type representing all floating-point status flags collectively |
### Functions
| | |
| --- | --- |
| [feclearexcept](fenv/feclearexcept "cpp/numeric/fenv/feclearexcept")
(C++11) | clears the specified floating-point status flags (function) |
| [fetestexcept](fenv/fetestexcept "cpp/numeric/fenv/fetestexcept")
(C++11) | determines which of the specified floating-point status flags are set (function) |
| [feraiseexcept](fenv/feraiseexcept "cpp/numeric/fenv/feraiseexcept")
(C++11) | raises the specified floating-point exceptions (function) |
| [fegetexceptflagfesetexceptflag](fenv/feexceptflag "cpp/numeric/fenv/feexceptflag")
(C++11)(C++11) | copies the state of the specified floating-point status flags from or to the floating-point environment (function) |
| [fegetroundfesetround](fenv/feround "cpp/numeric/fenv/feround")
(C++11)(C++11) | gets or sets rounding direction (function) |
| [fegetenvfesetenv](fenv/feenv "cpp/numeric/fenv/feenv")
(C++11) | saves or restores the current floating-point environment (function) |
| [feholdexcept](fenv/feholdexcept "cpp/numeric/fenv/feholdexcept")
(C++11) | saves the environment, clears all status flags and ignores all future errors (function) |
| [feupdateenv](fenv/feupdateenv "cpp/numeric/fenv/feupdateenv")
(C++11) | restores the floating-point environment and raises the previously raise exceptions (function) |
### Macros
| | |
| --- | --- |
| [FE\_ALL\_EXCEPTFE\_DIVBYZEROFE\_INEXACTFE\_INVALIDFE\_OVERFLOWFE\_UNDERFLOW](fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")
(C++11) | floating-point exceptions (macro constant) |
| [FE\_DOWNWARDFE\_TONEARESTFE\_TOWARDZEROFE\_UPWARD](fenv/fe_round "cpp/numeric/fenv/FE round")
(C++11) | floating-point rounding direction (macro constant) |
| [FE\_DFL\_ENV](fenv/fe_dfl_env "cpp/numeric/fenv/FE DFL ENV")
(C++11) | default floating-point environment (macro constant) |
### Notes
The floating-point exceptions are not related to the C++ exceptions. When a floating-point operation raises a floating-point exception, the status of the floating-point environment changes, which can be tested with `[std::fetestexcept](fenv/fetestexcept "cpp/numeric/fenv/fetestexcept")`, but the execution of a C++ program on most implementations continues uninterrupted.
There are compiler extensions that may be used to generate C++ exceptions automatically whenever a floating-point exception is raised:
* GNU libc function `[feenableexcept()](http://www.gnu.org/s/hello/manual/libc/Control-Functions.html)` enables trapping of the floating-point exceptions, which generates the signal `SIGFPE`. If the compiler option `-fnon-call-exceptions` was used, the handler for that signal may throw a user-defined C++ exception.
* MSVC function `[\_control87()](http://msdn.microsoft.com/en-us/library/e9b52ceh.aspx)` enables trapping of the floating-point exceptions, which generates a hardware exception, which can be converted to C++ exceptions with `[\_set\_se\_translator](http://msdn.microsoft.com/en-us/library/5z4bw5h5.aspx)`.
### See also
| |
| --- |
| [C documentation](https://en.cppreference.com/w/c/numeric/fenv "c/numeric/fenv") for `Floating-point environment` |
| programming_docs |
cpp std::complex std::complex
============
| Defined in header `[<complex>](../header/complex "cpp/header/complex")` | | |
| --- | --- | --- |
|
```
template< class T >
class complex;
```
| (1) | |
|
```
template<> class complex<float>;
```
| (2) | |
|
```
template<> class complex<double>;
```
| (3) | |
|
```
template<> class complex<long double>;
```
| (4) | |
The specializations `std::complex<float>`, `std::complex<double>`, and `std::complex<long double>` are [LiteralTypes](../named_req/literaltype "cpp/named req/LiteralType") for representing and manipulating [complex numbers](https://en.wikipedia.org/wiki/Complex_number "enwiki:Complex number").
### Template parameters
| | | |
| --- | --- | --- |
| T | - | the type of the real and imaginary components. The behavior is unspecified (and may fail to compile) if T is not `float`, `double`, or `long double` and undefined if T is not [NumericType](../named_req/numerictype "cpp/named req/NumericType"). |
### Member types
| Member type | Definition |
| --- | --- |
| `value_type` | `T` |
### Member functions
| | |
| --- | --- |
| [(constructor)](complex/complex "cpp/numeric/complex/complex") | constructs a complex number (public member function) |
| [operator=](complex/operator= "cpp/numeric/complex/operator=") | assigns the contents (public member function) |
| [real](complex/real "cpp/numeric/complex/real") | accesses the real part of the complex number (public member function) |
| [imag](complex/imag "cpp/numeric/complex/imag") | accesses the imaginary part of the complex number (public member function) |
| [operator+=operator-=operator\*=operator/=](complex/operator_arith "cpp/numeric/complex/operator arith") | compound assignment of two complex numbers or a complex and a scalar (public member function) |
### Non-member functions
| | |
| --- | --- |
| [operator+operator-](complex/operator_arith2 "cpp/numeric/complex/operator arith2") | applies unary operators to complex numbers (function template) |
| [operator+operator-operator\*operator/](complex/operator_arith3 "cpp/numeric/complex/operator arith3") | performs complex number arithmetics on two complex values or a complex and a scalar (function template) |
| [operator==operator!=](complex/operator_cmp "cpp/numeric/complex/operator cmp")
(removed in C++20) | compares two complex numbers or a complex and a scalar (function template) |
| [operator<<operator>>](complex/operator_ltltgtgt "cpp/numeric/complex/operator ltltgtgt") | serializes and deserializes a complex number (function template) |
| [real](complex/real2 "cpp/numeric/complex/real2") | returns the real component (function template) |
| [imag](complex/imag2 "cpp/numeric/complex/imag2") | returns the imaginary component (function template) |
| [abs(std::complex)](complex/abs "cpp/numeric/complex/abs") | returns the magnitude of a complex number (function template) |
| [arg](complex/arg "cpp/numeric/complex/arg") | returns the phase angle (function template) |
| [norm](complex/norm "cpp/numeric/complex/norm") | returns the squared magnitude (function template) |
| [conj](complex/conj "cpp/numeric/complex/conj") | returns the complex conjugate (function template) |
| [proj](complex/proj "cpp/numeric/complex/proj")
(C++11) | returns the projection onto the Riemann sphere (function template) |
| [polar](complex/polar "cpp/numeric/complex/polar") | constructs a complex number from magnitude and phase angle (function template) |
| Exponential functions |
| [exp(std::complex)](complex/exp "cpp/numeric/complex/exp") | complex base *e* exponential (function template) |
| [log(std::complex)](complex/log "cpp/numeric/complex/log") | complex natural logarithm with the branch cuts along the negative real axis (function template) |
| [log10(std::complex)](complex/log10 "cpp/numeric/complex/log10") | complex common logarithm with the branch cuts along the negative real axis (function template) |
| Power functions |
| [pow(std::complex)](complex/pow "cpp/numeric/complex/pow") | complex power, one or both arguments may be a complex number (function template) |
| [sqrt(std::complex)](complex/sqrt "cpp/numeric/complex/sqrt") | complex square root in the range of the right half-plane (function template) |
| Trigonometric functions |
| [sin(std::complex)](complex/sin "cpp/numeric/complex/sin") | computes sine of a complex number (\({\small\sin{z} }\)sin(z)) (function template) |
| [cos(std::complex)](complex/cos "cpp/numeric/complex/cos") | computes cosine of a complex number (\({\small\cos{z} }\)cos(z)) (function template) |
| [tan(std::complex)](complex/tan "cpp/numeric/complex/tan") | computes tangent of a complex number (\({\small\tan{z} }\)tan(z)) (function template) |
| [asin(std::complex)](complex/asin "cpp/numeric/complex/asin")
(C++11) | computes arc sine of a complex number (\({\small\arcsin{z} }\)arcsin(z)) (function template) |
| [acos(std::complex)](complex/acos "cpp/numeric/complex/acos")
(C++11) | computes arc cosine of a complex number (\({\small\arccos{z} }\)arccos(z)) (function template) |
| [atan(std::complex)](complex/atan "cpp/numeric/complex/atan")
(C++11) | computes arc tangent of a complex number (\({\small\arctan{z} }\)arctan(z)) (function template) |
| Hyperbolic functions |
| [sinh(std::complex)](complex/sinh "cpp/numeric/complex/sinh") | computes hyperbolic sine of a complex number (\({\small\sinh{z} }\)sinh(z)) (function template) |
| [cosh(std::complex)](complex/cosh "cpp/numeric/complex/cosh") | computes hyperbolic cosine of a complex number (\({\small\cosh{z} }\)cosh(z)) (function template) |
| [tanh(std::complex)](complex/tanh "cpp/numeric/complex/tanh") | computes hyperbolic tangent of a complex number (\({\small\tanh{z} }\)tanh(z)) (function template) |
| [asinh(std::complex)](complex/asinh "cpp/numeric/complex/asinh")
(C++11) | computes area hyperbolic sine of a complex number (\({\small\operatorname{arsinh}{z} }\)arsinh(z)) (function template) |
| [acosh(std::complex)](complex/acosh "cpp/numeric/complex/acosh")
(C++11) | computes area hyperbolic cosine of a complex number (\({\small\operatorname{arcosh}{z} }\)arcosh(z)) (function template) |
| [atanh(std::complex)](complex/atanh "cpp/numeric/complex/atanh")
(C++11) | computes area hyperbolic tangent of a complex number (\({\small\operatorname{artanh}{z} }\)artanh(z)) (function template) |
### Array-oriented access
| | |
| --- | --- |
| For any object `z` of type `complex<T>`, `reinterpret_cast<T(&)[2]>(z)[0]` is the real part of z and `reinterpret_cast<T(&)[2]>(z)[1]` is the imaginary part of z.
For any pointer to an element of an array of `complex<T>` named `p` and any valid array index `i`, `reinterpret_cast<T*>(p)[2*i]` is the real part of the complex number `p[i]`, and `reinterpret_cast<T*>(p)[2*i + 1]` is the imaginary part of the complex number `p[i]`
The intent of this requirement is to preserve binary compatibility between the C++ library complex number types and the [C language complex number types](https://en.cppreference.com/w/c/language/arithmetic_types#Complex_floating_types "c/language/arithmetic types") (and arrays thereof), which have an identical object representation requirement. | (since C++11) |
### Implementation notes
| | |
| --- | --- |
| In order to satisfy the requirements of array-oriented access, an implementation is constrained to store the real and imaginary components of a `std::complex` specialization in separate and adjacent memory locations. Possible declarations for its non-static data members include:* an array of type `value_type[2]`, with the first element holding the real component and the second element holding the imaginary component (e.g. Microsoft Visual Studio)
* a single member of type `value_type _Complex` (encapsulating the corresponding [C language complex number type](https://en.cppreference.com/w/c/language/arithmetic_types#Complex_floating_types "c/language/arithmetic types")) (e.g. GNU libstdc++);
* two members of type `value_type`, with the same member access, holding the real and the imaginary components respectively (e.g. LLVM libc++).
An implementation cannot declare additional non-static data members that would occupy storage disjoint from the real and imaginary components, and must ensure that the class template specialization does not contain any padding. The implementation must also ensure that optimizations to array access account for the possibility that a pointer to `value_type` may be aliasing a `std::complex` specialization or array thereof. | (since C++11) |
### Literals
| Defined in inline namespace `std::literals::complex_literals` |
| --- |
| [operator""ifoperator""ioperator""il](complex/operator%22%22i "cpp/numeric/complex/operator\"\"i")
(C++14) | A `std::complex` literal representing pure imaginary number (function) |
### Example
```
#include <iostream>
#include <iomanip>
#include <complex>
#include <cmath>
int main()
{
using namespace std::complex_literals;
std::cout << std::fixed << std::setprecision(1);
std::complex<double> z1 = 1i * 1i; // imaginary unit squared
std::cout << "i * i = " << z1 << '\n';
std::complex<double> z2 = std::pow(1i, 2); // imaginary unit squared
std::cout << "pow(i, 2) = " << z2 << '\n';
const double PI = std::acos(-1); // or std::numbers::pi in C++20
std::complex<double> z3 = std::exp(1i * PI); // Euler's formula
std::cout << "exp(i * pi) = " << z3 << '\n';
std::complex<double> z4 = 1. + 2i, z5 = 1. - 2i; // conjugates
std::cout << "(1+2i)*(1-2i) = " << z4*z5 << '\n';
}
```
Output:
```
i * i = (-1.0,0.0)
pow(i, 2) = (-1.0,0.0)
exp(i * pi) = (-1.0,0.0)
(1+2i)*(1-2i) = (5.0,0.0)
```
### See also
| |
| --- |
| [C documentation](https://en.cppreference.com/w/c/numeric/complex "c/numeric/complex") for Complex number arithmetic |
cpp Mathematical constants Mathematical constants
======================
### Constants (since C++20)
| Defined in header `[<numbers>](../header/numbers "cpp/header/numbers")` |
| --- |
| Defined in namespace `std::numbers` |
| e\_v | [the mathematical constant \(\small e\)e](https://en.wikipedia.org/wiki/E_(mathematical_constant) "enwiki:E (mathematical constant)") (variable template) |
| log2e\_v | \(\log\_{2}e\)log2e (variable template) |
| log10e\_v | \(\log\_{10}e\)log10e (variable template) |
| pi\_v | [the mathematical constant \(\pi\)ฯ](https://en.wikipedia.org/wiki/Pi_(mathematical_constant) "enwiki:Pi (mathematical constant)") (variable template) |
| inv\_pi\_v | \(\frac1\pi\)1/ฯ (variable template) |
| inv\_sqrtpi\_v | \(\frac1{\sqrt\pi}\)1/โฯ (variable template) |
| ln2\_v | \(\ln{2}\)ln 2 (variable template) |
| ln10\_v | \(\ln{10}\)ln 10 (variable template) |
| sqrt2\_v | \(\sqrt2\)โ2 (variable template) |
| sqrt3\_v | \(\sqrt3\)โ3 (variable template) |
| inv\_sqrt3\_v | \(\frac1{\sqrt3}\)1/โ3 (variable template) |
| egamma\_v | [the EulerโMascheroni constant](https://en.wikipedia.org/wiki/Euler%E2%80%93Mascheroni_constant "enwiki:EulerโMascheroni constant") (variable template) |
| phi\_v | [the golden ratio ฮฆ constant](https://en.wikipedia.org/wiki/Golden_ratio "enwiki:Golden ratio") (\(\frac{1+\sqrt5}2\)1 + โ5/2) (variable template) |
| inline constexpr double e | `e_v<double>` (constant) |
| inline constexpr double log2e | `log2e_v<double>` (constant) |
| inline constexpr double log10e | `log10e_v<double>` (constant) |
| inline constexpr double pi | `pi_v<double>` (constant) |
| inline constexpr double inv\_pi | `inv_pi_v<double>` (constant) |
| inline constexpr double inv\_sqrtpi | `inv_sqrtpi_v<double>` (constant) |
| inline constexpr double ln2 | `ln2_v<double>` (constant) |
| inline constexpr double ln10 | `ln10_v<double>` (constant) |
| inline constexpr double sqrt2 | `sqrt2_v<double>` (constant) |
| inline constexpr double sqrt3 | `sqrt3_v<double>` (constant) |
| inline constexpr double inv\_sqrt3 | `inv_sqrt3_v<double>` (constant) |
| inline constexpr double egamma | `egamma_v<double>` (constant) |
| inline constexpr double phi | `phi_v<double>` (constant) |
### Notes
A program that instantiates a primary template of a mathematical constant variable template is ill-formed.
The standard library specializes mathematical constant variable templates for all floating-point types (i.e. `float`, `double` and `long double`).
A program may partially or explicitly specialize a mathematical constant variable template provided that the specialization depends on a program-defined type.
| [Feature-test](../utility/feature_test "cpp/utility/feature test") macro |
| --- |
| [`__cpp_lib_math_constants`](../feature_test#Library_features "cpp/feature test") |
### Example
```
#include <cmath>
#include <iomanip>
#include <iostream>
#include <limits>
#include <numbers>
#include <string_view>
#include <functional>
using std::placeholders::_2;
template <class T>
constexpr auto operator^(T base, decltype(_2)) { return base * base; }
int main()
{
using namespace std::numbers;
std::cout << "The answer is " <<
(((std::sin(e)^_2) + (std::cos(e)^_2)) +
std::pow(e, ln2) + std::sqrt(pi) * inv_sqrtpi +
((std::cosh(pi)^_2) - (std::sinh(pi)^_2)) +
sqrt3 * inv_sqrt3 * log2e * ln2 * log10e * ln10 *
pi * inv_pi + (phi * phi - phi)) *
((sqrt2 * sqrt3)^_2) << '\n';
auto egamma_aprox = [] (unsigned const iterations) {
long double s{}, m{2.0};
for (unsigned c{2}; c != iterations; ++c, ++m) {
const long double t{ std::riemann_zeta(m) / m };
(c & 1) == 0 ? s += t : s -= t;
}
return s;
};
constexpr std::string_view ฮณ {"0.577215664901532860606512090082402"};
std::cout
<< "ฮณ as 10โถ sums of ยฑฮถ(m)/m = "
<< egamma_aprox(1'000'000) << '\n'
<< "ฮณ as egamma_v<float> = "
<< std::setprecision(std::numeric_limits<float>::digits10 + 1)
<< egamma_v<float> << '\n'
<< "ฮณ as egamma_v<double> = "
<< std::setprecision(std::numeric_limits<double>::digits10 + 1)
<< egamma_v<double> << '\n'
<< "ฮณ as egamma_v<long double> = "
<< std::setprecision(std::numeric_limits<long double>::digits10 + 1)
<< egamma_v<long double> << '\n'
<< "ฮณ with " << ฮณ.length() - 1 << " digits precision = " << ฮณ << '\n';
}
```
Possible output:
```
The answer is 42
ฮณ as 10โถ sums of ยฑฮถ(m)/m = 0.577215
ฮณ as egamma_v<float> = 0.5772157
ฮณ as egamma_v<double> = 0.5772156649015329
ฮณ as egamma_v<long double> = 0.5772156649015328606
ฮณ with 34 digits precision = 0.577215664901532860606512090082402
```
### See also
| | |
| --- | --- |
| [ratio](ratio/ratio "cpp/numeric/ratio/ratio")
(C++11) | represents exact rational fraction (class template) |
cpp std::bit_ceil std::bit\_ceil
==============
| Defined in header `[<bit>](../header/bit "cpp/header/bit")` | | |
| --- | --- | --- |
|
```
template< class T >
constexpr T bit_ceil( T x );
```
| | (since C++20) |
Calculates the smallest integral power of two that is not smaller than `x`.
If that value is not representable in `T`, the behavior is undefined. Call to this function is permitted in [constant evaluation](../language/constant_expression "cpp/language/constant expression") only if the undefined behavior does not occur.
This overload participates in overload resolution only if `T` is an unsigned integer type (that is, `unsigned char`, `unsigned short`, `unsigned int`, `unsigned long`, `unsigned long long`, or an extended unsigned integer type).
### Parameters
| | | |
| --- | --- | --- |
| x | - | value of unsigned integer type |
### Return value
The smallest integral power of two that is not smaller than `x`.
### Exceptions
Throws nothing.
### Notes
| [Feature-test](../utility/feature_test "cpp/utility/feature test") macro |
| --- |
| [`__cpp_lib_int_pow2`](../feature_test#Library_features "cpp/feature test") |
### Possible implementation
See possible implementations in [libstdc++ (gcc)](https://github.com/gcc-mirror/gcc/blob/62c25d7adb1a5664982449dda0e7f9ca63cf4735/libstdc%2B%2B-v3/include/std/bit#L217-L248) and [libc++ (clang)](https://github.com/llvm/llvm-project/blob/llvmorg-14.0.4/libcxx/include/bit#L304-L321).
| |
| --- |
|
```
template <std::unsigned_integral T>
requires !std::same_as<T, bool> && !std::same_as<T, char> &&
!std::same_as<T, char8_t> && !std::same_as<T, char16_t> &&
!std::same_as<T, char32_t> && !std::same_as<T, wchar_t>
constexpr T bit_ceil(T x) noexcept
{
if (x <= 1u)
return T(1);
if constexpr (std::same_as<T, decltype(+x)>)
return T(1) << std::bit_width(T(x - 1));
else { // for types subject to integral promotion
constexpr int offset_for_ub =
std::numeric_limits<unsigned>::digits - std::numeric_limits<T>::digits;
return T(1u << (std::bit_width(T(x - 1)) + offset_for_ub) >> offset_for_ub);
}
}
```
|
### Example
```
#include <bit>
#include <bitset>
#include <iostream>
auto main() -> signed int // :()
{
using bin = std::bitset<8>;
for (unsigned x{0}; x != 10; ++x)
{
unsigned const z = std::bit_ceil(x); // `ceil2` before P1956R1
std::cout << "bit_ceil( " << bin(x) << " ) = " << bin(z) << '\n';
}
}
```
Output:
```
bit_ceil( 00000000 ) = 00000001
bit_ceil( 00000001 ) = 00000001
bit_ceil( 00000010 ) = 00000010
bit_ceil( 00000011 ) = 00000100
bit_ceil( 00000100 ) = 00000100
bit_ceil( 00000101 ) = 00001000
bit_ceil( 00000110 ) = 00001000
bit_ceil( 00000111 ) = 00001000
bit_ceil( 00001000 ) = 00001000
bit_ceil( 00001001 ) = 00010000
```
### See also
| | |
| --- | --- |
| [bit\_floor](bit_floor "cpp/numeric/bit floor")
(C++20) | finds the largest integral power of two not greater than the given value (function template) |
cpp std::valarray<T>::size std::valarray<T>::size
======================
| | | |
| --- | --- | --- |
|
```
std::size_t size() const;
```
| | |
Returns the number of elements in the valarray.
### Parameters
(none).
### Return value
Number of elements in the valarray.
### Example
```
#include <iostream>
#include <valarray>
int main()
{
std::valarray<double> a = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
std::cout << "Average: " << a.sum()/a.size() << '\n';
}
```
Output:
```
Average: 5.5
```
### See also
| | |
| --- | --- |
| [resize](resize "cpp/numeric/valarray/resize") | changes the size of valarray (public member function) |
cpp std::valarray<T>::operator+=,-=,*=,/=,%=,&=,|=,<<=,>>= std::valarray<T>::operator+=,-=,\*=,/=,%=,&=,|=,<<=,>>=
=======================================================
| | | |
| --- | --- | --- |
|
```
valarray<T>& operator+=( const valarray<T>& v );
valarray<T>& operator-=( const valarray<T>& v );
valarray<T>& operator*=( const valarray<T>& v );
valarray<T>& operator/=( const valarray<T>& v );
valarray<T>& operator%=( const valarray<T>& v );
valarray<T>& operator&=( const valarray<T>& v );
valarray<T>& operator|=( const valarray<T>& v );
valarray<T>& operator^=( const valarray<T>& v );
valarray<T>& operator<<=( const valarray<T>& v );
valarray<T>& operator>>=( const valarray<T>& v );
```
| (1) | |
|
```
valarray<T>& operator+=( const T& val );
valarray<T>& operator-=( const T& val );
valarray<T>& operator*=( const T& val );
valarray<T>& operator/=( const T& val );
valarray<T>& operator%=( const T& val );
valarray<T>& operator&=( const T& val );
valarray<T>& operator|=( const T& val );
valarray<T>& operator^=( const T& val );
valarray<T>& operator<<=( const T& val );
valarray<T>& operator>>=( const T& val );
```
| (2) | |
Applies compound assignment operators to each element in the numeric array.
1) Each element is assigned value obtained by applying the corresponding operator to the previous value of the element and corresponding element from `v`.
The behavior is undefined if `size() != v.size()`
The behavior is undefined if any of the values in `v` is computed during the assignment and depends on any of the values in `*this`, that is, the expression on the right side of the assignment refers to a variable in the left side of the assignment.
2) Each element is assigned value obtained by applying the corresponding operator to the previous value of the element and the value of `val`. ### Parameters
| | | |
| --- | --- | --- |
| v | - | another numeric array |
| val | - | a value |
### Return value
`*this`.
### Exceptions
May throw implementation-defined exceptions.
### Notes
Each of the operators can only be instantiated if the following requirements are met:
* The indicated operator can be applied to type `T`
* The result value can be unambiguously converted to `T`.
### Example
```
#include <iostream>
#include <string_view>
#include <type_traits>
#include <valarray>
void o(std::string_view rem, auto const& v, bool nl = false) {
if constexpr (std::is_scalar_v<std::decay_t<decltype(v)>>) {
std::cout << rem << " : " << v;
} else {
for (std::cout << rem << " : { "; auto const e : v)
std::cout << e << ' ';
std::cout << "}";
}
std::cout << (nl ? "\n" : "; ");
}
int main()
{
std::valarray<int> x, y;
o("x", x = {1, 2, 3, 4}), o("y", y = {4, 3, 2, 1}), o("x += y", x += y, 1);
o("x", x = {4, 3, 2, 1}), o("y", y = {3, 2, 1, 0}), o("x -= y", x -= y, 1);
o("x", x = {1, 2, 3, 4}), o("y", y = {5, 4, 3, 2}), o("x *= y", x *= y, 1);
o("x", x = {1, 3, 4, 7}), o("y", y = {1, 1, 3, 5}), o("x &= y", x &= y, 1);
o("x", x = {0, 1, 2, 4}), o("y", y = {4, 3, 2, 1}), o("x <<=y", x <<=y, 1);
o("x", x = {1, 2, 3, 4}), o("x += 5", x += 5, 1);
o("x", x = {1, 2, 3, 4}), o("x *= 2", x *= 2, 1);
o("x", x = {8, 6, 4, 2}), o("x /= 2", x /= 2, 1);
o("x", x = {8, 4, 2, 1}), o("x >>=1", x >>=1, 1);
}
```
Output:
```
x : { 1 2 3 4 }; y : { 4 3 2 1 }; x += y : { 5 5 5 5 }
x : { 4 3 2 1 }; y : { 3 2 1 0 }; x -= y : { 1 1 1 1 }
x : { 1 2 3 4 }; y : { 5 4 3 2 }; x *= y : { 5 8 9 8 }
x : { 1 3 4 7 }; y : { 1 1 3 5 }; x &= y : { 1 1 0 5 }
x : { 0 1 2 4 }; y : { 4 3 2 1 }; x <<=y : { 0 8 8 8 }
x : { 1 2 3 4 }; x += 5 : { 6 7 8 9 }
x : { 1 2 3 4 }; x *= 2 : { 2 4 6 8 }
x : { 8 6 4 2 }; x /= 2 : { 4 3 2 1 }
x : { 8 4 2 1 }; x >>=1 : { 4 2 1 0 }
```
### See also
| | |
| --- | --- |
| [operator+operator-operator~operator!](operator_arith "cpp/numeric/valarray/operator arith") | applies a unary arithmetic operator to each element of the valarray (public member function) |
| [operator+operator-operator\*operator/operator%operator&operator|operator^operator<<operator>>operator&&operator||](operator_arith3 "cpp/numeric/valarray/operator arith3") | applies binary operators to each element of two valarrays, or a valarray and a value (function template) |
| programming_docs |
cpp std::atan(std::valarray) std::atan(std::valarray)
========================
| Defined in header `[<valarray>](../../header/valarray "cpp/header/valarray")` | | |
| --- | --- | --- |
|
```
template< class T >
valarray<T> atan( const valarray<T>& va );
```
| | |
For each element in `va` computes arc tangent of the value of the element.
### Parameters
| | | |
| --- | --- | --- |
| va | - | value array to apply the operation to |
### Return value
Value array containing arc tangents of the values in `va`.
### Notes
Unqualified function (`atan`) is used to perform the computation. If such function is not available, `[std::atan](http://en.cppreference.com/w/cpp/numeric/math/atan)` is used due to [argument-dependent lookup](../../language/adl "cpp/language/adl").
The function can be implemented with the return type different from `[std::valarray](../valarray "cpp/numeric/valarray")`. In this case, the replacement type has the following properties:
* All `const` member functions of `[std::valarray](../valarray "cpp/numeric/valarray")` are provided.
* `[std::valarray](../valarray "cpp/numeric/valarray")`, `[std::slice\_array](slice_array "cpp/numeric/valarray/slice array")`, `[std::gslice\_array](gslice_array "cpp/numeric/valarray/gslice array")`, `[std::mask\_array](mask_array "cpp/numeric/valarray/mask array")` and `[std::indirect\_array](indirect_array "cpp/numeric/valarray/indirect array")` can be constructed from the replacement type.
* All functions accepting an argument of type `const [std::valarray](http://en.cppreference.com/w/cpp/numeric/valarray)&` except [`begin()`](begin2 "cpp/numeric/valarray/begin2") and [`end()`](end2 "cpp/numeric/valarray/end2") (since C++11) should also accept the replacement type.
* All functions accepting two arguments of type `const [std::valarray](http://en.cppreference.com/w/cpp/numeric/valarray)&` should accept every combination of `const [std::valarray](http://en.cppreference.com/w/cpp/numeric/valarray)&` and the replacement type.
* The return type does not add more than two levels of template nesting over the most deeply-nested argument type.
### Possible implementation
| |
| --- |
|
```
template< class T >
valarray<T> atan( const valarray<T>& va )
{
valarray<T> other = va;
for (T &i : other) {
i = atan(i);
}
return other; // proxy object may be returned
}
```
|
### Example
```
#include <algorithm>
#include <cmath>
#include <iostream>
#include <valarray>
auto show = [](char const* title, const std::valarray<float>& va) {
std::cout << title << " :";
std::for_each(std::begin(va), std::end(va),
[](const float x) { std::cout << " " << std::fixed << x; });
std::cout << '\n';
};
int main()
{
const std::valarray<float> x = {.1f, .3f, .6f, .9f};
const std::valarray<float> f = std::atan(x);
const std::valarray<float> g = std::tan(f);
show("x ", x);
show("f = atan(x)", f);
show("g = tan(f) ", g);
}
```
Output:
```
x : 0.100000 0.300000 0.600000 0.900000
f = atan(x) : 0.099669 0.291457 0.540420 0.732815
g = tan(f) : 0.100000 0.300000 0.600000 0.900000
```
### See also
| | |
| --- | --- |
| [asin(std::valarray)](asin "cpp/numeric/valarray/asin") | applies the function `[std::asin](../math/asin "cpp/numeric/math/asin")` to each element of valarray (function template) |
| [acos(std::valarray)](acos "cpp/numeric/valarray/acos") | applies the function `[std::acos](../math/acos "cpp/numeric/math/acos")` to each element of valarray (function template) |
| [atan2(std::valarray)](atan2 "cpp/numeric/valarray/atan2") | applies the function `[std::atan2](../math/atan2 "cpp/numeric/math/atan2")` to a valarray and a value (function template) |
| [tan(std::valarray)](tan "cpp/numeric/valarray/tan") | applies the function `[std::tan](../math/tan "cpp/numeric/math/tan")` to each element of valarray (function template) |
| [atanatanfatanl](../math/atan "cpp/numeric/math/atan")
(C++11)(C++11) | computes arc tangent (\({\small\arctan{x} }\)arctan(x)) (function) |
| [atan(std::complex)](../complex/atan "cpp/numeric/complex/atan")
(C++11) | computes arc tangent of a complex number (\({\small\arctan{z} }\)arctan(z)) (function template) |
cpp std::asin(std::valarray) std::asin(std::valarray)
========================
| Defined in header `[<valarray>](../../header/valarray "cpp/header/valarray")` | | |
| --- | --- | --- |
|
```
template< class T >
valarray<T> asin( const valarray<T>& va );
```
| | |
For each element in `va` computes arc sine of the value of the element.
### Parameters
| | | |
| --- | --- | --- |
| va | - | value array to apply the operation to |
### Return value
Value array containing arc sines of the values in `va`.
### Notes
Unqualified function (`asin`) is used to perform the computation. If such function is not available, `[std::asin](http://en.cppreference.com/w/cpp/numeric/math/asin)` is used due to [argument-dependent lookup](../../language/adl "cpp/language/adl").
The function can be implemented with the return type different from `[std::valarray](../valarray "cpp/numeric/valarray")`. In this case, the replacement type has the following properties:
* All `const` member functions of `[std::valarray](../valarray "cpp/numeric/valarray")` are provided.
* `[std::valarray](../valarray "cpp/numeric/valarray")`, `[std::slice\_array](slice_array "cpp/numeric/valarray/slice array")`, `[std::gslice\_array](gslice_array "cpp/numeric/valarray/gslice array")`, `[std::mask\_array](mask_array "cpp/numeric/valarray/mask array")` and `[std::indirect\_array](indirect_array "cpp/numeric/valarray/indirect array")` can be constructed from the replacement type.
* All functions accepting an argument of type `const [std::valarray](http://en.cppreference.com/w/cpp/numeric/valarray)&` except [`begin()`](begin2 "cpp/numeric/valarray/begin2") and [`end()`](end2 "cpp/numeric/valarray/end2") (since C++11) should also accept the replacement type.
* All functions accepting two arguments of type `const [std::valarray](http://en.cppreference.com/w/cpp/numeric/valarray)&` should accept every combination of `const [std::valarray](http://en.cppreference.com/w/cpp/numeric/valarray)&` and the replacement type.
* The return type does not add more than two levels of template nesting over the most deeply-nested argument type.
### Possible implementation
| |
| --- |
|
```
template< class T >
valarray<T> asin( const valarray<T>& va )
{
valarray<T> other = va;
for (T &i : other) {
i = asin(i);
}
return other; // proxy object may be returned
}
```
|
### Example
```
#include <cmath>
#include <numbers>
#include <iostream>
#include <valarray>
int main()
{
// take common y-values from unit circle
const double s22 = std::sqrt(2.0) / 2.0;
const double s32 = std::sqrt(3.0) / 2.0;
const std::valarray<double> v1 =
{-1.0, -s32, -s22, -0.5, 0.0, 0.5, s22, s32, 1.0};
// fill with results of radians to degrees conversion
const std::valarray<double> v2 =
std::asin(v1) * 180.0 / std::numbers::pi;
for(std::cout << std::showpos; double n : v2)
std::cout << n << "ยฐ ";
std::cout << '\n';
}
```
Output:
```
-90ยฐ -60ยฐ -45ยฐ -30ยฐ +0ยฐ +30ยฐ +45ยฐ +60ยฐ +90ยฐ
```
### See also
| | |
| --- | --- |
| [acos(std::valarray)](acos "cpp/numeric/valarray/acos") | applies the function `[std::acos](../math/acos "cpp/numeric/math/acos")` to each element of valarray (function template) |
| [atan(std::valarray)](atan "cpp/numeric/valarray/atan") | applies the function `[std::atan](../math/atan "cpp/numeric/math/atan")` to each element of valarray (function template) |
| [atan2(std::valarray)](atan2 "cpp/numeric/valarray/atan2") | applies the function `[std::atan2](../math/atan2 "cpp/numeric/math/atan2")` to a valarray and a value (function template) |
| [sin(std::valarray)](sin "cpp/numeric/valarray/sin") | applies the function `[std::sin](../math/sin "cpp/numeric/math/sin")` to each element of valarray (function template) |
| [asinasinfasinl](../math/asin "cpp/numeric/math/asin")
(C++11)(C++11) | computes arc sine (\({\small\arcsin{x} }\)arcsin(x)) (function) |
| [asin(std::complex)](../complex/asin "cpp/numeric/complex/asin")
(C++11) | computes arc sine of a complex number (\({\small\arcsin{z} }\)arcsin(z)) (function template) |
cpp deduction guides for std::valarray
deduction guides for `std::valarray`
====================================
| Defined in header `[<valarray>](../../header/valarray "cpp/header/valarray")` | | |
| --- | --- | --- |
|
```
template<typename T, std::size_t cnt>
valarray(const T(&)[cnt], std::size_t) -> valarray<T>;
```
| | (since C++17) |
This [deduction guide](../../language/class_template_argument_deduction "cpp/language/class template argument deduction") is provided for `[std::valarray](../valarray "cpp/numeric/valarray")` to allow deduction from array and size (note that deduction from pointer and size is covered by the implicit guides).
### Example
```
#include <valarray>
#include <iostream>
int main()
{
int a[] = {1, 2, 3, 4};
std::valarray va(a, 3); // uses explicit deduction guide
for (int x : va)
std::cout << x << ' ';
}
```
Output:
```
1 2 3
```
cpp std::cosh(std::valarray) std::cosh(std::valarray)
========================
| Defined in header `[<valarray>](../../header/valarray "cpp/header/valarray")` | | |
| --- | --- | --- |
|
```
template< class T >
valarray<T> cosh( const valarray<T>& va );
```
| | |
For each element in `va` computes hyperbolic cosine of the value of the element.
### Parameters
| | | |
| --- | --- | --- |
| va | - | value array to apply the operation to |
### Return value
Value array containing hyperbolic cosine of the values in `va`.
### Notes
Unqualified function (`cosh`) is used to perform the computation. If such function is not available, `[std::cosh](http://en.cppreference.com/w/cpp/numeric/math/cosh)` is used due to [argument-dependent lookup](../../language/adl "cpp/language/adl").
The function can be implemented with the return type different from `[std::valarray](../valarray "cpp/numeric/valarray")`. In this case, the replacement type has the following properties:
* All `const` member functions of `[std::valarray](../valarray "cpp/numeric/valarray")` are provided.
* `[std::valarray](../valarray "cpp/numeric/valarray")`, `[std::slice\_array](slice_array "cpp/numeric/valarray/slice array")`, `[std::gslice\_array](gslice_array "cpp/numeric/valarray/gslice array")`, `[std::mask\_array](mask_array "cpp/numeric/valarray/mask array")` and `[std::indirect\_array](indirect_array "cpp/numeric/valarray/indirect array")` can be constructed from the replacement type.
* All functions accepting an argument of type `const [std::valarray](http://en.cppreference.com/w/cpp/numeric/valarray)&` except [`begin()`](begin2 "cpp/numeric/valarray/begin2") and [`end()`](end2 "cpp/numeric/valarray/end2") (since C++11) should also accept the replacement type.
* All functions accepting two arguments of type `const [std::valarray](http://en.cppreference.com/w/cpp/numeric/valarray)&` should accept every combination of `const [std::valarray](http://en.cppreference.com/w/cpp/numeric/valarray)&` and the replacement type.
* The return type does not add more than two levels of template nesting over the most deeply-nested argument type.
### Possible implementation
| |
| --- |
|
```
template< class T >
valarray<T> cosh( const valarray<T>& va )
{
valarray<T> other = va;
for (T &i : other) {
i = cosh(i);
}
return other; // proxy object may be returned
}
```
|
### Example
```
#include <cmath>
#include <iomanip>
#include <iostream>
#include <valarray>
void show(const char* title, const std::valarray<float>& data)
{
const int w { 9 };
std::cout << std::setw(w) << title << " | ";
for (float x : data)
std::cout << std::setw(w) << x << " | ";
std::cout << '\n';
}
int main()
{
const std::valarray<float> x { .1, .2, .3, .4 };
const auto sinh = std::sinh(x);
const auto cosh = std::cosh(x);
const auto z = (cosh * cosh) - (sinh * sinh);
show("x" , x );
show("sinh(x)", sinh);
show("cosh(x)", cosh);
show("z" , z );
}
```
Output:
```
x | 0.1 | 0.2 | 0.3 | 0.4 |
sinh(x) | 0.100167 | 0.201336 | 0.30452 | 0.410752 |
cosh(x) | 1.005 | 1.02007 | 1.04534 | 1.08107 |
z | 1 | 1 | 1 | 1 |
```
### See also
| | |
| --- | --- |
| [sinh(std::valarray)](sinh "cpp/numeric/valarray/sinh") | applies the function `[std::sinh](../math/sinh "cpp/numeric/math/sinh")` to each element of valarray (function template) |
| [tanh(std::valarray)](tanh "cpp/numeric/valarray/tanh") | applies the function `[std::tanh](../math/tanh "cpp/numeric/math/tanh")` to each element of valarray (function template) |
| [coshcoshfcoshl](../math/cosh "cpp/numeric/math/cosh")
(C++11)(C++11) | computes hyperbolic cosine (\({\small\cosh{x} }\)cosh(x)) (function) |
| [cosh(std::complex)](../complex/cosh "cpp/numeric/complex/cosh") | computes hyperbolic cosine of a complex number (\({\small\cosh{z} }\)cosh(z)) (function template) |
cpp std::indirect_array std::indirect\_array
====================
| Defined in header `[<valarray>](../../header/valarray "cpp/header/valarray")` | | |
| --- | --- | --- |
|
```
template< class T > class indirect_array;
```
| | |
`std::indirect_array` is a helper template used by the [valarray subscript operator](operator_at "cpp/numeric/valarray/operator at") with `[std::valarray](http://en.cppreference.com/w/cpp/numeric/valarray)<[std::size\_t](http://en.cppreference.com/w/cpp/types/size_t)>` argument. It has reference semantics to a subset of the array whose indices specified by the `[std::valarray](http://en.cppreference.com/w/cpp/numeric/valarray)<[std::size\_t](http://en.cppreference.com/w/cpp/types/size_t)>` object.
### Member types
| Type | Definition |
| --- | --- |
| `value_type` | `T` |
### Member functions
| | |
| --- | --- |
| [(constructor)](indirect_array/indirect_array "cpp/numeric/valarray/indirect array/indirect array") | constructs a `indirect_array` (public member function) |
| [(destructor)](indirect_array/~indirect_array "cpp/numeric/valarray/indirect array/~indirect array") | destroys a `indirect_array` (public member function) |
| [operator=](indirect_array/operator= "cpp/numeric/valarray/indirect array/operator=") | assigns contents (public member function) |
| [operator+=operator-=operator\*=operator/=operator%=operator&=operator|=operator^=operator<<=operator>>=](indirect_array/operator_arith "cpp/numeric/valarray/indirect array/operator arith") | performs arithmetic operation on the array referred by indirect array. (public member function) |
### Example
```
#include <iostream>
#include <valarray>
int main()
{
std::valarray<int> data = {0,1,2,3,4,5,6,7,8,9};
std::valarray<std::size_t> idx = {0,2,4,6,8};
std::cout << "Original valarray: ";
for(int n: data) std::cout << n << ' ';
std::cout << '\n';
data[idx] += data[idx]; // double the values at indexes 'idx'
// the type of data[idx] is std::indirect_array<int>
std::cout << "After indirect modification: ";
for(int n: data) std::cout << n << ' ';
std::cout << '\n';
}
```
Output:
```
Original valarray: 0 1 2 3 4 5 6 7 8 9
After indirect modification: 0 1 4 3 8 5 12 7 16 9
```
cpp std::valarray<T>::~valarray std::valarray<T>::~valarray
===========================
| | | |
| --- | --- | --- |
|
```
~valarray()
```
| | |
Destructs the numeric array. The destructors of the elements are called and the used storage is deallocated.
### Complexity
Linear in the size of the numeric array.
cpp std::cos(std::valarray) std::cos(std::valarray)
=======================
| Defined in header `[<valarray>](../../header/valarray "cpp/header/valarray")` | | |
| --- | --- | --- |
|
```
template< class T >
valarray<T> cos( const valarray<T>& va );
```
| | |
For each element in `va` computes cosine of the value of the element.
### Parameters
| | | |
| --- | --- | --- |
| va | - | value array to apply the operation to |
### Return value
Value array containing cosines of the values in `va`.
### Notes
Unqualified function (`cos`) is used to perform the computation. If such function is not available, `[std::cos](http://en.cppreference.com/w/cpp/numeric/math/cos)` is used due to [argument-dependent lookup](../../language/adl "cpp/language/adl").
The function can be implemented with the return type different from `[std::valarray](../valarray "cpp/numeric/valarray")`. In this case, the replacement type has the following properties:
* All `const` member functions of `[std::valarray](../valarray "cpp/numeric/valarray")` are provided.
* `[std::valarray](../valarray "cpp/numeric/valarray")`, `[std::slice\_array](slice_array "cpp/numeric/valarray/slice array")`, `[std::gslice\_array](gslice_array "cpp/numeric/valarray/gslice array")`, `[std::mask\_array](mask_array "cpp/numeric/valarray/mask array")` and `[std::indirect\_array](indirect_array "cpp/numeric/valarray/indirect array")` can be constructed from the replacement type.
* All functions accepting an argument of type `const [std::valarray](http://en.cppreference.com/w/cpp/numeric/valarray)&` except [`begin()`](begin2 "cpp/numeric/valarray/begin2") and [`end()`](end2 "cpp/numeric/valarray/end2") (since C++11) should also accept the replacement type.
* All functions accepting two arguments of type `const [std::valarray](http://en.cppreference.com/w/cpp/numeric/valarray)&` should accept every combination of `const [std::valarray](http://en.cppreference.com/w/cpp/numeric/valarray)&` and the replacement type.
* The return type does not add more than two levels of template nesting over the most deeply-nested argument type.
### Possible implementation
| |
| --- |
|
```
template< class T >
valarray<T> cos( const valarray<T>& va )
{
valarray<T> other = va;
for (T &i : other) {
i = cos(i);
}
return other; // proxy object may be returned
}
```
|
### Example
```
#include <cmath>
#include <iomanip>
#include <iostream>
#include <valarray>
void show(const char* title, const std::valarray<float>& data)
{
const int w { 9 };
std::cout << std::setw(w) << title << " | ";
for (float x : data)
std::cout << std::setw(w) << x << " | ";
std::cout << '\n';
}
int main()
{
const std::valarray<float> x { .1, .2, .3, .4 };
const auto sin = std::sin(x);
const auto cos = std::cos(x);
const auto z = (sin * sin) + (cos * cos);
show("x" , x );
show("sin(x)", sin);
show("cos(x)", cos);
show("z" , z );
}
```
Output:
```
x | 0.1 | 0.2 | 0.3 | 0.4 |
sin(x) | 0.0998334 | 0.198669 | 0.29552 | 0.389418 |
cos(x) | 0.995004 | 0.980067 | 0.955337 | 0.921061 |
z | 1 | 1 | 1 | 1 |
```
### See also
| | |
| --- | --- |
| [sin(std::valarray)](sin "cpp/numeric/valarray/sin") | applies the function `[std::sin](../math/sin "cpp/numeric/math/sin")` to each element of valarray (function template) |
| [tan(std::valarray)](tan "cpp/numeric/valarray/tan") | applies the function `[std::tan](../math/tan "cpp/numeric/math/tan")` to each element of valarray (function template) |
| [acos(std::valarray)](acos "cpp/numeric/valarray/acos") | applies the function `[std::acos](../math/acos "cpp/numeric/math/acos")` to each element of valarray (function template) |
| [coscosfcosl](../math/cos "cpp/numeric/math/cos")
(C++11)(C++11) | computes cosine (\({\small\cos{x} }\)cos(x)) (function) |
| [cos(std::complex)](../complex/cos "cpp/numeric/complex/cos") | computes cosine of a complex number (\({\small\cos{z} }\)cos(z)) (function template) |
| programming_docs |
cpp std::slice_array std::slice\_array
=================
| Defined in header `[<valarray>](../../header/valarray "cpp/header/valarray")` | | |
| --- | --- | --- |
|
```
template< class T > class slice_array;
```
| | |
`std::slice_array` is a helper template used by the [valarray subscript operator](operator_at "cpp/numeric/valarray/operator at") with `[std::slice](http://en.cppreference.com/w/cpp/numeric/valarray/slice)` argument. It has reference semantics to a subset of the array specified by the `[std::slice](http://en.cppreference.com/w/cpp/numeric/valarray/slice)` object.
### Member types
| Type | Definition |
| --- | --- |
| `value_type` | `T` |
### Member functions
| | |
| --- | --- |
| [(constructor)](slice_array/slice_array "cpp/numeric/valarray/slice array/slice array") | constructs a `slice_array` (public member function) |
| [(destructor)](slice_array/~slice_array "cpp/numeric/valarray/slice array/~slice array") | destroys a `slice_array` (public member function) |
| [operator=](slice_array/operator= "cpp/numeric/valarray/slice array/operator=") | assigns contents (public member function) |
| [operator+=operator-=operator\*=operator/=operator%=operator&=operator|=operator^=operator<<=operator>>=](slice_array/operator_arith "cpp/numeric/valarray/slice array/operator arith") | performs arithmetic operation on the array referred by slice. (public member function) |
### Example
```
#include <iostream>
#include <valarray>
class Matrix {
int dim;
std::valarray<int> data;
public:
explicit Matrix(int dim, int init = 0)
: dim{dim}, data(init, dim*dim) { }
void clear(int value = 0) { data = value; }
void identity() { clear(); diagonal() = 1; }
int& operator()(int x, int y) { return data[dim * y + x]; }
std::slice_array<int> diagonal() {
return data[std::slice(0, dim, dim+1)];
}
std::slice_array<int> secondary_diagonal() {
return data[std::slice(dim-1, dim, dim-1)];
}
std::slice_array<int> row(std::size_t row) {
return data[std::slice(dim*row, dim, 1)];
}
std::slice_array<int> column(std::size_t col) {
return data[std::slice(col, dim, dim)];
}
template<unsigned, unsigned> friend class MatrixStack;
};
template <unsigned dim = 3, unsigned max = 8> class MatrixStack {
std::valarray<int> stack;
unsigned count = 0;
public:
MatrixStack() : stack(dim*dim*max) {}
void print_all() const {
std::valarray<int> row(dim*count);
for (unsigned r = 0; r != dim; ++r) { // screen row
row = stack[std::gslice(r*dim, {count, dim}, {dim*dim, 1})];
for (unsigned i = 0; i != row.size(); ++i)
std::cout << row[i] << ((i+1) % dim ? " " : " โ ");
std::cout << '\n';
}
}
void push_back(Matrix const& m) {
if (count < max) {
stack[std::slice(count * dim * dim, dim * dim, 1)]
= m.data[std::slice(0, dim * dim, 1)];
++count;
}
}
};
int main()
{
constexpr int dim = 3;
Matrix m{dim};
MatrixStack<dim,12> stack;
m.identity();
stack.push_back(m);
m.clear(1);
m.secondary_diagonal() = 3;
stack.push_back(m);
for (int i = 0; i != dim; ++i) {
m.clear();
m.row(i) = i + 1;
stack.push_back(m);
}
for (int i = 0; i != dim; ++i) {
m.clear();
m.column(i) = i + 1;
stack.push_back(m);
}
m.clear();
m.row(1) = std::valarray<int>{4, 5, 6};
stack.push_back(m);
m.clear();
m.column(1) = std::valarray<int>{7, 8, 9};
stack.push_back(m);
stack.print_all();
}
```
Output:
```
1 0 0 โ 1 1 3 โ 1 1 1 โ 0 0 0 โ 0 0 0 โ 1 0 0 โ 0 2 0 โ 0 0 3 โ 0 0 0 โ 0 7 0 โ
0 1 0 โ 1 3 1 โ 0 0 0 โ 2 2 2 โ 0 0 0 โ 1 0 0 โ 0 2 0 โ 0 0 3 โ 4 5 6 โ 0 8 0 โ
0 0 1 โ 3 1 1 โ 0 0 0 โ 0 0 0 โ 3 3 3 โ 1 0 0 โ 0 2 0 โ 0 0 3 โ 0 0 0 โ 0 9 0 โ
```
### See also
| | |
| --- | --- |
| [gslice\_array](gslice_array "cpp/numeric/valarray/gslice array") | proxy to a subset of a valarray after applying a gslice (class template) |
cpp std::gslice std::gslice
===========
| Defined in header `[<valarray>](../../header/valarray "cpp/header/valarray")` | | |
| --- | --- | --- |
|
```
class gslice;
```
| | |
`std::gslice` is the selector class that identifies a subset of `[std::valarray](../valarray "cpp/numeric/valarray")` indices defined by a multi-level set of strides and sizes. Objects of type `std::gslice` can be used as indices with valarray's `operator[]` to select, for example, columns of a multidimensional array represented as a `valarray`.
Given the starting value s, a list of strides i
j and a list of sizes d
j, a `std::gslice` constructed from these values selects the set of indices k
j=s+ฮฃ
j(i
jd
j).
For example, a gslice with starting index `3`, strides `{19,4,1`} and lengths `{2,4,3`} generates the following set of `24=2*4*3` indices:
`3 + 0*19 + 0*4 + 0*1 = 3, 3 + 0*19 + 0*4 + 1*1 = 4, 3 + 0*19 + 0*4 + 2*1 = 5, 3 + 0*19 + 1*4 + 0*1 = 7, 3 + 0*19 + 1*4 + 1*1 = 8, 3 + 0*19 + 1*4 + 2*1 = 9, 3 + 0*19 + 2*4 + 0*1 = 11, ... 3 + 1*19 + 3*4 + 1*1 = 35, 3 + 1*19 + 3*4 + 2*1 = 36`.
It is possible to construct `std::gslice` objects that select some indices more than once: if the above example used the strides `{1,1,1}` , the indices would have been `{3, 4, 5, 4, 5, 6, ...}` . Such gslices may only be used as arguments to the const version of `std::valarray::operator[]`, otherwise the behavior is undefined.
### Member functions
| | |
| --- | --- |
| **(constructor)** | constructs a generic slice (public member function) |
| **startsizestride** | returns the parameters of the slice (public member function) |
std::gslice::gslice
--------------------
| | | |
| --- | --- | --- |
|
```
gslice()
```
| (1) | |
|
```
gslice( std::size_t start, const std::valarray<std::size_t>& sizes,
const std::valarray<std::size_t>& strides );
```
| (2) | |
|
```
gslice( const gslice& other );
```
| (3) | |
Constructs a new generic slice.
1) Default constructor. Equivalent to `gslice(0, [std::valarray](http://en.cppreference.com/w/cpp/numeric/valarray)<[std::size\_t](http://en.cppreference.com/w/cpp/types/size_t)>(), [std::valarray](http://en.cppreference.com/w/cpp/numeric/valarray)<[std::size\_t](http://en.cppreference.com/w/cpp/types/size_t)>())`. This constructor exists only to allow construction of arrays of slices.
2) Constructs a new slice with parameters `start`, `sizes`, `strides`.
3) Constructs a copy of `other`. ### Parameters
| | | |
| --- | --- | --- |
| start | - | the position of the first element |
| sizes | - | an array that defines the number of elements in each dimension |
| strides | - | an array that defines the number of positions between successive elements in each dimension |
| other | - | another slice to copy |
std::slice::start, size, stride
--------------------------------
| | | |
| --- | --- | --- |
|
```
std::size_t start() const;
```
| (1) | |
|
```
std::valarray<std::size_t> size() const;
```
| (2) | |
|
```
std::valarray<std::size_t> stride() const;
```
| (3) | |
Returns the parameters passed to the slice on construction - start, sizes and strides respectively.
### Parameters
(none).
### Return value
The parameters of the slice -- start, sizes and strides respectively.
### Complexity
Constant.
### Example
demonstrates the use of gslices to address columns of a 3D array.
```
#include <iostream>
#include <valarray>
void test_print(std::valarray<int>& v, int planes, int rows, int cols)
{
for(int r=0; r<rows; ++r) {
for(int z=0; z<planes; ++z) {
for(int c=0; c<cols; ++c)
std::cout << v[z*rows*cols + r*cols + c] << ' ';
std::cout << " ";
}
std::cout << '\n';
}
}
int main()
{
std::valarray<int> v = // 3d array: 2 x 4 x 3 elements
{ 111,112,113 , 121,122,123 , 131,132,133 , 141,142,143,
211,212,213 , 221,222,223 , 231,232,233 , 241,242,243};
// int ar3d[2][4][3]
std::cout << "Initial 2x4x3 array:\n";
test_print(v, 2, 4, 3);
// update every value in the first columns of both planes
v[std::gslice(0, {2, 4}, {4*3, 3})] = 1; // two level one strides of 12 elements
// then four level two strides of 3 elements
// subtract the third column from the second column in the 1st plane
v[std::gslice(1, {1, 4}, {4*3, 3})] -= v[std::gslice(2, {1, 4}, {4*3, 3})];
std::cout << "\n" "After column operations:\n";
test_print(v, 2, 4, 3);
}
```
Output:
```
Initial 2x4x3 array:
111 112 113 211 212 213
121 122 123 221 222 223
131 132 133 231 232 233
141 142 143 241 242 243
After column operations:
1 -1 113 1 212 213
1 -1 123 1 222 223
1 -1 133 1 232 233
1 -1 143 1 242 243
```
### See also
| | |
| --- | --- |
| [operator[]](operator_at "cpp/numeric/valarray/operator at") | get/set valarray element, slice, or mask (public member function) |
| [slice](slice "cpp/numeric/valarray/slice") | BLAS-like slice of a valarray: starting index, length, stride (class) |
| [gslice\_array](gslice_array "cpp/numeric/valarray/gslice array") | proxy to a subset of a valarray after applying a gslice (class template) |
cpp std::valarray<T>::operator[] std::valarray<T>::operator[]
============================
| | | |
| --- | --- | --- |
| | (1) | |
|
```
T operator[]( std::size_t pos ) const;
```
| (until C++11) |
|
```
const T& operator[]( std::size_t pos ) const;
```
| (since C++11) |
|
```
T& operator[]( std::size_t pos );
```
| (2) | |
|
```
std::valarray<T> operator[]( std::slice slicearr ) const;
```
| (3) | |
|
```
std::slice_array<T> operator[]( std::slice slicearr );
```
| (4) | |
|
```
std::valarray<T> operator[]( const std::gslice& gslicearr ) const;
```
| (5) | |
|
```
std::gslice_array<T> operator[]( const std::gslice& gslicearr );
```
| (6) | |
|
```
std::valarray<T> operator[]( const valarray<bool>& boolarr ) const;
```
| (7) | |
|
```
std::mask_array<T> operator[]( const valarray<bool>& boolarr );
```
| (8) | |
|
```
std::valarray<T> operator[]( const valarray<std::size_t>& indarr ) const;
```
| (9) | |
|
```
std::indirect_array<T> operator[]( const valarray<std::size_t>& indarr );
```
| (10) | |
Retrieve single elements or portions of the array.
The `const` overloads that return element sequences create a new `[std::valarray](../valarray "cpp/numeric/valarray")` object. The non-`const` overloads return classes holding references to the array elements.
### Parameters
| | | |
| --- | --- | --- |
| pos | - | position of the element to return |
| slicearr | - | [slice](slice "cpp/numeric/valarray/slice") of the elements to return |
| gslicearr | - | [gslice](gslice "cpp/numeric/valarray/gslice") of the elements to return |
| boolarr | - | mask of the elements to return |
| indarr | - | indices of the elements to return |
### Return value
1,2) A reference to the corresponding element
3,5,7,9) A `[std::valarray](../valarray "cpp/numeric/valarray")` object containing copies of the selected items
4,6,8,10) The corresponding data structure containing references to the selected items ### Exceptions
May throw implementation-defined exceptions.
### Precondition
The selected elements must exist.
### Notes
* For proper values of `i` and `j`, the following properties are true:
1) `(a[i] = q, a[i]) == q` For a non-const `a`.
2) `&a[i+j] == &a[i] + j` This means that valarray elements are adjacent in memory.
3) `&a[i] != &b[j]`
This holds for every objects `a` and `b` that are not aliases of one another.
This means that there are no aliases in the elements and this property can be used to perform some kinds of optimization.
* References become invalid on [resize](resize "cpp/numeric/valarray/resize") or when the array is destructed.
For overloads (3,5,7,9), The function can be implemented with the return type different from `[std::valarray](../valarray "cpp/numeric/valarray")`. In this case, the replacement type has the following properties:
* All `const` member functions of `[std::valarray](../valarray "cpp/numeric/valarray")` are provided.
* `[std::valarray](../valarray "cpp/numeric/valarray")`, `[std::slice\_array](slice_array "cpp/numeric/valarray/slice array")`, `[std::gslice\_array](gslice_array "cpp/numeric/valarray/gslice array")`, `[std::mask\_array](mask_array "cpp/numeric/valarray/mask array")` and `[std::indirect\_array](indirect_array "cpp/numeric/valarray/indirect array")` can be constructed from the replacement type.
* All functions accepting an argument of type `const [std::valarray](http://en.cppreference.com/w/cpp/numeric/valarray)&` except [`begin()`](begin2 "cpp/numeric/valarray/begin2") and [`end()`](end2 "cpp/numeric/valarray/end2") (since C++11) should also accept the replacement type.
* All functions accepting two arguments of type `const [std::valarray](http://en.cppreference.com/w/cpp/numeric/valarray)&` should accept every combination of `const [std::valarray](http://en.cppreference.com/w/cpp/numeric/valarray)&` and the replacement type.
* The return type does not add more than two levels of template nesting over the most deeply-nested argument type.
Slice/mask/indirect index accesses do not chain: `v[v==n][[std::slice](http://en.cppreference.com/w/cpp/numeric/valarray/slice)(0,5,2)] = x;` is an error because `[std::mask\_array](mask_array "cpp/numeric/valarray/mask array")` (the type of `v[v==n]`) does not have `operator[]`.
### Example
```
#include <iostream>
#include <valarray>
int main()
{
std::valarray<int> data = {0,1,2,3,4,5,6,7,8,9};
std::cout << "Initial valarray: ";
for(int n: data) std::cout << n << ' ';
std::cout << '\n';
data[data > 5] = -1; // valarray<bool> overload of operator[]
// the type of data>5 is std::valarray<bool>
// the type of data[data>5] is std::mask_array<int>
std::cout << "After v[v>5]=-1: ";
for(std::size_t n = 0; n < data.size(); ++n)
std::cout << data[n] << ' '; // regular operator[]
std::cout << '\n';
}
```
Output:
```
Initial valarray: 0 1 2 3 4 5 6 7 8 9
After v[v>5]=-1: 0 1 2 3 4 5 -1 -1 -1 -1
```
cpp std::valarray<T>::apply std::valarray<T>::apply
=======================
| | | |
| --- | --- | --- |
|
```
valarray<T> apply( T func(T) ) const;
```
| | |
|
```
valarray<T> apply( T func(const T&) ) const;
```
| | |
Returns a new valarray of the same size with values which are acquired by applying function `func` to the previous values of the elements.
### Parameters
| | | |
| --- | --- | --- |
| func | - | function to apply to the values |
### Return value
The resulting valarray with values acquired by applying function `func`.
### Notes
The function can be implemented with the return type different from `[std::valarray](../valarray "cpp/numeric/valarray")`. In this case, the replacement type has the following properties:
* All `const` member functions of `[std::valarray](../valarray "cpp/numeric/valarray")` are provided.
* `[std::valarray](../valarray "cpp/numeric/valarray")`, `[std::slice\_array](slice_array "cpp/numeric/valarray/slice array")`, `[std::gslice\_array](gslice_array "cpp/numeric/valarray/gslice array")`, `[std::mask\_array](mask_array "cpp/numeric/valarray/mask array")` and `[std::indirect\_array](indirect_array "cpp/numeric/valarray/indirect array")` can be constructed from the replacement type.
* All functions accepting an argument of type `const [std::valarray](http://en.cppreference.com/w/cpp/numeric/valarray)&` except [`begin()`](begin2 "cpp/numeric/valarray/begin2") and [`end()`](end2 "cpp/numeric/valarray/end2") (since C++11) should also accept the replacement type.
* All functions accepting two arguments of type `const [std::valarray](http://en.cppreference.com/w/cpp/numeric/valarray)&` should accept every combination of `const [std::valarray](http://en.cppreference.com/w/cpp/numeric/valarray)&` and the replacement type.
* The return type does not add more than two levels of template nesting over the most deeply-nested argument type.
### Possible implementation
Following straightforward implementations can be replaced by expression templates for a higher efficiency.
| |
| --- |
|
```
template<class T>
valarray<T> valarray<T>::apply( T func(T) ) const
{
valarray<T> other = *this;
for (T &i : other) {
i = func(i);
}
return other;
}
template<class T>
valarray<T> valarray<T>::apply( T func(const T&) ) const
{
valarray<T> other = *this;
for (T &i : other) {
i = func(i);
}
return other;
}
```
|
### Example
calculates and prints the first 10 factorials.
```
#include <iostream>
#include <valarray>
#include <cmath>
int main()
{
std::valarray<int> v = {1,2,3,4,5,6,7,8,9,10};
v = v.apply([](int n)->int {
return std::round(std::tgamma(n+1));
});
for(auto n : v) {
std::cout << n << ' ';
}
std::cout << '\n';
}
```
Output:
```
1 2 6 24 120 720 5040 40320 362880 3628800
```
### See also
| | |
| --- | --- |
| [for\_each](../../algorithm/for_each "cpp/algorithm/for each") | applies a function to a range of elements (function template) |
| [ranges::for\_each](../../algorithm/ranges/for_each "cpp/algorithm/ranges/for each")
(C++20) | applies a function to a range of elements (niebloid) |
cpp std::sqrt(std::valarray) std::sqrt(std::valarray)
========================
| Defined in header `[<valarray>](../../header/valarray "cpp/header/valarray")` | | |
| --- | --- | --- |
|
```
template< class T >
valarray<T> sqrt( const valarray<T>& va );
```
| | |
For each element in `va` computes the square root of the value of the element.
### Parameters
| | | |
| --- | --- | --- |
| va | - | value array to apply the operation to |
### Return value
Value array containing square roots of the values in `va`.
### Notes
Unqualified function (`sqrt`) is used to perform the computation. If such function is not available, `[std::sqrt](http://en.cppreference.com/w/cpp/numeric/math/sqrt)` is used due to [argument-dependent lookup](../../language/adl "cpp/language/adl").
The function can be implemented with the return type different from `[std::valarray](../valarray "cpp/numeric/valarray")`. In this case, the replacement type has the following properties:
* All `const` member functions of `[std::valarray](../valarray "cpp/numeric/valarray")` are provided.
* `[std::valarray](../valarray "cpp/numeric/valarray")`, `[std::slice\_array](slice_array "cpp/numeric/valarray/slice array")`, `[std::gslice\_array](gslice_array "cpp/numeric/valarray/gslice array")`, `[std::mask\_array](mask_array "cpp/numeric/valarray/mask array")` and `[std::indirect\_array](indirect_array "cpp/numeric/valarray/indirect array")` can be constructed from the replacement type.
* All functions accepting an argument of type `const [std::valarray](http://en.cppreference.com/w/cpp/numeric/valarray)&` except [`begin()`](begin2 "cpp/numeric/valarray/begin2") and [`end()`](end2 "cpp/numeric/valarray/end2") (since C++11) should also accept the replacement type.
* All functions accepting two arguments of type `const [std::valarray](http://en.cppreference.com/w/cpp/numeric/valarray)&` should accept every combination of `const [std::valarray](http://en.cppreference.com/w/cpp/numeric/valarray)&` and the replacement type.
* The return type does not add more than two levels of template nesting over the most deeply-nested argument type.
### Possible implementation
| |
| --- |
|
```
template< class T >
valarray<T> sqrt( const valarray<T>& va )
{
valarray<T> other = va;
for (T &i : other) {
i = sqrt(i);
}
return other; // proxy object may be returned
}
```
|
### Example
Finds real roots of multiple quadratic equations.
```
#include <cstddef>
#include <valarray>
#include <iostream>
int main()
{
std::valarray<double> a(1, 8);
std::valarray<double> b{1, 2, 3, 4, 5, 6, 7, 8};
std::valarray<double> c = -b;
// literals must also be of type T until LWG3074 (double in this case)
std::valarray<double> d = std::sqrt(b * b - 4.0 * a * c);
std::valarray<double> x1 = (-b - d) / (2.0 * a);
std::valarray<double> x2 = (-b + d) / (2.0 * a);
std::cout << "quadratic equation: root 1: root 2:\n";
for (std::size_t i = 0; i < a.size(); ++i) {
std::cout << a[i] << "\u00B7x\u00B2 + " << b[i] << "\u00B7x + "
<< c[i] << " = 0 " << std::fixed << x1[i] << " "
<< x2[i] << std::defaultfloat << '\n';
}
}
```
Output:
```
quadratic equation: root 1: root 2:
1ยทxยฒ + 1ยทx + -1 = 0 -1.618034 0.618034
1ยทxยฒ + 2ยทx + -2 = 0 -2.732051 0.732051
1ยทxยฒ + 3ยทx + -3 = 0 -3.791288 0.791288
1ยทxยฒ + 4ยทx + -4 = 0 -4.828427 0.828427
1ยทxยฒ + 5ยทx + -5 = 0 -5.854102 0.854102
1ยทxยฒ + 6ยทx + -6 = 0 -6.872983 0.872983
1ยทxยฒ + 7ยทx + -7 = 0 -7.887482 0.887482
1ยทxยฒ + 8ยทx + -8 = 0 -8.898979 0.898979
```
### See also
| | |
| --- | --- |
| [pow(std::valarray)](pow "cpp/numeric/valarray/pow") | applies the function `[std::pow](../math/pow "cpp/numeric/math/pow")` to two valarrays or a valarray and a value (function template) |
| [sqrtsqrtfsqrtl](../math/sqrt "cpp/numeric/math/sqrt")
(C++11)(C++11) | computes square root (\(\small{\sqrt{x} }\)โx) (function) |
| [sqrt(std::complex)](../complex/sqrt "cpp/numeric/complex/sqrt") | complex square root in the range of the right half-plane (function template) |
| programming_docs |
cpp std::valarray<T>::swap std::valarray<T>::swap
======================
| | | |
| --- | --- | --- |
|
```
void swap( valarray& other );
```
| | (until C++11) |
|
```
void swap( valarray& other ) noexcept;
```
| | (since C++11) |
Swaps the contents with those of `other`.
### Parameters
| | | |
| --- | --- | --- |
| other | - | another valarray to swap the contents with |
### Return value
(none).
cpp std::mask_array std::mask\_array
================
| Defined in header `[<valarray>](../../header/valarray "cpp/header/valarray")` | | |
| --- | --- | --- |
|
```
template< class T > class mask_array;
```
| | |
`std::mask_array` is a helper template used by the [valarray subscript operator](operator_at "cpp/numeric/valarray/operator at") with `[std::valarray](http://en.cppreference.com/w/cpp/numeric/valarray)<bool>` argument. It has reference semantics and provides access to the subset of the valarray consisting of the elements whose indices correspond to `true` values in the `[std::valarray](http://en.cppreference.com/w/cpp/numeric/valarray)<bool>` mask.
### Member types
| Type | Definition |
| --- | --- |
| `value_type` | `T` |
### Member functions
| | |
| --- | --- |
| [(constructor)](mask_array/mask_array "cpp/numeric/valarray/mask array/mask array") | constructs a `mask_array` (public member function) |
| [(destructor)](mask_array/~mask_array "cpp/numeric/valarray/mask array/~mask array") | destroys a `mask_array` (public member function) |
| [operator=](mask_array/operator= "cpp/numeric/valarray/mask array/operator=") | assigns contents (public member function) |
| [operator+=operator-=operator\*=operator/=operator%=operator&=operator|=operator^=operator<<=operator>>=](mask_array/operator_arith "cpp/numeric/valarray/mask array/operator arith") | performs arithmetic operation on the array referred by mask. (public member function) |
### Example
```
#include <iostream>
#include <valarray>
int main()
{
std::valarray<int> data = {0,1,2,3,4,5,6,7,8,9};
std::cout << "Initial valarray: ";
for(int n: data) std::cout << n << ' ';
std::cout << '\n';
data[data > 5] = -1;
// the type of data>5 is std::valarray<bool>
// the type of data[data>5] is std::mask_array<int>
std::cout << "After v[v>5]=-1: ";
for(int n: data) std::cout << n << ' ';
std::cout << '\n';
}
```
Output:
```
Initial valarray: 0 1 2 3 4 5 6 7 8 9
After v[v>5]=-1: 0 1 2 3 4 5 -1 -1 -1 -1
```
cpp std::tanh(std::valarray) std::tanh(std::valarray)
========================
| Defined in header `[<valarray>](../../header/valarray "cpp/header/valarray")` | | |
| --- | --- | --- |
|
```
template< class T >
valarray<T> tanh( const valarray<T>& va );
```
| | |
For each element in `va` computes hyperbolic tangent of the value of the element.
### Parameters
| | | |
| --- | --- | --- |
| va | - | value array to apply the operation to |
### Return value
Value array containing hyperbolic tangent of the values in `va`.
### Notes
Unqualified function (`tanh`) is used to perform the computation. If such function is not available, `[std::tanh](http://en.cppreference.com/w/cpp/numeric/math/tanh)` is used due to [argument-dependent lookup](../../language/adl "cpp/language/adl").
The function can be implemented with the return type different from `[std::valarray](../valarray "cpp/numeric/valarray")`. In this case, the replacement type has the following properties:
* All `const` member functions of `[std::valarray](../valarray "cpp/numeric/valarray")` are provided.
* `[std::valarray](../valarray "cpp/numeric/valarray")`, `[std::slice\_array](slice_array "cpp/numeric/valarray/slice array")`, `[std::gslice\_array](gslice_array "cpp/numeric/valarray/gslice array")`, `[std::mask\_array](mask_array "cpp/numeric/valarray/mask array")` and `[std::indirect\_array](indirect_array "cpp/numeric/valarray/indirect array")` can be constructed from the replacement type.
* All functions accepting an argument of type `const [std::valarray](http://en.cppreference.com/w/cpp/numeric/valarray)&` except [`begin()`](begin2 "cpp/numeric/valarray/begin2") and [`end()`](end2 "cpp/numeric/valarray/end2") (since C++11) should also accept the replacement type.
* All functions accepting two arguments of type `const [std::valarray](http://en.cppreference.com/w/cpp/numeric/valarray)&` should accept every combination of `const [std::valarray](http://en.cppreference.com/w/cpp/numeric/valarray)&` and the replacement type.
* The return type does not add more than two levels of template nesting over the most deeply-nested argument type.
### Possible implementation
| |
| --- |
|
```
template< class T >
valarray<T> tanh( const valarray<T>& va )
{
valarray<T> other = va;
for (T &i : other) {
i = tanh(i);
}
return other; // proxy object may be returned
}
```
|
### Example
```
#include <cmath>
#include <iostream>
#include <valarray>
auto show = [](char const* title, const std::valarray<double>& va) {
std::cout << title << " :";
for(auto x : va)
std::cout << " " << std::fixed << x;
std::cout << '\n';
};
int main()
{
const std::valarray<double> x = {.0, .1, .2, .3};
const std::valarray<double> sinh = std::sinh(x);
const std::valarray<double> cosh = std::cosh(x);
const std::valarray<double> tanh = std::tanh(x);
const std::valarray<double> tanh_by_def = sinh / cosh;
const std::valarray<double> tanh_2x = std::tanh(2.0 * x);
const std::valarray<double> tanh_2x_by_def =
(2.0 * tanh) / (1.0 + std::pow(tanh, 2.0));
show("x ", x);
show("tanh(x) ", tanh);
show("tanh(x) (def) ", tanh_by_def);
show("tanh(2*x) ", tanh_2x);
show("tanh(2*x) (def)", tanh_2x_by_def);
}
```
Output:
```
x : 0.000000 0.100000 0.200000 0.300000
tanh(x) : 0.000000 0.099668 0.197375 0.291313
tanh(x) (def) : 0.000000 0.099668 0.197375 0.291313
tanh(2*x) : 0.000000 0.197375 0.379949 0.537050
tanh(2*x) (def) : 0.000000 0.197375 0.379949 0.537050
```
### See also
| | |
| --- | --- |
| [sinh(std::valarray)](sinh "cpp/numeric/valarray/sinh") | applies the function `[std::sinh](../math/sinh "cpp/numeric/math/sinh")` to each element of valarray (function template) |
| [cosh(std::valarray)](cosh "cpp/numeric/valarray/cosh") | applies the function `[std::cosh](../math/cosh "cpp/numeric/math/cosh")` to each element of valarray (function template) |
| [tanhtanhftanhl](../math/tanh "cpp/numeric/math/tanh")
(C++11)(C++11) | computes hyperbolic tangent (\({\small\tanh{x} }\)tanh(x)) (function) |
| [tanh(std::complex)](../complex/tanh "cpp/numeric/complex/tanh") | computes hyperbolic tangent of a complex number (\({\small\tanh{z} }\)tanh(z)) (function template) |
cpp std::gslice_array std::gslice\_array
==================
| Defined in header `[<valarray>](../../header/valarray "cpp/header/valarray")` | | |
| --- | --- | --- |
|
```
template< class T > class gslice_array;
```
| | |
`std::gslice_array` is a helper template used by the [valarray subscript operator](operator_at "cpp/numeric/valarray/operator at") with `[std::gslice](http://en.cppreference.com/w/cpp/numeric/valarray/gslice)` argument. It has reference semantics to a subset of the array specified by the `[std::gslice](http://en.cppreference.com/w/cpp/numeric/valarray/gslice)` object.
### Member types
| Type | Definition |
| --- | --- |
| `value_type` | `T` |
### Member functions
| | |
| --- | --- |
| [(constructor)](gslice_array/gslice_array "cpp/numeric/valarray/gslice array/gslice array") | constructs a `gslice_array` (public member function) |
| [(destructor)](gslice_array/~gslice_array "cpp/numeric/valarray/gslice array/~gslice array") | destroys a `gslice_array` (public member function) |
| [operator=](gslice_array/operator= "cpp/numeric/valarray/gslice array/operator=") | assigns contents (public member function) |
| [operator+=operator-=operator\*=operator/=operator%=operator&=operator|=operator^=operator<<=operator>>=](gslice_array/operator_arith "cpp/numeric/valarray/gslice array/operator arith") | performs arithmetic operation on the array referred by generic slice. (public member function) |
### Example
```
#include <cassert>
#include <cstddef>
#include <iomanip>
#include <iostream>
#include <numeric>
#include <valarray>
int main()
{
std::valarray<int> data(32);
std::iota(std::begin(data), std::end(data), 0);
const std::size_t offset = 1, z = 2, y = 3, x = 4;
const std::valarray<std::size_t> sizes{z, y, x};
const std::valarray<std::size_t> strides{15, 5, 1};
const std::gslice gslice = std::gslice(offset, sizes, strides);
// indices are generated according to the formula:
// index[k] = offset + [0,1,2)*15 + [0,1,2,3)*5 + [0,1,2,3,4)*1
// = offset + inner_product(sizes[k], strides);
// where sizes[k] = {[0,z), [0,y), [0,x)}, while the rightmost index (x)
// runs fastest. As a result we have following set of indices:
// index[0] = 1 + 0*15 + 0*5 + 0*1 = 1
// index[1] = 1 + 0*15 + 0*5 + 1*1 = 2
// index[2] = 1 + 0*15 + 0*5 + 2*1 = 3
// index[3] = 1 + 0*15 + 0*5 + 3*1 = 4
// index[4] = 1 + 0*15 + 1*5 + 0*1 = 6
// index[5] = 1 + 0*15 + 1*5 + 1*1 = 7
// index[6] = 1 + 0*15 + 1*5 + 2*1 = 8
// index[7] = 1 + 0*15 + 1*5 + 3*1 = 9
// ...
// index[22] = 1 + 1*15 + 2*5 + 2*1 = 28
// index[23] = 1 + 1*15 + 2*5 + 3*1 = 29
const std::valarray<int> indices = data[gslice];
for (unsigned i=0; i != indices.size(); ++i) {
std::cout << std::setfill('0') << std::setw(2) << indices[i] << ' ';
}
std::cout << "\nTotal indices: " << indices.size() << '\n';
assert(indices.size() == x*y*z);
data = 0;
std::gslice_array<int> gslice_array = data[gslice];
gslice_array = 1;
// Cells that correspond to generated indices = '1', skipped cells = '0'.
for (auto i : data) { std::cout << i << ' '; }
std::cout << "\nSum of ones = " << data.sum() << '\n';
}
```
Output:
```
01 02 03 04 06 07 08 09 11 12 13 14 16 17 18 19 21 22 23 24 26 27 28 29
Total indices: 24
0 1 1 1 1 0 1 1 1 1 0 1 1 1 1 0 1 1 1 1 0 1 1 1 1 0 1 1 1 1 0 0
Sum of ones = 24
```
### See also
| | |
| --- | --- |
| [slice\_array](slice_array "cpp/numeric/valarray/slice array") | proxy to a subset of a valarray after applying a slice (class template) |
cpp std::exp(std::valarray) std::exp(std::valarray)
=======================
| Defined in header `[<valarray>](../../header/valarray "cpp/header/valarray")` | | |
| --- | --- | --- |
|
```
template< class T >
valarray<T> exp( const valarray<T>& va );
```
| | |
For each element in `va` computes *e* raised to the power equal to the value of the element.
### Parameters
| | | |
| --- | --- | --- |
| va | - | value array to apply the operation to |
### Return value
Value array containing *e* raised by the values in `va`.
### Notes
Unqualified function (`exp`) is used to perform the computation. If such function is not available, `[std::exp](http://en.cppreference.com/w/cpp/numeric/math/exp)` is used due to [argument-dependent lookup](../../language/adl "cpp/language/adl").
The function can be implemented with the return type different from `[std::valarray](../valarray "cpp/numeric/valarray")`. In this case, the replacement type has the following properties:
* All `const` member functions of `[std::valarray](../valarray "cpp/numeric/valarray")` are provided.
* `[std::valarray](../valarray "cpp/numeric/valarray")`, `[std::slice\_array](slice_array "cpp/numeric/valarray/slice array")`, `[std::gslice\_array](gslice_array "cpp/numeric/valarray/gslice array")`, `[std::mask\_array](mask_array "cpp/numeric/valarray/mask array")` and `[std::indirect\_array](indirect_array "cpp/numeric/valarray/indirect array")` can be constructed from the replacement type.
* All functions accepting an argument of type `const [std::valarray](http://en.cppreference.com/w/cpp/numeric/valarray)&` except [`begin()`](begin2 "cpp/numeric/valarray/begin2") and [`end()`](end2 "cpp/numeric/valarray/end2") (since C++11) should also accept the replacement type.
* All functions accepting two arguments of type `const [std::valarray](http://en.cppreference.com/w/cpp/numeric/valarray)&` should accept every combination of `const [std::valarray](http://en.cppreference.com/w/cpp/numeric/valarray)&` and the replacement type.
* The return type does not add more than two levels of template nesting over the most deeply-nested argument type.
### Possible implementation
| |
| --- |
|
```
template< class T >
valarray<T> exp( const valarray<T>& va )
{
valarray<T> other = va;
for (T &i : other) {
i = exp(i);
}
return other; // proxy object may be returned
}
```
|
### Example
This example demonstrates the [Euler's identity eiฯ
= -1](https://en.wikipedia.org/wiki/Euler%27s_identity "enwiki:Euler's identity") and the related exponents.
```
#include <iostream>
#include <complex>
#include <numbers>
#include <valarray>
int main()
{
const double pi = std::numbers::pi;
std::valarray<std::complex<double>> v = {
{0, 0}, {0, pi/2}, {0, pi}, {0, 3*pi/2}, {0, 2*pi}
};
std::valarray<std::complex<double>> v2 = std::exp(v);
for(std::cout << std::showpos << std::fixed; auto n : v2) {
std::cout << n << '\n';
}
}
```
Output:
```
(+1.000000,+0.000000)
(+0.000000,+1.000000)
(-1.000000,+0.000000)
(-0.000000,-1.000000)
(+1.000000,-0.000000)
```
### See also
| | |
| --- | --- |
| [log(std::valarray)](log "cpp/numeric/valarray/log") | applies the function `[std::log](../math/log "cpp/numeric/math/log")` to each element of valarray (function template) |
| [expexpfexpl](../math/exp "cpp/numeric/math/exp")
(C++11)(C++11) | returns *e* raised to the given power (\({\small e^x}\)ex) (function) |
| [exp(std::complex)](../complex/exp "cpp/numeric/complex/exp") | complex base *e* exponential (function template) |
cpp std::valarray<T>::sum std::valarray<T>::sum
=====================
| | | |
| --- | --- | --- |
|
```
T sum() const;
```
| | |
Computes the sum of the elements.
The function can be used only if `operator+=` is defined for type `T`. If the `std::valarray` is empty, the behavior is undefined. The order in which the elements are processed by this function is unspecified.
### Parameters
(none).
### Return value
The sum of the elements.
### Example
```
#include <iostream>
#include <valarray>
int main()
{
std::valarray<int> a = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
std::cout << a.sum() << '\n';
}
```
Output:
```
55
```
### See also
| | |
| --- | --- |
| [apply](apply "cpp/numeric/valarray/apply") | applies a function to every element of a valarray (public member function) |
| [accumulate](../../algorithm/accumulate "cpp/algorithm/accumulate") | sums up a range of elements (function template) |
cpp std::valarray<T>::resize std::valarray<T>::resize
========================
| | | |
| --- | --- | --- |
|
```
void resize( std::size_t count, T value = T() );
```
| | |
Resizes the valarray to contain `count` elements and assigns `value` to each element.
This functions invalidates all pointers and references to elements in the array.
### Parameters
| | | |
| --- | --- | --- |
| count | - | new size of the container |
| value | - | the value to initialize the new elements with |
### Return value
(none).
### Example
```
#include <valarray>
#include <iostream>
int main()
{
std::valarray<int> v{1,2,3};
v.resize(10);
for(int n: v) std::cout << n << ' ';
std::cout << '\n';
}
```
Output:
```
0 0 0 0 0 0 0 0 0 0
```
### See also
| | |
| --- | --- |
| [size](size "cpp/numeric/valarray/size") | returns the size of valarray (public member function) |
cpp std::slice std::slice
==========
| Defined in header `[<valarray>](../../header/valarray "cpp/header/valarray")` | | |
| --- | --- | --- |
|
```
class slice;
```
| | |
`std::slice` is the selector class that identifies a subset of `[std::valarray](../valarray "cpp/numeric/valarray")` similar to [BLAS](https://en.wikipedia.org/wiki/BLAS "enwiki:BLAS") slice. An object of type `std::slice` holds three values: the starting index, the stride, and the total number of values in the subset. Objects of type `std::slice` can be used as indexes with valarray's `operator[]`.
### Member functions
| | |
| --- | --- |
| **(constructor)** | constructs a slice (public member function) |
| **startsizestride** | returns the parameters of the slice (public member function) |
std::slice::slice
------------------
| | | |
| --- | --- | --- |
|
```
slice()
```
| (1) | |
|
```
slice( std::size_t start, std::size_t size, std::size_t stride );
```
| (2) | |
|
```
slice( const slice& other );
```
| (3) | |
Constructs a new slice.
1) Default constructor. Equivalent to `slice(0, 0, 0)`. This constructor exists only to allow construction of arrays of slices.
2) Constructs a new slice with parameters `start`, `size`, `stride`. This slice will refer to `size` number of elements, each with the position:
start + 0\*stride
start + 1\*stride
...
start + (size-1)\*stride
3) Constructs a copy of `other`. ### Parameters
| | | |
| --- | --- | --- |
| start | - | the position of the first element |
| size | - | the number of elements in the slice |
| stride | - | the number of positions between successive elements in the slice |
| other | - | another slice to copy |
std::slice::start, size, stride
--------------------------------
| | | |
| --- | --- | --- |
|
```
std::size_t start() const;
```
| (1) | |
|
```
std::size_t size() const;
```
| (2) | |
|
```
std::size_t stride() const;
```
| (3) | |
Returns the parameters passed to the slice on construction - start, size and stride respectively.
### Parameters
(none).
### Return value
The parameters of the slice -- start, size and stride respectively.
### Complexity
Constant.
### Non-member functions
| | |
| --- | --- |
| **operator==(std::slice)**
(C++20) | checks if two slices are equal (function) |
operator==(std::slice)
-----------------------
| | | |
| --- | --- | --- |
|
```
friend bool operator==( const slice& lhs, const slice& rhs );
```
| | (since C++20) |
Checks if the parameters of `lhs` and `rhs` - start, size and stride are equal respectively.
This function is not visible to ordinary [unqualified](../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../language/adl "cpp/language/adl") when `std::slice` is an associated class of the arguments.
The `!=` operator is [synthesized](../../language/operators#Relational_operators "cpp/language/operators") from `operator==`.
### Parameters
| | | |
| --- | --- | --- |
| lhs, rhs | - | slices to compare |
### Return value
`lhs.start() == rhs.start() && lhs.size() == rhs.size() && lhs.stride() == rhs.stride()`.
### Example
Barebones valarray-backed Matrix class with a [trace](https://en.wikipedia.org/wiki/Trace_(linear_algebra) "enwiki:Trace (linear algebra)") calculating function.
```
#include <iostream>
#include <valarray>
class Matrix {
std::valarray<int> data;
int dim;
public:
Matrix(int r, int c) : data(r*c), dim(c) {}
int& operator()(int r, int c) {return data[r*dim + c];}
int trace() const {
return data[std::slice(0, dim, dim+1)].sum();
}
};
int main()
{
Matrix m(3,3);
int n = 0;
for(int r=0; r<3; ++r)
for(int c=0; c<3; ++c)
m(r, c) = ++n;
std::cout << "Trace of the matrix (1,2,3) (4,5,6) (7,8,9) is " << m.trace() << '\n';
}
```
Output:
```
Trace of the matrix (1,2,3) (4,5,6) (7,8,9) is 15
```
### See also
| | |
| --- | --- |
| [operator[]](operator_at "cpp/numeric/valarray/operator at") | get/set valarray element, slice, or mask (public member function) |
| [gslice](gslice "cpp/numeric/valarray/gslice") | generalized slice of a valarray: starting index, set of lengths, set of strides (class) |
| [slice\_array](slice_array "cpp/numeric/valarray/slice array") | proxy to a subset of a valarray after applying a slice (class template) |
| programming_docs |
cpp std::sinh(std::valarray) std::sinh(std::valarray)
========================
| Defined in header `[<valarray>](../../header/valarray "cpp/header/valarray")` | | |
| --- | --- | --- |
|
```
template< class T >
valarray<T> sinh( const valarray<T>& va );
```
| | |
For each element in `va` computes hyperbolic sine of the value of the element.
### Parameters
| | | |
| --- | --- | --- |
| va | - | value array to apply the operation to |
### Return value
Value array containing hyperbolic sine of the values in `va`.
### Notes
Unqualified function (`sinh`) is used to perform the computation. If such function is not available, `[std::sinh](http://en.cppreference.com/w/cpp/numeric/math/sinh)` is used due to [argument-dependent lookup](../../language/adl "cpp/language/adl").
The function can be implemented with the return type different from `[std::valarray](../valarray "cpp/numeric/valarray")`. In this case, the replacement type has the following properties:
* All `const` member functions of `[std::valarray](../valarray "cpp/numeric/valarray")` are provided.
* `[std::valarray](../valarray "cpp/numeric/valarray")`, `[std::slice\_array](slice_array "cpp/numeric/valarray/slice array")`, `[std::gslice\_array](gslice_array "cpp/numeric/valarray/gslice array")`, `[std::mask\_array](mask_array "cpp/numeric/valarray/mask array")` and `[std::indirect\_array](indirect_array "cpp/numeric/valarray/indirect array")` can be constructed from the replacement type.
* All functions accepting an argument of type `const [std::valarray](http://en.cppreference.com/w/cpp/numeric/valarray)&` except [`begin()`](begin2 "cpp/numeric/valarray/begin2") and [`end()`](end2 "cpp/numeric/valarray/end2") (since C++11) should also accept the replacement type.
* All functions accepting two arguments of type `const [std::valarray](http://en.cppreference.com/w/cpp/numeric/valarray)&` should accept every combination of `const [std::valarray](http://en.cppreference.com/w/cpp/numeric/valarray)&` and the replacement type.
* The return type does not add more than two levels of template nesting over the most deeply-nested argument type.
### Possible implementation
| |
| --- |
|
```
template< class T >
valarray<T> sinh( const valarray<T>& va )
{
valarray<T> other = va;
for (T &i : other) {
i = sinh(i);
}
return other; // proxy object may be returned
}
```
|
### Example
```
#include <cmath>
#include <iomanip>
#include <iostream>
#include <valarray>
#include <complex>
template<typename T>
void show(char const* title, const std::valarray<T>& va)
{
std::cout << title << " : " << std::right;
for (T x : va) {
std::cout << std::fixed << x << " ";
}
std::cout << '\n';
}
template<typename T>
void sinh_for(std::valarray<T> const& z)
{
// Hyperbolic sine is sinh(z) = (eแถป - eโปแถป) / 2.
const std::valarray<T> sinh_z { std::sinh(z) };
const std::valarray<T> e_z { std::exp(z) };
const std::valarray<T> e_neg_z { std::exp(-z) };
const std::valarray<T> sinh_def { (e_z - e_neg_z) / 2.0f };
show("n ", z);
show("sinh(n) ", sinh_z);
show("(eโฟ-eโปโฟ)/2", sinh_def);
std::cout.put('\n');
}
int main()
{
sinh_for(std::valarray<float>{ -.2f, -.1f, 0.f, .1f, .2f, INFINITY });
sinh_for(std::valarray<std::complex<double>>{ {-.2,-.1}, {.2,.1} });
}
```
Output:
```
n : -0.200000 -0.100000 0.000000 0.100000 0.200000 inf
sinh(n) : -0.201336 -0.100167 0.000000 0.100167 0.201336 inf
(eโฟ-eโปโฟ)/2 : -0.201336 -0.100167 0.000000 0.100167 0.201336 inf
n : (-0.200000,-0.100000) (0.200000,0.100000)
sinh(n) : (-0.200330,-0.101837) (0.200330,0.101837)
(eโฟ-eโปโฟ)/2 : (-0.200330,-0.101837) (0.200330,0.101837)
```
### See also
| | |
| --- | --- |
| [cosh(std::valarray)](cosh "cpp/numeric/valarray/cosh") | applies the function `[std::cosh](../math/cosh "cpp/numeric/math/cosh")` to each element of valarray (function template) |
| [tanh(std::valarray)](tanh "cpp/numeric/valarray/tanh") | applies the function `[std::tanh](../math/tanh "cpp/numeric/math/tanh")` to each element of valarray (function template) |
| [sinhsinhfsinhl](../math/sinh "cpp/numeric/math/sinh")
(C++11)(C++11) | computes hyperbolic sine (\({\small\sinh{x} }\)sinh(x)) (function) |
| [sinh(std::complex)](../complex/sinh "cpp/numeric/complex/sinh") | computes hyperbolic sine of a complex number (\({\small\sinh{z} }\)sinh(z)) (function template) |
cpp std::valarray<T>::max std::valarray<T>::max
=====================
| | | |
| --- | --- | --- |
|
```
T max() const;
```
| | |
Computes the maximum value of the elements.
If there are no elements, the behavior is undefined.
The function can be used only if `operator<` is defined for type `T`.
### Parameters
(none).
### Return value
The maximum of the elements.
### Example
```
#include <valarray>
#include <iostream>
int main()
{
std::valarray<double> a{1, 2, 3, 4, 5, 6, 7, 8};
std::cout << "Maximum value : " << a.max() << "\n";
}
```
Output:
```
Maximum value : 8
```
### See also
| | |
| --- | --- |
| [min](min "cpp/numeric/valarray/min") | returns the smallest element (public member function) |
cpp std::swap(std::valarray)
std::swap(std::valarray)
========================
| Defined in header `[<valarray>](../../header/valarray "cpp/header/valarray")` | | |
| --- | --- | --- |
|
```
template< class T >
void swap( std::valarray<T> &lhs, std::valarray<T> &rhs ) noexcept;
```
| | (since C++11) |
Specializes the `[std::swap](../../algorithm/swap "cpp/algorithm/swap")` algorithm for `[std::valarray](../valarray "cpp/numeric/valarray")`. Swaps the contents of `lhs` and `rhs`. Calls `lhs.swap(rhs)`.
### Parameters
| | | |
| --- | --- | --- |
| lhs, rhs | - | valarrays whose contents to swap |
### Return value
(none).
### Complexity
Constant.
### See also
| | |
| --- | --- |
| [swap](swap "cpp/numeric/valarray/swap") | swaps with another valarray (public member function) |
cpp std::valarray<T>::shift std::valarray<T>::shift
=======================
| | | |
| --- | --- | --- |
|
```
valarray<T> shift( int count ) const;
```
| | |
Returns a new valarray of the same size with elements whose positions are shifted by `count` elements. The new position of each element is iโcount where i is the previous position. The value of shifted in elements is `T()`.
### Parameters
| | | |
| --- | --- | --- |
| count | - | number of positions to shift the elements by |
### Return value
The resulting valarray with shifted elements.
### Notes
The function can be implemented with the return type different from `[std::valarray](../valarray "cpp/numeric/valarray")`. In this case, the replacement type has the following properties:
* All `const` member functions of `[std::valarray](../valarray "cpp/numeric/valarray")` are provided.
* `[std::valarray](../valarray "cpp/numeric/valarray")`, `[std::slice\_array](slice_array "cpp/numeric/valarray/slice array")`, `[std::gslice\_array](gslice_array "cpp/numeric/valarray/gslice array")`, `[std::mask\_array](mask_array "cpp/numeric/valarray/mask array")` and `[std::indirect\_array](indirect_array "cpp/numeric/valarray/indirect array")` can be constructed from the replacement type.
* All functions accepting an argument of type `const [std::valarray](http://en.cppreference.com/w/cpp/numeric/valarray)&` except [`begin()`](begin2 "cpp/numeric/valarray/begin2") and [`end()`](end2 "cpp/numeric/valarray/end2") (since C++11) should also accept the replacement type.
* All functions accepting two arguments of type `const [std::valarray](http://en.cppreference.com/w/cpp/numeric/valarray)&` should accept every combination of `const [std::valarray](http://en.cppreference.com/w/cpp/numeric/valarray)&` and the replacement type.
* The return type does not add more than two levels of template nesting over the most deeply-nested argument type.
### Example
```
#include <iostream>
#include <valarray>
int main() {
std::valarray<int> v{1, 2, 3, 4, 5, 6, 7, 8};
for (auto const& val : v) {
std::cout << val << " ";
}
std::cout << "\n";
std::valarray<int> v2 = v.shift(2);
for (auto const& val : v2) {
std::cout << val << " ";
}
std::cout << "\n";
}
```
Output:
```
1 2 3 4 5 6 7 8
3 4 5 6 7 8 0 0
```
### See also
| | |
| --- | --- |
| [cshift](cshift "cpp/numeric/valarray/cshift") | circular shift of the elements of the valarray (public member function) |
cpp std::valarray<T>::min std::valarray<T>::min
=====================
| | | |
| --- | --- | --- |
|
```
T min() const;
```
| | |
Computes the minimum value of the elements.
If there are no elements, the behavior is undefined.
The function can be used only if `operator<` is defined for type `T`.
### Parameters
(none).
### Return value
The minimum of the elements.
### Example
```
#include <valarray>
#include <iostream>
int main()
{
std::valarray<double> a{1, 2, 3, 4, 5, 6, 7, 8};
std::cout << "Minimum value : " << a.min() << "\n";
}
```
Output:
```
Minimum value : 1
```
### See also
| | |
| --- | --- |
| [max](max "cpp/numeric/valarray/max") | returns the largest element (public member function) |
cpp std::log(std::valarray) std::log(std::valarray)
=======================
| Defined in header `[<valarray>](../../header/valarray "cpp/header/valarray")` | | |
| --- | --- | --- |
|
```
template< class T >
valarray<T> log( const valarray<T>& va );
```
| | |
For each element in `va` computes natural logarithm of the value of the element.
### Parameters
| | | |
| --- | --- | --- |
| va | - | value array to apply the operation to |
### Return value
Value array containing natural logarithms of the values in `va`.
### Notes
Unqualified function (`log`) is used to perform the computation. If such function is not available, `[std::log](http://en.cppreference.com/w/cpp/numeric/math/log)` is used due to [argument-dependent lookup](../../language/adl "cpp/language/adl").
The function can be implemented with the return type different from `[std::valarray](../valarray "cpp/numeric/valarray")`. In this case, the replacement type has the following properties:
* All `const` member functions of `[std::valarray](../valarray "cpp/numeric/valarray")` are provided.
* `[std::valarray](../valarray "cpp/numeric/valarray")`, `[std::slice\_array](slice_array "cpp/numeric/valarray/slice array")`, `[std::gslice\_array](gslice_array "cpp/numeric/valarray/gslice array")`, `[std::mask\_array](mask_array "cpp/numeric/valarray/mask array")` and `[std::indirect\_array](indirect_array "cpp/numeric/valarray/indirect array")` can be constructed from the replacement type.
* All functions accepting an argument of type `const [std::valarray](http://en.cppreference.com/w/cpp/numeric/valarray)&` except [`begin()`](begin2 "cpp/numeric/valarray/begin2") and [`end()`](end2 "cpp/numeric/valarray/end2") (since C++11) should also accept the replacement type.
* All functions accepting two arguments of type `const [std::valarray](http://en.cppreference.com/w/cpp/numeric/valarray)&` should accept every combination of `const [std::valarray](http://en.cppreference.com/w/cpp/numeric/valarray)&` and the replacement type.
* The return type does not add more than two levels of template nesting over the most deeply-nested argument type.
### Possible implementation
| |
| --- |
|
```
template< class T >
valarray<T> log( const valarray<T>& va )
{
valarray<T> other = va;
for (T &i : other) {
i = log(i);
}
return other; // proxy object may be returned
}
```
|
### Example
```
#include <iomanip>
#include <iostream>
#include <valarray>
void show(char const* title, const std::valarray<double>& va)
{
std::cout << title << " :" << std::right << std::fixed;
for (double x : va) {
std::cout << std::setw(10) << x;
}
std::cout << '\n';
}
int main()
{
const std::valarray<double> n { 0.0, 1.0, 2.0, 3.0 };
const std::valarray<double> exp_n { std::exp(n) };
const std::valarray<double> log_exp_n { std::log(exp_n) };
show("n ", n);
show("eโฟ ", exp_n);
show("log(eโฟ)", log_exp_n);
}
```
Output:
```
n : 0.000000 1.000000 2.000000 3.000000
eโฟ : 1.000000 2.718282 7.389056 20.085537
log(eโฟ) : 0.000000 1.000000 2.000000 3.000000
```
### See also
| | |
| --- | --- |
| [log10(std::valarray)](log10 "cpp/numeric/valarray/log10") | applies the function `[std::log10](../math/log10 "cpp/numeric/math/log10")` to each element of valarray (function template) |
| [exp(std::valarray)](exp "cpp/numeric/valarray/exp") | applies the function `[std::exp](../math/exp "cpp/numeric/math/exp")` to each element of valarray (function template) |
| [loglogflogl](../math/log "cpp/numeric/math/log")
(C++11)(C++11) | computes natural (base *e*) logarithm (\({\small \ln{x} }\)ln(x)) (function) |
| [log(std::complex)](../complex/log "cpp/numeric/complex/log") | complex natural logarithm with the branch cuts along the negative real axis (function template) |
cpp std::abs(std::valarray) std::abs(std::valarray)
=======================
| Defined in header `[<valarray>](../../header/valarray "cpp/header/valarray")` | | |
| --- | --- | --- |
|
```
template< class T >
valarray<T> abs( const valarray<T>& va );
```
| | |
Computes absolute value of each element in the value array.
### Parameters
| | | |
| --- | --- | --- |
| va | - | value array to apply the operation to |
### Return value
Value array containing absolute values of the values in `va`.
### Notes
Unqualified function (`abs`) is used to perform the computation. If such function is not available, `std::abs` is used due to [argument-dependent lookup](../../language/adl "cpp/language/adl").
The function can be implemented with the return type different from `[std::valarray](../valarray "cpp/numeric/valarray")`. In this case, the replacement type has the following properties:
* All `const` member functions of `[std::valarray](../valarray "cpp/numeric/valarray")` are provided.
* `[std::valarray](../valarray "cpp/numeric/valarray")`, `[std::slice\_array](slice_array "cpp/numeric/valarray/slice array")`, `[std::gslice\_array](gslice_array "cpp/numeric/valarray/gslice array")`, `[std::mask\_array](mask_array "cpp/numeric/valarray/mask array")` and `[std::indirect\_array](indirect_array "cpp/numeric/valarray/indirect array")` can be constructed from the replacement type.
* All functions accepting an argument of type `const [std::valarray](http://en.cppreference.com/w/cpp/numeric/valarray)&` except [`begin()`](begin2 "cpp/numeric/valarray/begin2") and [`end()`](end2 "cpp/numeric/valarray/end2") (since C++11) should also accept the replacement type.
* All functions accepting two arguments of type `const [std::valarray](http://en.cppreference.com/w/cpp/numeric/valarray)&` should accept every combination of `const [std::valarray](http://en.cppreference.com/w/cpp/numeric/valarray)&` and the replacement type.
* The return type does not add more than two levels of template nesting over the most deeply-nested argument type.
### Possible implementation
| |
| --- |
|
```
template< class T >
valarray<T> abs( const valarray<T>& va )
{
valarray<T> other = va;
for (T &i : other) {
i = abs(i);
}
return other; // proxy object may be returned
}
```
|
### Example
```
#include <valarray>
#include <iostream>
int main()
{
std::valarray<int> v{1, -2, 3, -4, 5, -6, 7, -8};
std::valarray<int> v2 = std::abs(v);
for(auto n : v2) {
std::cout << n << ' ';
}
std::cout << '\n';
}
```
Output:
```
1 2 3 4 5 6 7 8
```
### See also
| | |
| --- | --- |
| [abs(int)labsllabs](../math/abs "cpp/numeric/math/abs")
(C++11) | computes absolute value of an integral value (\(\small{|x|}\)|x|) (function) |
| [abs(float)fabsfabsffabsl](../math/fabs "cpp/numeric/math/fabs")
(C++11)(C++11) | absolute value of a floating point value (\(\small{|x|}\)|x|) (function) |
| [abs(std::complex)](../complex/abs "cpp/numeric/complex/abs") | returns the magnitude of a complex number (function template) |
cpp std::valarray<T>::operator= std::valarray<T>::operator=
===========================
| | | |
| --- | --- | --- |
|
```
valarray<T>& operator=( const valarray<T>& other );
```
| (1) | |
|
```
valarray<T>& operator=( valarray<T>&& other ) noexcept;
```
| (2) | (since C++11) |
|
```
valarray<T>& operator=( const T& val );
```
| (3) | |
|
```
valarray<T>& operator=( const std::slice_array<T>& other);
```
| (4) | |
|
```
valarray<T>& operator=( const std::gslice_array<T>& other);
```
| (5) | |
|
```
valarray<T>& operator=( const std::mask_array<T>& other );
```
| (6) | |
|
```
valarray<T>& operator=( const std::indirect_array<T>& other );
```
| (7) | |
|
```
valarray<T>& operator=( std::initializer_list<T> il );
```
| (8) | (since C++11) |
Replaces the contents of the numeric array.
1) Copy assignment operator. Each element of `*this` is assigned the value of the corresponding element of `other`. If the length of `other` does not equal the length of `*this`, the behavior is undefined (until C++11) first resizes as if by `resize(other.size())` (since C++11).
2) Move assignment operator. Replaces the contents of `*this` with those of `other`. The value of `other` is unspecified after this operation. The complexity of this operation may be linear if T has non-trivial destructors, but is usually constant otherwise.
3) Replaces each value in `*this` with a copy of `val`.
4-7) Replaces the contents of `*this` with the result of a generalized subscripting operation. The behavior is undefined if the length of the argument does not equal the length of `*this` or if any value on the left depends on the value on the right (e.g `v=v[v>2]`).
8) Assigns the contents of initializer list `il`. Equivalent to `*this = valarray(il)`. ### Parameters
| | | |
| --- | --- | --- |
| other | - | another numeric array (or a mask) to assign |
| val | - | the value to initialize each element with |
| il | - | initializer list to assign |
### Return value
`*this`.
### Exceptions
1, 3-8) May throw implementation-defined exceptions. ### Example
```
#include <iomanip>
#include <iostream>
#include <valarray>
void print(const char* rem, const std::valarray<int>& v)
{
std::cout << std::left << std::setw(36) << rem << std::right;
for (int n: v) std::cout << std::setw(3) << n;
std::cout << '\n';
}
int main()
{
std::valarray<int> v1(3);
v1 = -1; // (3) from a scalar
print("assigned from scalar: ", v1);
v1 = {1, 2, 3, 4, 5, 6}; // (8): from initializer list of different size
print("assigned from initializer_list:", v1);
std::valarray<int> v2(3);
v2 = v1[std::slice(0,3,2)]; // (4): from slice array
print("every 2nd element starting at pos 0:", v2);
v2 = v1[v1 % 2 == 0]; // (6): from mask array
print("values that are even:", v2);
std::valarray<std::size_t> idx = {0,1,2,4}; // index array
v2.resize(4); // sizes must match when assigning from gen subscript
v2 = v1[idx]; // (7): from indirect array
print("values at positions 0, 1, 2, 4:", v2);
}
```
Output:
```
assigned from scalar: -1 -1 -1
assigned from initializer_list: 1 2 3 4 5 6
every 2nd element starting at pos 0: 1 3 5
values that are even: 2 4 6
values at positions 0, 1, 2, 4: 1 2 3 5
```
cpp std::log10(std::valarray) std::log10(std::valarray)
=========================
| Defined in header `[<valarray>](../../header/valarray "cpp/header/valarray")` | | |
| --- | --- | --- |
|
```
template< class T >
valarray<T> log10( const valarray<T>& va );
```
| | |
For each element in `va` computes common (base 10) logarithm of the value of the element.
### Parameters
| | | |
| --- | --- | --- |
| va | - | value array to apply the operation to |
### Return value
Value array containing common logarithms of the values in `va`.
### Notes
Unqualified function (`log10`) is used to perform the computation. If such function is not available, `[std::log10](http://en.cppreference.com/w/cpp/numeric/math/log10)` is used due to [argument-dependent lookup](../../language/adl "cpp/language/adl").
The function can be implemented with the return type different from `[std::valarray](../valarray "cpp/numeric/valarray")`. In this case, the replacement type has the following properties:
* All `const` member functions of `[std::valarray](../valarray "cpp/numeric/valarray")` are provided.
* `[std::valarray](../valarray "cpp/numeric/valarray")`, `[std::slice\_array](slice_array "cpp/numeric/valarray/slice array")`, `[std::gslice\_array](gslice_array "cpp/numeric/valarray/gslice array")`, `[std::mask\_array](mask_array "cpp/numeric/valarray/mask array")` and `[std::indirect\_array](indirect_array "cpp/numeric/valarray/indirect array")` can be constructed from the replacement type.
* All functions accepting an argument of type `const [std::valarray](http://en.cppreference.com/w/cpp/numeric/valarray)&` except [`begin()`](begin2 "cpp/numeric/valarray/begin2") and [`end()`](end2 "cpp/numeric/valarray/end2") (since C++11) should also accept the replacement type.
* All functions accepting two arguments of type `const [std::valarray](http://en.cppreference.com/w/cpp/numeric/valarray)&` should accept every combination of `const [std::valarray](http://en.cppreference.com/w/cpp/numeric/valarray)&` and the replacement type.
* The return type does not add more than two levels of template nesting over the most deeply-nested argument type.
### Possible implementation
| |
| --- |
|
```
template< class T >
valarray<T> log10( const valarray<T>& va )
{
valarray<T> other = va;
for (T &i : other) {
i = log10(i);
}
return other; // proxy object may be returned
}
```
|
### Example
```
#include <cmath>
#include <iomanip>
#include <iostream>
#include <valarray>
void show(char const* title, const std::valarray<float>& va)
{
std::cout << title << " : " << std::right;
for (float x : va) {
std::cout << std::setw(6) << x;
}
std::cout << '\n';
}
int main()
{
const std::valarray<float> n { -2.f, -1.f, 0.f, 1.f, 2.f, 3.f, INFINITY };
const std::valarray<float> pow10 { std::pow(10.f, n) };
const std::valarray<float> log10_pow10 { std::log10(pow10) };
show("n ", n);
show("10โฟ ", pow10);
show("lg(10โฟ)", log10_pow10);
}
```
Output:
```
n : -2 -1 0 1 2 3 inf
10โฟ : 0.01 0.1 1 10 100 1000 inf
lg(10โฟ) : -2 -1 0 1 2 3 inf
```
### See also
| | |
| --- | --- |
| [log(std::valarray)](log "cpp/numeric/valarray/log") | applies the function `[std::log](../math/log "cpp/numeric/math/log")` to each element of valarray (function template) |
| [log10log10flog10l](../math/log10 "cpp/numeric/math/log10")
(C++11)(C++11) | computes common (base *10*) logarithm (\({\small \log\_{10}{x} }\)log10(x)) (function) |
| [log10(std::complex)](../complex/log10 "cpp/numeric/complex/log10") | complex common logarithm with the branch cuts along the negative real axis (function template) |
| programming_docs |
cpp std::valarray<T>::valarray std::valarray<T>::valarray
==========================
| | | |
| --- | --- | --- |
|
```
valarray();
```
| (1) | |
|
```
explicit valarray( std::size_t count );
```
| (2) | |
|
```
valarray( const T& val, std::size_t count );
```
| (3) | |
|
```
valarray( const T* vals, std::size_t count );
```
| (4) | |
|
```
valarray( const valarray& other );
```
| (5) | |
|
```
valarray( valarray&& other ) noexcept;
```
| (6) | (since C++11) |
|
```
valarray( const std::slice_array<T>& sa );
```
| (7) | |
|
```
valarray( const std::gslice_array<T>& gsa );
```
| (8) | |
|
```
valarray( const std::mask_array<T>& ma );
```
| (9) | |
|
```
valarray( const std::indirect_array<T>& ia );
```
| (10) | |
|
```
valarray( std::initializer_list<T> il );
```
| (11) | (since C++11) |
Constructs new numeric array from various sources.
1) Default constructor. Constructs an empty numeric array.
2) Constructs a numeric array with `count` copies of [value-initialized](../../language/value_initialization "cpp/language/value initialization") elements.
3) Constructs a numeric array with `count` copies of `val`.
4) Constructs a numeric array with copies of `count` values from an array pointed to by `vals`. If this array contains less than `count` values, the behavior is undefined.
5) Copy constructor. Constructs the numeric array with the copy of the contents of `other`.
6) Move constructor. Constructs the container with the contents of `other` using move semantics.
7-10) [Converting constructor](../../language/converting_constructor "cpp/language/converting constructor"). Convert the corresponding data structure to a `valarray`.
11) Constructs the numeric array with the contents of the initializer list `il`. ### Parameters
| | | |
| --- | --- | --- |
| count | - | the number of elements to construct |
| val | - | the value to initialize the elements with |
| vals | - | pointer to a C array to use as source to initialize the contents |
| other | - | another numeric array to use as source to initialize the contents |
| sa | - | slice array to initialize the elements with |
| gsa | - | generic slice array to initialize the elements with |
| ma | - | mask array to initialize the elements with |
| ia | - | indirect array to initialize the elements with |
| il | - | initializer list to initialize the elements with |
### Exceptions
1-5, 7-11) May throw implementation-defined exceptions. ### Example
cpp std::atan2(std::valarray) std::atan2(std::valarray)
=========================
| Defined in header `[<valarray>](../../header/valarray "cpp/header/valarray")` | | |
| --- | --- | --- |
|
```
template< class T >
std::valarray<T> atan2( const std::valarray<T>& y, const std::valarray<T>& x );
```
| (1) | |
|
```
template< class T >
std::valarray<T> atan2( const std::valarray<T>& y,
const typename std::valarray<T>::value_type& vx );
```
| (2) | |
|
```
template< class T >
std::valarray<T> atan2( const typename std::valarray<T>::value_type& vy,
const std::valarray<T>& x );
```
| (3) | |
Computes the inverse tangent of `y/x` using the signs of arguments to correctly determine quadrant.
1) Computes the inverse tangent of each pair of corresponding values from `y` and `x`. The behavior is undefined if `x.size() != y.size()`.
2) Computes the inverse tangent of `vx` and each value in the numeric array `y`.
3) Computes the inverse tangent of `vy` and each value in the numeric array `x`. ### Parameters
| | | |
| --- | --- | --- |
| x, y | - | numeric arrays to compute inverse tangent of |
| vy, vx | - | values to compute inverse tangent of |
### Return value
A numeric array containing the results of computation of inverse tangent.
### Notes
Unqualified function (`atan2`) is used to perform the computation. If such function is not available, `[std::atan2](http://en.cppreference.com/w/cpp/numeric/math/atan2)` is used due to [argument-dependent lookup](../../language/adl "cpp/language/adl").
The function can be implemented with the return type different from `[std::valarray](../valarray "cpp/numeric/valarray")`. In this case, the replacement type has the following properties:
* All `const` member functions of `[std::valarray](../valarray "cpp/numeric/valarray")` are provided.
* `[std::valarray](../valarray "cpp/numeric/valarray")`, `[std::slice\_array](slice_array "cpp/numeric/valarray/slice array")`, `[std::gslice\_array](gslice_array "cpp/numeric/valarray/gslice array")`, `[std::mask\_array](mask_array "cpp/numeric/valarray/mask array")` and `[std::indirect\_array](indirect_array "cpp/numeric/valarray/indirect array")` can be constructed from the replacement type.
* All functions accepting an argument of type `const [std::valarray](http://en.cppreference.com/w/cpp/numeric/valarray)&` except [`begin()`](begin2 "cpp/numeric/valarray/begin2") and [`end()`](end2 "cpp/numeric/valarray/end2") (since C++11) should also accept the replacement type.
* All functions accepting two arguments of type `const [std::valarray](http://en.cppreference.com/w/cpp/numeric/valarray)&` should accept every combination of `const [std::valarray](http://en.cppreference.com/w/cpp/numeric/valarray)&` and the replacement type.
* The return type does not add more than two levels of template nesting over the most deeply-nested argument type.
### Example
```
#include <algorithm>
#include <cmath>
#include <iostream>
#include <iomanip>
#include <valarray>
void show(char const* title, const std::valarray<double>& va) {
std::cout << title << " ";
std::for_each(std::begin(va), std::end(va), [](const double x) {
std::cout << " " << std::right << std::setw(4) << x << "ยฐ";
});
std::cout << '\n';
}
const double pi = std::acos(-1.0); // C++20: std::numbers::pi
int main()
{
auto degrees_to_radians = [](double const& x) { return (pi * x / 180); };
auto radians_to_degrees = [](double const& x) { return (180 * x / pi); };
const std::valarray<double> degrees{-90, -60, -45, -30, 0, 30, 45, 60, 90};
const std::valarray<double> radians = degrees.apply(degrees_to_radians);
const auto sin = std::sin(radians);
const auto cos = std::cos(radians);
show("(1)", std::atan2(sin, cos).apply(radians_to_degrees));
show("(2)", std::atan2(sin/cos, 1.0).apply(radians_to_degrees));
show("(3)", std::atan2(1.0, cos/sin).apply(radians_to_degrees));
}
```
Output:
```
(1) -90ยฐ -60ยฐ -45ยฐ -30ยฐ 0ยฐ 30ยฐ 45ยฐ 60ยฐ 90ยฐ
(2) -90ยฐ -60ยฐ -45ยฐ -30ยฐ 0ยฐ 30ยฐ 45ยฐ 60ยฐ 90ยฐ
(3) 90ยฐ 120ยฐ 135ยฐ 150ยฐ 0ยฐ 30ยฐ 45ยฐ 60ยฐ 90ยฐ
```
### 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 3074](https://cplusplus.github.io/LWG/issue3074) | C++98 | `T` is deduced from both the scalar and the `valarray` for (2-3), disallowing mixed-type calls | only deduce `T` from the `valarray` |
### See also
| | |
| --- | --- |
| [asin(std::valarray)](asin "cpp/numeric/valarray/asin") | applies the function `[std::asin](../math/asin "cpp/numeric/math/asin")` to each element of valarray (function template) |
| [acos(std::valarray)](acos "cpp/numeric/valarray/acos") | applies the function `[std::acos](../math/acos "cpp/numeric/math/acos")` to each element of valarray (function template) |
| [atan(std::valarray)](atan "cpp/numeric/valarray/atan") | applies the function `[std::atan](../math/atan "cpp/numeric/math/atan")` to each element of valarray (function template) |
| [atan2atan2fatan2l](../math/atan2 "cpp/numeric/math/atan2")
(C++11)(C++11) | arc tangent, using signs to determine quadrants (function) |
| [arg](../complex/arg "cpp/numeric/complex/arg") | returns the phase angle (function template) |
cpp std::valarray<T>::cshift std::valarray<T>::cshift
========================
| | | |
| --- | --- | --- |
|
```
valarray<T> cshift( int count ) const;
```
| | |
Returns a new valarray of the same size with elements whose positions are shifted circularly by `count` elements. The new position of each element is (iโcount) mod s where i is the previous position and s is `size()`.
### Parameters
| | | |
| --- | --- | --- |
| count | - | number of positions to shift the elements by |
### Return value
The resulting valarray with circularly shifted elements.
### Notes
The function can be implemented with the return type different from `[std::valarray](../valarray "cpp/numeric/valarray")`. In this case, the replacement type has the following properties:
* All `const` member functions of `[std::valarray](../valarray "cpp/numeric/valarray")` are provided.
* `[std::valarray](../valarray "cpp/numeric/valarray")`, `[std::slice\_array](slice_array "cpp/numeric/valarray/slice array")`, `[std::gslice\_array](gslice_array "cpp/numeric/valarray/gslice array")`, `[std::mask\_array](mask_array "cpp/numeric/valarray/mask array")` and `[std::indirect\_array](indirect_array "cpp/numeric/valarray/indirect array")` can be constructed from the replacement type.
* All functions accepting an argument of type `const [std::valarray](http://en.cppreference.com/w/cpp/numeric/valarray)&` except [`begin()`](begin2 "cpp/numeric/valarray/begin2") and [`end()`](end2 "cpp/numeric/valarray/end2") (since C++11) should also accept the replacement type.
* All functions accepting two arguments of type `const [std::valarray](http://en.cppreference.com/w/cpp/numeric/valarray)&` should accept every combination of `const [std::valarray](http://en.cppreference.com/w/cpp/numeric/valarray)&` and the replacement type.
* The return type does not add more than two levels of template nesting over the most deeply-nested argument type.
### Example
```
#include <iostream>
#include <valarray>
int main() {
std::valarray<int> v{1, 2, 3, 4, 5, 6, 7, 8};
for (auto const& val : v) {
std::cout << val << " ";
}
std::cout << "\n";
std::valarray<int> v2 = v.cshift(2);
for (auto const& val : v2) {
std::cout << val << " ";
}
std::cout << "\n";
}
```
Output:
```
1 2 3 4 5 6 7 8
3 4 5 6 7 8 1 2
```
### See also
| | |
| --- | --- |
| [shift](shift "cpp/numeric/valarray/shift") | zero-filling shift the elements of the valarray (public member function) |
cpp std::acos(std::valarray) std::acos(std::valarray)
========================
| Defined in header `[<valarray>](../../header/valarray "cpp/header/valarray")` | | |
| --- | --- | --- |
|
```
template< class T >
valarray<T> acos( const valarray<T>& va );
```
| | |
For each element in `va` computes arc cosine of the value of the element.
### Parameters
| | | |
| --- | --- | --- |
| va | - | value array to apply the operation to |
### Return value
Value array containing arc cosines of the values in `va`.
### Notes
Unqualified function (`acos`) is used to perform the computation. If such function is not available, `[std::acos](http://en.cppreference.com/w/cpp/numeric/math/acos)` is used due to [argument-dependent lookup](../../language/adl "cpp/language/adl").
The function can be implemented with the return type different from `[std::valarray](../valarray "cpp/numeric/valarray")`. In this case, the replacement type has the following properties:
* All `const` member functions of `[std::valarray](../valarray "cpp/numeric/valarray")` are provided.
* `[std::valarray](../valarray "cpp/numeric/valarray")`, `[std::slice\_array](slice_array "cpp/numeric/valarray/slice array")`, `[std::gslice\_array](gslice_array "cpp/numeric/valarray/gslice array")`, `[std::mask\_array](mask_array "cpp/numeric/valarray/mask array")` and `[std::indirect\_array](indirect_array "cpp/numeric/valarray/indirect array")` can be constructed from the replacement type.
* All functions accepting an argument of type `const [std::valarray](http://en.cppreference.com/w/cpp/numeric/valarray)&` except [`begin()`](begin2 "cpp/numeric/valarray/begin2") and [`end()`](end2 "cpp/numeric/valarray/end2") (since C++11) should also accept the replacement type.
* All functions accepting two arguments of type `const [std::valarray](http://en.cppreference.com/w/cpp/numeric/valarray)&` should accept every combination of `const [std::valarray](http://en.cppreference.com/w/cpp/numeric/valarray)&` and the replacement type.
* The return type does not add more than two levels of template nesting over the most deeply-nested argument type.
### Possible implementation
| |
| --- |
|
```
template< class T >
valarray<T> acos( const valarray<T>& va )
{
valarray<T> other = va;
for (T &i : other) {
i = acos(i);
}
return other; // proxy object may be returned
}
```
|
### Example
```
#include <cmath>
#include <numbers>
#include <iostream>
#include <valarray>
int main()
{
// take common x-values from unit circle
const double s32 = std::sqrt(3.0) / 2.0;
const double s22 = std::sqrt(2.0) / 2.0;
std::valarray<double> v1 = {-1.0, -s32, -s22, -0.5, 0.0, 0.5, s22, s32, 1.0};
std::valarray<double> v2 = std::acos(v1) * 180.0 / std::numbers::pi;
for(double n : v2)
std::cout << n << "ยฐ ";
std::cout << '\n';
}
```
Output:
```
180ยฐ 150ยฐ 135ยฐ 120ยฐ 90ยฐ 60ยฐ 45ยฐ 30ยฐ 0ยฐ
```
### See also
| | |
| --- | --- |
| [asin(std::valarray)](asin "cpp/numeric/valarray/asin") | applies the function `[std::asin](../math/asin "cpp/numeric/math/asin")` to each element of valarray (function template) |
| [atan(std::valarray)](atan "cpp/numeric/valarray/atan") | applies the function `[std::atan](../math/atan "cpp/numeric/math/atan")` to each element of valarray (function template) |
| [atan2(std::valarray)](atan2 "cpp/numeric/valarray/atan2") | applies the function `[std::atan2](../math/atan2 "cpp/numeric/math/atan2")` to a valarray and a value (function template) |
| [cos(std::valarray)](cos "cpp/numeric/valarray/cos") | applies the function `[std::cos](../math/cos "cpp/numeric/math/cos")` to each element of valarray (function template) |
| [acosacosfacosl](../math/acos "cpp/numeric/math/acos")
(C++11)(C++11) | computes arc cosine (\({\small\arccos{x} }\)arccos(x)) (function) |
| [acos(std::complex)](../complex/acos "cpp/numeric/complex/acos")
(C++11) | computes arc cosine of a complex number (\({\small\arccos{z} }\)arccos(z)) (function template) |
cpp std::end(std::valarray)
std::end(std::valarray)
=======================
| | | |
| --- | --- | --- |
|
```
template< class T >
/*unspecified1*/ end( valarray<T>& v );
```
| (1) | (since C++11) |
|
```
template< class T >
/*unspecified2*/ end( const valarray<T>& v );
```
| (2) | (since C++11) |
The overload of `[std::end](../../iterator/end "cpp/iterator/end")` for `valarray` returns an iterator of unspecified type referring to the one past the last element in the numeric array.
1) The return type meets the requirements of mutable [LegacyRandomAccessIterator](../../named_req/randomaccessiterator "cpp/named req/RandomAccessIterator").
2) The return type meets the requirements of constant [LegacyRandomAccessIterator](../../named_req/randomaccessiterator "cpp/named req/RandomAccessIterator"). The iterator obtained from this function template is invalidated when the member function `resize()` is called on the array `v` or when the lifetime of `v` ends, whichever comes first.
### Parameters
| | | |
| --- | --- | --- |
| v | - | a numeric array |
### Return value
Iterator to one past the last value in the numeric array.
### Exceptions
May throw implementation-defined exceptions.
### Notes
Unlike other functions that take `std::valarray` arguments, `end()` cannot accept the replacement types (such as the types produced by expression templates) that may be returned from expressions involving valarrays: `[std::end](http://en.cppreference.com/w/cpp/iterator/end)(v1 + v2)` is not portable, `[std::end](http://en.cppreference.com/w/cpp/iterator/end)([std::valarray](http://en.cppreference.com/w/cpp/numeric/valarray)<T>(v1 + v2))` has to be used instead.
The intent of this function is to allow [range for loops](../../language/range-for "cpp/language/range-for") to work with valarrays, not to provide container semantics.
### Example
```
#include <iostream>
#include <valarray>
#include <algorithm>
int main()
{
const std::valarray<char> va {
'H', 'e', 'l', 'l', 'o',
',', ' ',
'C', '+', '+', '!', '\n'
};
std::for_each(
std::begin(va),
std::end(va),
[](char c) {
std::cout << c;
});
}
```
Possible output:
```
Hello, C++!
```
### See also
| | |
| --- | --- |
| [std::begin(std::valarray)](begin2 "cpp/numeric/valarray/begin2")
(C++11) | overloads `[std::begin](../../iterator/begin "cpp/iterator/begin")` (function template) |
cpp operator==,!=,<,<=,>,>=(std::valarray) operator==,!=,<,<=,>,>=(std::valarray)
======================================
| Defined in header `[<valarray>](../../header/valarray "cpp/header/valarray")` | | |
| --- | --- | --- |
|
```
template< class T >
std::valarray<bool> operator==( const std::valarray<T>& lhs, const std::valarray<T>& rhs );
template< class T >
std::valarray<bool> operator!=( const std::valarray<T>& lhs, const std::valarray<T>& rhs );
template< class T >
std::valarray<bool> operator< ( const std::valarray<T>& lhs, const std::valarray<T>& rhs );
template< class T >
std::valarray<bool> operator<=( const std::valarray<T>& lhs, const std::valarray<T>& rhs );
template< class T >
std::valarray<bool> operator> ( const std::valarray<T>& lhs, const std::valarray<T>& rhs );
template< class T >
std::valarray<bool> operator>=( const std::valarray<T>& lhs, const std::valarray<T>& rhs );
```
| (1) | |
|
```
template< class T >
std::valarray<bool> operator==( const typename std::valarray<T>::value_type & lhsv,
const std::valarray<T>& rhs );
template< class T >
std::valarray<bool> operator!=( const typename std::valarray<T>::value_type & lhsv,
const std::valarray<T>& rhs );
template< class T >
std::valarray<bool> operator< ( const typename std::valarray<T>::value_type & lhsv,
const std::valarray<T>& rhs );
template< class T >
std::valarray<bool> operator<=( const typename std::valarray<T>::value_type & lhsv,
const std::valarray<T>& rhs );
template< class T >
std::valarray<bool> operator> ( const typename std::valarray<T>::value_type & lhsv,
const std::valarray<T>& rhs );
template< class T >
std::valarray<bool> operator>=( const typename std::valarray<T>::value_type & lhsv,
const std::valarray<T>& rhs );
```
| (2) | |
|
```
template< class T >
std::valarray<bool> operator==( const std::valarray<T>& lhs,
const typename std::valarray<T>::value_type & rhsv );
template< class T >
std::valarray<bool> operator!=( const std::valarray<T>& lhs,
const typename std::valarray<T>::value_type & rhsv );
template< class T >
std::valarray<bool> operator< ( const std::valarray<T>& lhs,
const typename std::valarray<T>::value_type & rhsv );
template< class T >
std::valarray<bool> operator<=( const std::valarray<T>& lhs,
const typename std::valarray<T>::value_type & rhsv );
template< class T >
std::valarray<bool> operator> ( const std::valarray<T>& lhs,
const typename std::valarray<T>::value_type & rhsv );
template< class T >
std::valarray<bool> operator>=( const std::valarray<T>& lhs,
const typename std::valarray<T>::value_type & rhsv );
```
| (3) | |
Compares each value within the numeric array with another value.
1) Returns a numeric array of `bool` containing elements each of which is obtained by applying the indicated comparison operator to the corresponding values of `lhs` and `rhs`
The behavior is undefined if `size() != v.size()`.
2) Returns a numeric array of `bool` containing elements each of which is obtained by applying the indicated comparison operator to `lhsv` and the corresponding value of `rhs` .
3) Returns a numeric array of `bool` containing elements each of which is obtained by applying the indicated comparison operator to the corresponding value of `lhs` and `rhsv`. ### Parameters
| | | |
| --- | --- | --- |
| lhs, rhs | - | numeric arrays to compare |
| lhsv, rhsv | - | values to compare to each element within a numeric array |
### Return value
A numeric array of `bool` containing comparison results of corresponding elements.
### Exceptions
May throw implementation-defined exceptions.
### Notes
Each of the operators can only be instantiated if the following requirements are met:
* The indicated operator can be applied to type `T`
* The result value can be unambiguously converted to `bool`.
The function can be implemented with the return type different from `[std::valarray](../valarray "cpp/numeric/valarray")`. In this case, the replacement type has the following properties:
* All `const` member functions of `[std::valarray](../valarray "cpp/numeric/valarray")` are provided.
* `[std::valarray](../valarray "cpp/numeric/valarray")`, `[std::slice\_array](slice_array "cpp/numeric/valarray/slice array")`, `[std::gslice\_array](gslice_array "cpp/numeric/valarray/gslice array")`, `[std::mask\_array](mask_array "cpp/numeric/valarray/mask array")` and `[std::indirect\_array](indirect_array "cpp/numeric/valarray/indirect array")` can be constructed from the replacement type.
* All functions accepting an argument of type `const [std::valarray](http://en.cppreference.com/w/cpp/numeric/valarray)&` except [`begin()`](begin2 "cpp/numeric/valarray/begin2") and [`end()`](end2 "cpp/numeric/valarray/end2") (since C++11) should also accept the replacement type.
* All functions accepting two arguments of type `const [std::valarray](http://en.cppreference.com/w/cpp/numeric/valarray)&` should accept every combination of `const [std::valarray](http://en.cppreference.com/w/cpp/numeric/valarray)&` and the replacement type.
* The return type does not add more than two levels of template nesting over the most deeply-nested argument type.
### Example
```
#include <iostream>
#include <valarray>
int main()
{
// zero all negatives in a valarray
std::valarray<int> v = {1, -1, 0, -3, 10, -1, -2};
std::cout << "Before: ";
for(auto n: v) {
std::cout << n << ' ';
}
std::cout << '\n';
v[v < 0] = 0;
std::cout << "After: ";
for(auto n: v) {
std::cout << n << ' ';
}
std::cout << '\n';
// convert the valarray<bool> result of == to a single bool
std::valarray<int> a = {1,2,3};
std::valarray<int> b = {2,4,6};
std::cout << "2*a == b is " << std::boolalpha
<< (2*a == b).min() << '\n';
}
```
Output:
```
Before: 1 -1 0 -3 10 -1 -2
After: 1 0 0 0 10 0 0
2*a == b is 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 3074](https://cplusplus.github.io/LWG/issue3074) | C++98 | `T` is deduced from both the scalar and the `valarray` for (2-3), disallowing mixed-type calls | only deduce `T` from the `valarray` |
| programming_docs |
cpp std::begin(std::valarray)
std::begin(std::valarray)
=========================
| | | |
| --- | --- | --- |
|
```
template< class T >
/*unspecified1*/ begin( valarray<T>& v );
```
| (1) | (since C++11) |
|
```
template< class T >
/*unspecified2*/ begin( const valarray<T>& v );
```
| (2) | (since C++11) |
The overload of `[std::begin](../../iterator/begin "cpp/iterator/begin")` for `valarray` returns an iterator of unspecified type referring to the first element in the numeric array.
1) The return type meets the requirements of mutable [LegacyRandomAccessIterator](../../named_req/randomaccessiterator "cpp/named req/RandomAccessIterator").
2) The return type meets the requirements of constant [LegacyRandomAccessIterator](../../named_req/randomaccessiterator "cpp/named req/RandomAccessIterator"). The iterator obtained from this function is invalidated when the member function `resize()` is called on the array `v` or when the lifetime of `v` ends, whichever comes first.
### Parameters
| | | |
| --- | --- | --- |
| v | - | a numeric array |
### Return value
Iterator to the first value in the numeric array.
### Exceptions
May throw implementation-defined exceptions.
### Notes
Unlike other functions that take `std::valarray` arguments, `begin()` cannot accept the replacement types (such as the types produced by expression templates) that may be returned from expressions involving valarrays: `[std::begin](http://en.cppreference.com/w/cpp/iterator/begin)(v1 + v2)` is not portable, `[std::begin](http://en.cppreference.com/w/cpp/iterator/begin)([std::valarray](http://en.cppreference.com/w/cpp/numeric/valarray)<T>(v1 + v2))` has to be used instead.
The intent of this function is to allow [range for loops](../../language/range-for "cpp/language/range-for") to work with valarrays, not to provide container semantics.
### Example
```
#include <iostream>
#include <valarray>
#include <algorithm>
auto show = [](std::valarray<int> const& v) {
std::for_each(std::begin(v), std::end(v), [](int c) {
std::cout << c << ' ';
});
std::cout << '\n';
};
int main()
{
const std::valarray<int> x { 47, 70, 37, 52, 90, 23, 17, 33, 22, 16, 21, 4 };
const std::valarray<int> y { 25, 31, 71, 56, 21, 21, 15, 34, 21, 27, 12, 6 };
show(x);
show(y);
const std::valarray<int> z { x + y };
std::for_each(std::begin(z), std::end(z), [](char c) { std::cout << c; });
}
```
Output:
```
47 70 37 52 90 23 17 33 22 16 21 4
25 31 71 56 21 21 15 34 21 27 12 6
Hello, C++!
```
### See also
| | |
| --- | --- |
| [std::end(std::valarray)](end2 "cpp/numeric/valarray/end2")
(C++11) | specializes `[std::end](../../iterator/end "cpp/iterator/end")` (function template) |
cpp std::sin(std::valarray) std::sin(std::valarray)
=======================
| Defined in header `[<valarray>](../../header/valarray "cpp/header/valarray")` | | |
| --- | --- | --- |
|
```
template< class T >
valarray<T> sin( const valarray<T>& va );
```
| | |
For each element in `va` computes sine of the value of the element.
### Parameters
| | | |
| --- | --- | --- |
| va | - | value array to apply the operation to |
### Return value
Value array containing sine of the values in `va`.
### Notes
Unqualified function (`sin`) is used to perform the computation. If such function is not available, `[std::sin](http://en.cppreference.com/w/cpp/numeric/math/sin)` is used due to [argument-dependent lookup](../../language/adl "cpp/language/adl").
The function can be implemented with the return type different from `[std::valarray](../valarray "cpp/numeric/valarray")`. In this case, the replacement type has the following properties:
* All `const` member functions of `[std::valarray](../valarray "cpp/numeric/valarray")` are provided.
* `[std::valarray](../valarray "cpp/numeric/valarray")`, `[std::slice\_array](slice_array "cpp/numeric/valarray/slice array")`, `[std::gslice\_array](gslice_array "cpp/numeric/valarray/gslice array")`, `[std::mask\_array](mask_array "cpp/numeric/valarray/mask array")` and `[std::indirect\_array](indirect_array "cpp/numeric/valarray/indirect array")` can be constructed from the replacement type.
* All functions accepting an argument of type `const [std::valarray](http://en.cppreference.com/w/cpp/numeric/valarray)&` except [`begin()`](begin2 "cpp/numeric/valarray/begin2") and [`end()`](end2 "cpp/numeric/valarray/end2") (since C++11) should also accept the replacement type.
* All functions accepting two arguments of type `const [std::valarray](http://en.cppreference.com/w/cpp/numeric/valarray)&` should accept every combination of `const [std::valarray](http://en.cppreference.com/w/cpp/numeric/valarray)&` and the replacement type.
* The return type does not add more than two levels of template nesting over the most deeply-nested argument type.
### Possible implementation
| |
| --- |
|
```
template< class T >
valarray<T> sin( const valarray<T>& va )
{
valarray<T> other = va;
for (T &i : other) {
i = sin(i);
}
return other; // proxy object may be returned
}
```
|
### Example
```
#include <valarray>
#include <iostream>
#include <numbers>
#include <cmath>
int main()
{
std::valarray<double> v1 = {0, 0.25, 0.5, 0.75, 1};
std::valarray<double> v2 = std::sin(v1 * std::numbers::pi);
for(double n : v2)
std::cout << std::fixed << n << ' ';
std::cout << '\n';
}
```
Output:
```
0.000000 0.707107 1.000000 0.707107 0.000000
```
### See also
| | |
| --- | --- |
| [cos(std::valarray)](cos "cpp/numeric/valarray/cos") | applies the function `[std::cos](../math/cos "cpp/numeric/math/cos")` to each element of valarray (function template) |
| [tan(std::valarray)](tan "cpp/numeric/valarray/tan") | applies the function `[std::tan](../math/tan "cpp/numeric/math/tan")` to each element of valarray (function template) |
| [asin(std::valarray)](asin "cpp/numeric/valarray/asin") | applies the function `[std::asin](../math/asin "cpp/numeric/math/asin")` to each element of valarray (function template) |
| [sinsinfsinl](../math/sin "cpp/numeric/math/sin")
(C++11)(C++11) | computes sine (\({\small\sin{x} }\)sin(x)) (function) |
| [sin(std::complex)](../complex/sin "cpp/numeric/complex/sin") | computes sine of a complex number (\({\small\sin{z} }\)sin(z)) (function template) |
cpp std::tan(std::valarray) std::tan(std::valarray)
=======================
| Defined in header `[<valarray>](../../header/valarray "cpp/header/valarray")` | | |
| --- | --- | --- |
|
```
template< class T >
valarray<T> tan( const valarray<T>& va );
```
| | |
For each element in `va` computes tangent of the value of the element.
### Parameters
| | | |
| --- | --- | --- |
| va | - | value array to apply the operation to |
### Return value
Value array containing tangents of the values in `va`.
### Notes
Unqualified function (`tan`) is used to perform the computation. If such function is not available, `[std::tan](http://en.cppreference.com/w/cpp/numeric/math/tan)` is used due to [argument-dependent lookup](../../language/adl "cpp/language/adl").
The function can be implemented with the return type different from `[std::valarray](../valarray "cpp/numeric/valarray")`. In this case, the replacement type has the following properties:
* All `const` member functions of `[std::valarray](../valarray "cpp/numeric/valarray")` are provided.
* `[std::valarray](../valarray "cpp/numeric/valarray")`, `[std::slice\_array](slice_array "cpp/numeric/valarray/slice array")`, `[std::gslice\_array](gslice_array "cpp/numeric/valarray/gslice array")`, `[std::mask\_array](mask_array "cpp/numeric/valarray/mask array")` and `[std::indirect\_array](indirect_array "cpp/numeric/valarray/indirect array")` can be constructed from the replacement type.
* All functions accepting an argument of type `const [std::valarray](http://en.cppreference.com/w/cpp/numeric/valarray)&` except [`begin()`](begin2 "cpp/numeric/valarray/begin2") and [`end()`](end2 "cpp/numeric/valarray/end2") (since C++11) should also accept the replacement type.
* All functions accepting two arguments of type `const [std::valarray](http://en.cppreference.com/w/cpp/numeric/valarray)&` should accept every combination of `const [std::valarray](http://en.cppreference.com/w/cpp/numeric/valarray)&` and the replacement type.
* The return type does not add more than two levels of template nesting over the most deeply-nested argument type.
### Possible implementation
| |
| --- |
|
```
template< class T >
valarray<T> tan( const valarray<T>& va )
{
valarray<T> other = va;
for (T &i : other) {
i = tan(i);
}
return other; // proxy object may be returned
}
```
|
### Example
```
#include <cmath>
#include <iostream>
#include <valarray>
auto show = [](char const* title, const std::valarray<double>& va) {
std::cout << title << " :";
for(auto x : va)
std::cout << " " << std::fixed << x;
std::cout << '\n';
};
int main()
{
const std::valarray<double> x = {.0, .1, .2, .3};
const std::valarray<double> y = std::tan(x);
const std::valarray<double> z = std::atan(y);
show("x ", x);
show("y = tan(x) ", y);
show("z = atan(y)", z);
}
```
Output:
```
x : 0.000000 0.100000 0.200000 0.300000
y = tan(x) : 0.000000 0.100335 0.202710 0.309336
z = atan(y) : 0.000000 0.100000 0.200000 0.300000
```
### See also
| | |
| --- | --- |
| [sin(std::valarray)](sin "cpp/numeric/valarray/sin") | applies the function `[std::sin](../math/sin "cpp/numeric/math/sin")` to each element of valarray (function template) |
| [cos(std::valarray)](cos "cpp/numeric/valarray/cos") | applies the function `[std::cos](../math/cos "cpp/numeric/math/cos")` to each element of valarray (function template) |
| [atan(std::valarray)](atan "cpp/numeric/valarray/atan") | applies the function `[std::atan](../math/atan "cpp/numeric/math/atan")` to each element of valarray (function template) |
| [tantanftanl](../math/tan "cpp/numeric/math/tan")
(C++11)(C++11) | computes tangent (\({\small\tan{x} }\)tan(x)) (function) |
| [tan(std::complex)](../complex/tan "cpp/numeric/complex/tan") | computes tangent of a complex number (\({\small\tan{z} }\)tan(z)) (function template) |
cpp std::gslice_array<T>::gslice_array std::gslice\_array<T>::gslice\_array
====================================
| | | |
| --- | --- | --- |
|
```
gslice_array( const gslice_array& other );
```
| | |
|
```
gslice_array() = delete;
```
| | |
Constructs a `gslice_array` from another `gslice_array` `other`.
The default constructor is implicitly deleted.
### Parameters
| | | |
| --- | --- | --- |
| other | - | `gslice_array` to initialize with |
cpp std::gslice_array<T>::operator= std::gslice\_array<T>::operator=
================================
| | | |
| --- | --- | --- |
|
```
void operator=( const T& value ) const;
```
| (1) | |
|
```
void operator=( const std::valarray<T>& val_arr ) const;
```
| (2) | |
|
```
const gslice_array& operator=( const gslice_array& sl_arr) const;
```
| (3) | (since C++11) |
Assigns values to all referred elements.
1) Assigns `value` to all of the elements.
2) Assigns the elements of `val_arr` to the referred to elements of `*this`.
3) Assigns the selected elements from `sl_arr` to the referred to elements of `*this`. ### Parameters
| | | |
| --- | --- | --- |
| value | - | a value to assign to all of the referred elements |
| val\_arr | - | `[std::valarray](http://en.cppreference.com/w/cpp/numeric/valarray)` to assign |
| sl\_arr | - | `[std::gslice\_array](http://en.cppreference.com/w/cpp/numeric/valarray/gslice_array)` to assign |
### Return value
1-2) (none)
3) `*this`
### Exceptions
May throw implementation-defined exceptions.
### Example
cpp std::gslice_array<T>::operator+=,-=,*=,/=,%=,&=,|=,^=,<<=,>>= std::gslice\_array<T>::operator+=,-=,\*=,/=,%=,&=,|=,^=,<<=,>>=
===============================================================
| | | |
| --- | --- | --- |
|
```
void operator+=( const std::valarray<T>& other ) const;
```
| | |
|
```
void operator-=( const std::valarray<T>& other ) const;
```
| | |
|
```
void operator*=( const std::valarray<T>& other ) const;
```
| | |
|
```
void operator/=( const std::valarray<T>& other ) const;
```
| | |
|
```
void operator%=( const std::valarray<T>& other ) const;
```
| | |
|
```
void operator&=( const std::valarray<T>& other ) const;
```
| | |
|
```
void operator|=( const std::valarray<T>& other ) const;
```
| | |
|
```
void operator^=( const std::valarray<T>& other ) const;
```
| | |
|
```
void operator<<=( const std::valarray<T>& other ) const;
```
| | |
|
```
void operator>>=( const std::valarray<T>& other ) const;
```
| | |
Applies the corresponding operation to the referred elements and the elements of `other`.
### Parameters
| | | |
| --- | --- | --- |
| other | - | argument array to retrieve the values from |
### Return value
(none).
### Exceptions
May throw implementation-defined exceptions.
### Example
cpp std::gslice_array<T>::~gslice_array std::gslice\_array<T>::~gslice\_array
=====================================
| | | |
| --- | --- | --- |
|
```
~gslice_array();
```
| | |
Destroys the indexes in the array. The elements referred to by the object are not modified.
cpp std::indirect_array<T>::~indirect_array std::indirect\_array<T>::~indirect\_array
=========================================
| | | |
| --- | --- | --- |
|
```
~indirect_array();
```
| | |
Destroys the indexes in the array. The elements referred to by the object are not modified.
cpp std::indirect_array<T>::indirect_array std::indirect\_array<T>::indirect\_array
========================================
| | | |
| --- | --- | --- |
|
```
indirect_array( const indirect_array& other );
```
| | |
|
```
indirect_array() = delete;
```
| | |
Constructs a `indirect_array` from another `indirect_array` `other`.
The default constructor is implicitly deleted.
### Parameters
| | | |
| --- | --- | --- |
| other | - | `indirect_array` to initialize with |
cpp std::indirect_array<T>::operator= std::indirect\_array<T>::operator=
==================================
| | | |
| --- | --- | --- |
|
```
void operator=( const T& value ) const;
```
| (1) | |
|
```
void operator=( const std::valarray<T>& val_arr ) const;
```
| (2) | |
|
```
const indirect_array& operator=( const indirect_array& sl_arr) const;
```
| (3) | (since C++11) |
Assigns values to all referred elements.
1) Assigns `value` to all of the elements.
2) Assigns the elements of `val_arr` to the referred to elements of `*this`.
3) Assigns the selected elements from `sl_arr` to the referred to elements of `*this`. ### Parameters
| | | |
| --- | --- | --- |
| value | - | a value to assign to all of the referred elements |
| val\_arr | - | `[std::valarray](http://en.cppreference.com/w/cpp/numeric/valarray)` to assign |
| sl\_arr | - | `[std::indirect\_array](http://en.cppreference.com/w/cpp/numeric/valarray/indirect_array)` to assign |
### Return value
1-2) (none)
3) `*this`
### Exceptions
May throw implementation-defined exceptions.
### Example
```
#include <iomanip>
#include <iostream>
#include <valarray>
#include <numeric>
void print(int n, std::valarray<int> const& v)
{
std::cout << n << ':';
for (int e : v) std::cout << std::setw(3) << e;
std::cout << '\n';
}
int main()
{
std::valarray<int> v(8);
std::iota(std::begin(v), std::end(v), 0);
print(1, v);
std::valarray<std::size_t> idx{1, 3, 5, 7};
const std::indirect_array<int> ia = v[idx];
// 'ia' refers to v[1], v[3], v[5], v[7]
ia = -1; // (1), effectively:
// v[1] = v[3] = v[5] = v[7] = -1;
print(2, v);
ia = /*std::valarray<int>*/{-1, -2, -3, -4}; // (2),
// effectively: v[1]=-1, v[3]=-2, v[5]=-3, v[7]=-4;
print(3, v);
std::valarray<std::size_t> idx2{0, 2, 4, 6};
const std::indirect_array<int> ia2 = v[idx2];
// 'ia2' refers to v[0], v[2], v[4], v[6]
ia = ia2; // (3), effectively:
// v[1]=v[0], v[3]=v[2], v[5]=v[4], v[7]=v[6];
print(4, v);
}
```
Output:
```
1: 0 1 2 3 4 5 6 7
2: 0 -1 2 -1 4 -1 6 -1
3: 0 -1 2 -2 4 -3 6 -4
4: 0 0 2 2 4 4 6 6
```
cpp std::indirect_array<T>::operator+=,-=,*=,/=,%=,&=,|=,^=,<<=,>>= std::indirect\_array<T>::operator+=,-=,\*=,/=,%=,&=,|=,^=,<<=,>>=
=================================================================
| | | |
| --- | --- | --- |
|
```
void operator+=( const std::valarray<T>& other ) const;
```
| | |
|
```
void operator-=( const std::valarray<T>& other ) const;
```
| | |
|
```
void operator*=( const std::valarray<T>& other ) const;
```
| | |
|
```
void operator/=( const std::valarray<T>& other ) const;
```
| | |
|
```
void operator%=( const std::valarray<T>& other ) const;
```
| | |
|
```
void operator&=( const std::valarray<T>& other ) const;
```
| | |
|
```
void operator|=( const std::valarray<T>& other ) const;
```
| | |
|
```
void operator^=( const std::valarray<T>& other ) const;
```
| | |
|
```
void operator<<=( const std::valarray<T>& other ) const;
```
| | |
|
```
void operator>>=( const std::valarray<T>& other ) const;
```
| | |
Applies the corresponding operation to the referred elements and the elements of `other`.
### Parameters
| | | |
| --- | --- | --- |
| other | - | argument array to retrieve the values from |
### Return value
(none).
### Exceptions
May throw implementation-defined exceptions.
### Example
cpp std::slice_array<T>::slice_array std::slice\_array<T>::slice\_array
==================================
| | | |
| --- | --- | --- |
|
```
slice_array( const slice_array& other );
```
| | |
|
```
slice_array() = delete;
```
| | |
Constructs a `slice_array` from another `slice_array` `other`.
The default constructor is implicitly deleted.
### Parameters
| | | |
| --- | --- | --- |
| other | - | `slice_array` to initialize with |
cpp std::slice_array<T>::operator= std::slice\_array<T>::operator=
===============================
| | | |
| --- | --- | --- |
|
```
void operator=( const T& value ) const;
```
| (1) | |
|
```
void operator=( const std::valarray<T>& val_arr ) const;
```
| (2) | |
|
```
const slice_array& operator=( const slice_array& sl_arr) const;
```
| (3) | (since C++11) |
Assigns values to all referred elements.
1) Assigns `value` to all of the elements.
2) Assigns the elements of `val_arr` to the referred to elements of `*this`.
3) Assigns the selected elements from `sl_arr` to the referred to elements of `*this`. ### Parameters
| | | |
| --- | --- | --- |
| value | - | a value to assign to all of the referred elements |
| val\_arr | - | `[std::valarray](http://en.cppreference.com/w/cpp/numeric/valarray)` to assign |
| sl\_arr | - | `[std::slice\_array](http://en.cppreference.com/w/cpp/numeric/valarray/slice_array)` to assign |
### Return value
1-2) (none)
3) `*this`
### Exceptions
May throw implementation-defined exceptions.
### Example
```
#include <iostream>
#include <valarray>
void print(char const* remark, std::valarray<int> const& v = {})
{
std::cout << remark;
if (v.size() != 0) {
std::cout << ":";
for (int e : v) std::cout << ' ' << e;
}
std::cout << '\n';
}
int main()
{
std::valarray<int> v1{1,2,3,4,5,6,7,8};
std::slice_array<int> s1 = v1[std::slice(1, 4, 2)];
print("v1", v1);
print("s1", s1);
print("\n(1) operator=( const T& )");
print("s1 = 42");
s1 = 42; // (1)
print("s1", s1);
print("v1", v1);
print("\n(2) operator=( const std::valarray<T>& )");
std::valarray<int> v2{10,11,12,13,14,15};
print("v2", v2);
print("s1 = v2");
s1 = v2; // (2)
print("s1", s1);
print("v1", v1);
print("\n(3) operator=( const slice_array& )");
v1 = {1,2,3,4,5,6,7,8};
std::slice_array<int> s2 = v1[std::slice(0, 4, 1)];
std::slice_array<int> s3 = v2[std::slice(1, 4, 1)];
print("v1", v1);
print("v2", v2);
print("s2", s2);
print("s3", s3);
print("s2 = s3");
s2 = s3; // (3) Note: LHS and RHS must have same size.
print("s2", s2);
print("v1", v1);
}
```
Output:
```
v1: 1 2 3 4 5 6 7 8
s1: 2 4 6 8
(1) operator=( const T& )
s1 = 42
s1: 42 42 42 42
v1: 1 42 3 42 5 42 7 42
(2) operator=( const std::valarray<T>& )
v2: 10 11 12 13 14 15
s1 = v2
s1: 10 11 12 13
v1: 1 10 3 11 5 12 7 13
(3) operator=( const slice_array& )
v1: 1 2 3 4 5 6 7 8
v2: 10 11 12 13 14 15
s2: 1 2 3 4
s3: 11 12 13 14
s2 = s3
s2: 11 12 13 14
v1: 11 12 13 14 5 6 7 8
```
| programming_docs |
cpp std::slice_array<T>::operator+=,-=,*=,/=,%=,&=,|=,^=,<<=,>>= std::slice\_array<T>::operator+=,-=,\*=,/=,%=,&=,|=,^=,<<=,>>=
==============================================================
| | | |
| --- | --- | --- |
|
```
void operator+=( const std::valarray<T>& other ) const;
```
| | |
|
```
void operator-=( const std::valarray<T>& other ) const;
```
| | |
|
```
void operator*=( const std::valarray<T>& other ) const;
```
| | |
|
```
void operator/=( const std::valarray<T>& other ) const;
```
| | |
|
```
void operator%=( const std::valarray<T>& other ) const;
```
| | |
|
```
void operator&=( const std::valarray<T>& other ) const;
```
| | |
|
```
void operator|=( const std::valarray<T>& other ) const;
```
| | |
|
```
void operator^=( const std::valarray<T>& other ) const;
```
| | |
|
```
void operator<<=( const std::valarray<T>& other ) const;
```
| | |
|
```
void operator>>=( const std::valarray<T>& other ) const;
```
| | |
Applies the corresponding operation to the referred elements and the elements of `other`.
### Parameters
| | | |
| --- | --- | --- |
| other | - | argument array to retrieve the values from |
### Return value
(none).
### Exceptions
May throw implementation-defined exceptions.
### Example
cpp std::slice_array<T>::~slice_array std::slice\_array<T>::~slice\_array
===================================
| | | |
| --- | --- | --- |
|
```
~slice_array();
```
| | |
Destroys the indexes in the array. The elements referred to by the object are not modified.
cpp std::mask_array<T>::mask_array std::mask\_array<T>::mask\_array
================================
| | | |
| --- | --- | --- |
|
```
mask_array( const mask_array& other );
```
| | |
|
```
mask_array() = delete;
```
| | |
Constructs a `mask_array` from another `mask_array` `other`.
The default constructor is implicitly deleted.
### Parameters
| | | |
| --- | --- | --- |
| other | - | `mask_array` to initialize with |
cpp std::mask_array<T>::~mask_array std::mask\_array<T>::~mask\_array
=================================
| | | |
| --- | --- | --- |
|
```
~mask_array();
```
| | |
Destroys the indexes in the array. The elements referred to by the object are not modified.
cpp std::mask_array<T>::operator= std::mask\_array<T>::operator=
==============================
| | | |
| --- | --- | --- |
|
```
void operator=( const T& value ) const;
```
| (1) | |
|
```
void operator=( const std::valarray<T>& val_arr ) const;
```
| (2) | |
|
```
const mask_array& operator=( const mask_array& sl_arr) const;
```
| (3) | (since C++11) |
Assigns values to all referred elements.
1) Assigns `value` to all of the elements.
2) Assigns the elements of `val_arr` to the referred to elements of `*this`.
3) Assigns the selected elements from `sl_arr` to the referred to elements of `*this`. ### Parameters
| | | |
| --- | --- | --- |
| value | - | a value to assign to all of the referred elements |
| val\_arr | - | `[std::valarray](http://en.cppreference.com/w/cpp/numeric/valarray)` to assign |
| sl\_arr | - | `[std::mask\_array](http://en.cppreference.com/w/cpp/numeric/valarray/mask_array)` to assign |
### Return value
1-2) (none)
3) `*this`
### Exceptions
May throw implementation-defined exceptions.
### Example
```
#include <iomanip>
#include <iostream>
#include <valarray>
void print(std::valarray<int> const& v)
{
for (int e : v) std::cout << std::setw(2) << e << ' ';
std::cout << '\n';
}
int main()
{
const auto init = {1, 2, 3, 4, 5, 6, 7, 8};
std::valarray<int> v;
v = init;
v[(v % 2) == 0] = 0; // (1)
print(v);
v = init;
v[(v % 2) == 1] = std::valarray<int>{-1, -2, -3, -4}; // (2)
print(v);
v = init;
v[(v % 2) == 0] = v[(v % 2) == 1]; // (3)
print(v);
}
```
Output:
```
1 0 3 0 5 0 7 0
-1 2 -2 4 -3 6 -4 8
1 1 3 3 5 5 7 7
```
cpp std::mask_array<T>::operator+=,-=,*=,/=,%=,&=,|=,^=,<<=,>>= std::mask\_array<T>::operator+=,-=,\*=,/=,%=,&=,|=,^=,<<=,>>=
=============================================================
| | | |
| --- | --- | --- |
|
```
void operator+=( const std::valarray<T>& other ) const;
```
| | |
|
```
void operator-=( const std::valarray<T>& other ) const;
```
| | |
|
```
void operator*=( const std::valarray<T>& other ) const;
```
| | |
|
```
void operator/=( const std::valarray<T>& other ) const;
```
| | |
|
```
void operator%=( const std::valarray<T>& other ) const;
```
| | |
|
```
void operator&=( const std::valarray<T>& other ) const;
```
| | |
|
```
void operator|=( const std::valarray<T>& other ) const;
```
| | |
|
```
void operator^=( const std::valarray<T>& other ) const;
```
| | |
|
```
void operator<<=( const std::valarray<T>& other ) const;
```
| | |
|
```
void operator>>=( const std::valarray<T>& other ) const;
```
| | |
Applies the corresponding operation to the referred elements and the elements of `other`.
### Parameters
| | | |
| --- | --- | --- |
| other | - | argument array to retrieve the values from |
### Return value
(none).
### Exceptions
May throw implementation-defined exceptions.
### Example
cpp operator<<,>>(std::complex)
operator<<,>>(std::complex)
===========================
| Defined in header `[<complex>](../../header/complex "cpp/header/complex")` | | |
| --- | --- | --- |
|
```
template< class T, class CharT, class Traits >
std::basic_ostream<CharT, Traits>&
operator<<( std::basic_ostream<CharT, Traits>& os,
const std::complex<T>& x );
```
| (1) | |
|
```
template< class T, class CharT, class Traits >
std::basic_istream<CharT, Traits>&
operator>>( std::basic_istream<CharT, Traits>& is,
std::complex<T>& x );
```
| (2) | |
1) Writes to `os` the complex number in the form `(real,imaginary)`. 2) Reads a complex number from `is`. The supported formats are * `real`
* `(real)`
* `(real,imaginary)`
Where the input for `real` and `imaginary` must be convertible to `T`. If an error occurs calls `is.setstate(ios_base::failbit)`.
### Exceptions
May throw `[std::ios\_base::failure](../../io/ios_base/failure "cpp/io/ios base/failure")` on stream errors.
### Parameters
| | | |
| --- | --- | --- |
| os | - | a character output stream |
| is | - | a character input stream |
| x | - | the complex number to be inserted or extracted |
### Return value
1) `os`
2) `is`
### Notes
1) As the comma may be used in the current locale as decimal separator, the output may be ambiguous. This can be solved with `[std::showpoint](../../io/manip/showpoint "cpp/io/manip/showpoint")` which forces the decimal separator to be visible.
2) The input is performed as a series of simple formatted extractions. Whitespace skipping is the same for each of them. ### Possible implementation
| |
| --- |
|
```
template<class T, class charT, class traits>
basic_ostream<charT, traits>&
operator<<(basic_ostream<charT, traits>& o, const complex<T>& x) {
basic_ostringstream<charT, traits> s;
s.flags(o.flags());
s.imbue(o.getloc());
s.precision(o.precision());
s << '(' << x.real() << "," << x.imag() << ')';
return o << s.str();
}
```
|
### Example
```
#include <iostream>
#include <complex>
int main()
{
std::cout << std::complex<double>{3.14, 2.71} << '\n';
}
```
Possible output:
```
(3.14,2.71)
```
cpp std::imag(std::complex) std::imag(std::complex)
=======================
| Defined in header `[<complex>](../../header/complex "cpp/header/complex")` | | |
| --- | --- | --- |
| | (1) | |
|
```
template< class T >
T imag( const std::complex<T>& z );
```
| (until C++14) |
|
```
template< class T >
constexpr T imag( const std::complex<T>& z );
```
| (since C++14) |
| | (2) | |
|
```
float imag( float z );
template< class DoubleOrInteger >
double imag( DoubleOrInteger z );
long double imag( long double z );
```
| (since C++11) (until C++14) |
|
```
constexpr float imag( float z );
template< class DoubleOrInteger >
constexpr double imag( DoubleOrInteger z );
constexpr long double imag( long double z );
```
| (since C++14) |
1) Returns the imaginary component of the complex number `z`, i.e. `z.imag()`.
| | |
| --- | --- |
| 2) Additional overloads are provided for `float`, `double`, `long double`, and all integer types, which are treated as complex numbers with zero imaginary component. | (since C++11) |
### Parameters
| | | |
| --- | --- | --- |
| z | - | complex value |
### Return value
The imaginary component of `z`.
### See also
| | |
| --- | --- |
| [imag](imag "cpp/numeric/complex/imag") | accesses the imaginary part of the complex number (public member function) |
| [real](real2 "cpp/numeric/complex/real2") | returns the real component (function template) |
| [C documentation](https://en.cppreference.com/w/c/numeric/complex/cimag "c/numeric/complex/cimag") for `cimag` |
cpp std::complex<T>::operator+(unary), operator-(unary)
std::complex<T>::operator+(unary), operator-(unary)
===================================================
| | | |
| --- | --- | --- |
| | (1) | |
|
```
template< class T >
std::complex<T> operator+( const std::complex<T>& val );
```
| (until C++20) |
|
```
template< class T >
constexpr std::complex<T> operator+( const std::complex<T>& val );
```
| (since C++20) |
| | (2) | |
|
```
template< class T >
std::complex<T> operator-( const std::complex<T>& val );
```
| (until C++20) |
|
```
template< class T >
constexpr std::complex<T> operator-( const std::complex<T>& val );
```
| (since C++20) |
Implements the analogs of the unary arithmetic operators for complex numbers.
1) Returns the value of its argument
2) Negates the argument ### Parameters
| | | |
| --- | --- | --- |
| val | - | the complex number argument |
### Return value
1) a copy of the argument, `[std::complex](http://en.cppreference.com/w/cpp/numeric/complex)<T>(val)`
2) negated argument, `[std::complex](http://en.cppreference.com/w/cpp/numeric/complex)<T>(-val.real(), -val.imag())`
### See also
| | |
| --- | --- |
| [operator+operator-operator\*operator/](operator_arith3 "cpp/numeric/complex/operator arith3") | performs complex number arithmetics on two complex values or a complex and a scalar (function template) |
cpp std::complex<T>::imag std::complex<T>::imag
=====================
| | | |
| --- | --- | --- |
| primary template complex<T> | | |
| | (1) | |
|
```
T imag() const;
```
| (until C++14) |
|
```
constexpr T imag() const;
```
| (since C++14) |
| | (2) | |
|
```
void imag( T value );
```
| (until C++20) |
|
```
constexpr void imag( T value );
```
| (since C++20) |
| specialization complex<float> | | |
| | (1) | |
|
```
float imag() const;
```
| (until C++11) |
|
```
constexpr float imag() const;
```
| (since C++11) |
| | (2) | |
|
```
void imag( float value );
```
| (until C++20) |
|
```
constexpr void imag( float value );
```
| (since C++20) |
| specialization complex<double> | | |
| | (1) | |
|
```
double imag() const;
```
| (until C++11) |
|
```
constexpr double imag() const;
```
| (since C++11) |
| | (2) | |
|
```
void imag( double value );
```
| (until C++20) |
|
```
constexpr void imag( double value );
```
| (since C++20) |
| specialization complex<long double> | | |
| | (1) | |
|
```
long double imag() const;
```
| (until C++11) |
|
```
constexpr long double imag() const;
```
| (since C++11) |
| | (2) | |
|
```
void imag( long double value );
```
| (until C++20) |
|
```
constexpr void imag( long double value );
```
| (since C++20) |
Accesses the imaginary part of the complex number.
1) Returns the imaginary part.
2) Sets the imaginary part to `value`. ### Parameters
| | | |
| --- | --- | --- |
| value | - | the value to set the imaginary part to |
### Return value
1) The imaginary part of `*this`.
2) (none) ### Notes
In C++11, overload (1) in `complex` specializations used to be specified without `const` qualifier. However, in C++11, a [`constexpr`](../../language/constexpr "cpp/language/constexpr") specifier used in a non-static member function implies `const`, and thus the behavior is as if `const` is specified.
### See also
| | |
| --- | --- |
| [imag](imag2 "cpp/numeric/complex/imag2") | returns the imaginary component (function template) |
| [real](real "cpp/numeric/complex/real") | accesses the real part of the complex number (public member function) |
cpp std::atan(std::complex) std::atan(std::complex)
=======================
| Defined in header `[<complex>](../../header/complex "cpp/header/complex")` | | |
| --- | --- | --- |
|
```
template< class T >
complex<T> atan( const complex<T>& z );
```
| | (since C++11) |
Computes complex arc tangent of a complex value `z`. Branch cut exists outside the interval [โi ; +i] along the imaginary axis.
### Parameters
| | | |
| --- | --- | --- |
| z | - | complex value |
### Return value
If no errors occur, complex arc tangent of `z` is returned, in the range of a strip unbounded along the imaginary axis and in the interval [โฯ/2; +ฯ/2] along the real axis.
Errors and special cases are handled as if the operation is implemented by `-i * [std::atanh](atanh "cpp/numeric/complex/atanh")(i*z)`, where `i` is the imaginary unit.
### Notes
Inverse tangent (or arc tangent) is a multivalued function and requires a branch cut on the complex plane. The branch cut is conventionally placed at the line segments (-โi,-i) and (+i,+โi) of the imaginary axis. The mathematical definition of the principal value of inverse tangent is atan z = -
1/2 i [ln(1 - iz) - ln (1 + iz)] ### Example
```
#include <iostream>
#include <complex>
#include <cmath>
int main()
{
std::cout << std::fixed;
std::complex<double> z1(0, 2);
std::cout << "atan" << z1 << " = " << std::atan(z1) << '\n';
std::complex<double> z2(-0.0, 2);
std::cout << "atan" << z2 << " (the other side of the cut) = "
<< std::atan(z2) << '\n';
std::complex<double> z3(0, INFINITY);
std::cout << "2*atan" << z3 << " = " << 2.0*std::atan(z3) << '\n';
}
```
Output:
```
atan(0.000000,2.000000) = (1.570796,0.549306)
atan(-0.000000,2.000000) (the other side of the cut) = (-1.570796,0.549306)
2*atan(0.000000,inf) = (3.141593,0.000000)
```
### See also
| | |
| --- | --- |
| [asin(std::complex)](asin "cpp/numeric/complex/asin")
(C++11) | computes arc sine of a complex number (\({\small\arcsin{z} }\)arcsin(z)) (function template) |
| [acos(std::complex)](acos "cpp/numeric/complex/acos")
(C++11) | computes arc cosine of a complex number (\({\small\arccos{z} }\)arccos(z)) (function template) |
| [tan(std::complex)](tan "cpp/numeric/complex/tan") | computes tangent of a complex number (\({\small\tan{z} }\)tan(z)) (function template) |
| [atanatanfatanl](../math/atan "cpp/numeric/math/atan")
(C++11)(C++11) | computes arc tangent (\({\small\arctan{x} }\)arctan(x)) (function) |
| [atan(std::valarray)](../valarray/atan "cpp/numeric/valarray/atan") | applies the function `[std::atan](../math/atan "cpp/numeric/math/atan")` to each element of valarray (function template) |
| [C documentation](https://en.cppreference.com/w/c/numeric/complex/catan "c/numeric/complex/catan") for `catan` |
cpp std::arg(std::complex) std::arg(std::complex)
======================
| Defined in header `[<complex>](../../header/complex "cpp/header/complex")` | | |
| --- | --- | --- |
|
```
template< class T >
T arg( const complex<T>& z );
```
| (1) | |
|
```
long double arg( long double z );
```
| (2) | (since C++11) |
|
```
template< class DoubleOrInteger >
double arg( DoubleOrInteger z );
```
| (3) | (since C++11) |
|
```
float arg( float z );
```
| (4) | (since C++11) |
Calculates the phase angle (in radians) of the complex number `z`.
| | |
| --- | --- |
| Additional overloads are provided for `float`, `double`, `long double`, and all integer types, which are treated as complex numbers with zero imaginary component. | (since C++11) |
### Parameters
| | | |
| --- | --- | --- |
| z | - | complex value |
### Return value
If no errors occur, returns the phase angle of `z` in the interval [โฯ; ฯ].
Errors and special cases are handled as if the function is implemented as `[std::atan2](http://en.cppreference.com/w/cpp/numeric/math/atan2)([std::imag](http://en.cppreference.com/w/cpp/numeric/complex/imag2)(z), [std::real](http://en.cppreference.com/w/cpp/numeric/complex/real2)(z))`.
### Example
```
#include <iostream>
#include <complex>
int main()
{
std::complex<double> z1(1, 0);
std::cout << "phase angle of " << z1 << " is " << std::arg(z1) << '\n';
std::complex<double> z2(0, 1);
std::cout << "phase angle of " << z2 << " is " << std::arg(z2) << '\n';
std::complex<double> z3(-1, 0);
std::cout << "phase angle of " << z3 << " is " << std::arg(z3) << '\n';
std::complex<double> z4(-1, -0.0);
std::cout << "phase angle of " << z4 << " (the other side of the cut) is "
<< std::arg(z4) << '\n';
}
```
Output:
```
phase angle of (1,0) is 0
phase angle of (0,1) is 1.5708
phase angle of (-1,0) is 3.14159
phase angle of (-1,-0) (the other side of the cut) is -3.14159
```
### See also
| | |
| --- | --- |
| [abs(std::complex)](abs "cpp/numeric/complex/abs") | returns the magnitude of a complex number (function template) |
| [polar](polar "cpp/numeric/complex/polar") | constructs a complex number from magnitude and phase angle (function template) |
| [atan2atan2fatan2l](../math/atan2 "cpp/numeric/math/atan2")
(C++11)(C++11) | arc tangent, using signs to determine quadrants (function) |
| [atan2(std::valarray)](../valarray/atan2 "cpp/numeric/valarray/atan2") | applies the function `[std::atan2](../math/atan2 "cpp/numeric/math/atan2")` to a valarray and a value (function template) |
| [C documentation](https://en.cppreference.com/w/c/numeric/complex/carg "c/numeric/complex/carg") for `carg` |
cpp std::asin(std::complex) std::asin(std::complex)
=======================
| Defined in header `[<complex>](../../header/complex "cpp/header/complex")` | | |
| --- | --- | --- |
|
```
template< class T >
complex<T> asin( const complex<T>& z );
```
| | (since C++11) |
Computes complex arc sine of a complex value `z`. Branch cut exists outside the interval [โ1 ; +1] along the real axis.
### Parameters
| | | |
| --- | --- | --- |
| z | - | complex value |
### Return value
If no errors occur, complex arc sine of `z` is returned, in the range of a strip unbounded along the imaginary axis and in the interval [โฯ/2; +ฯ/2] along the real axis.
Errors and special cases are handled as if the operation is implemented by `-i * [std::asinh](asinh "cpp/numeric/complex/asinh")(i*z)`, where `i` is the imaginary unit.
### Notes
Inverse sine (or arc sine) is a multivalued function and requires a branch cut on the complex plane. The branch cut is conventionally placed at the line segments (-โ,-1) and (1,โ) of the real axis.
The mathematical definition of the principal value of arc sine is asin z = -*i*ln(*i*z + โ1-z2
) For any z, asin(z) = acos(-z) -
ฯ/2 ### Example
```
#include <iostream>
#include <cmath>
#include <complex>
int main()
{
std::cout << std::fixed;
std::complex<double> z1(-2, 0);
std::cout << "acos" << z1 << " = " << std::acos(z1) << '\n';
std::complex<double> z2(-2, -0.0);
std::cout << "acos" << z2 << " (the other side of the cut) = "
<< std::acos(z2) << '\n';
// for any z, acos(z) = pi - acos(-z)
const double pi = std::acos(-1);
std::complex<double> z3 = pi - std::acos(z2);
std::cout << "cos(pi - acos" << z2 << ") = " << std::cos(z3) << '\n';
}
```
Output:
```
asin(-2.000000,0.000000) = (-1.570796,1.316958)
asin(-2.000000,-0.000000) (the other side of the cut) = (-1.570796,-1.316958)
sin(acos(-2.000000,-0.000000) - pi/2) = (-2.000000,-0.000000)
```
### See also
| | |
| --- | --- |
| [acos(std::complex)](acos "cpp/numeric/complex/acos")
(C++11) | computes arc cosine of a complex number (\({\small\arccos{z} }\)arccos(z)) (function template) |
| [atan(std::complex)](atan "cpp/numeric/complex/atan")
(C++11) | computes arc tangent of a complex number (\({\small\arctan{z} }\)arctan(z)) (function template) |
| [sin(std::complex)](sin "cpp/numeric/complex/sin") | computes sine of a complex number (\({\small\sin{z} }\)sin(z)) (function template) |
| [asinasinfasinl](../math/asin "cpp/numeric/math/asin")
(C++11)(C++11) | computes arc sine (\({\small\arcsin{x} }\)arcsin(x)) (function) |
| [asin(std::valarray)](../valarray/asin "cpp/numeric/valarray/asin") | applies the function `[std::asin](../math/asin "cpp/numeric/math/asin")` to each element of valarray (function template) |
| [C documentation](https://en.cppreference.com/w/c/numeric/complex/casin "c/numeric/complex/casin") for `casin` |
| programming_docs |
cpp std::cosh(std::complex) std::cosh(std::complex)
=======================
| Defined in header `[<complex>](../../header/complex "cpp/header/complex")` | | |
| --- | --- | --- |
|
```
template< class T >
complex<T> cosh( const complex<T>& z );
```
| | (since C++11) |
Computes complex hyperbolic cosine of a complex value `z`.
### Parameters
| | | |
| --- | --- | --- |
| z | - | complex value |
### Return value
If no errors occur, complex hyperbolic cosine of `z` is returned.
### Error handling and special values
Errors are reported consistent with `[math\_errhandling](../math/math_errhandling "cpp/numeric/math/math errhandling")`.
If the implementation supports IEEE floating-point arithmetic,
* `[std::cosh](http://en.cppreference.com/w/cpp/numeric/math/cosh)([std::conj](http://en.cppreference.com/w/cpp/numeric/complex/conj)(z)) == [std::conj](http://en.cppreference.com/w/cpp/numeric/complex/conj)([std::cosh](http://en.cppreference.com/w/cpp/numeric/math/cosh)(z))`
* `[std::cosh](http://en.cppreference.com/w/cpp/numeric/math/cosh)(z) == [std::cosh](http://en.cppreference.com/w/cpp/numeric/math/cosh)(-z)`
* If `z` is `(+0,+0)`, the result is `(1,+0)`
* If `z` is `(+0,+โ)`, the result is `(NaN,ยฑ0)` (the sign of the imaginary part is unspecified) and `[FE\_INVALID](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` is raised
* If `z` is `(+0,NaN)`, the result is `(NaN,ยฑ0)` (the sign of the imaginary part is unspecified)
* If `z` is `(x,+โ)` (for any finite non-zero x), the result is `(NaN,NaN)` and `[FE\_INVALID](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` is raised
* If `z` is `(x,NaN)` (for any finite non-zero x), the result is `(NaN,NaN)` and `[FE\_INVALID](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` may be raised
* If `z` is `(+โ,+0)`, the result is `(+โ,+0)`
* If `z` is `(+โ,y)` (for any finite non-zero y), the result is `+โcis(y)`
* If `z` is `(+โ,+โ)`, the result is `(ยฑโ,NaN)` (the sign of the real part is unspecified) and `[FE\_INVALID](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` is raised
* If `z` is `(+โ,NaN)`, the result is `(+โ,NaN)`
* If `z` is `(NaN,+0)`, the result is `(NaN,ยฑ0)` (the sign of the imaginary part is unspecified)
* If `z` is `(NaN,+y)` (for any finite non-zero y), the result is `(NaN,NaN)` and `[FE\_INVALID](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` may be raised
* If `z` is `(NaN,NaN)`, the result is `(NaN,NaN)`
where cis(y) is cos(y) + i sin(y).
### Notes
Mathematical definition of hyperbolic cosine is cosh z = ez+e-z/2 Hyperbolic cosine is an entire function in the complex plane and has no branch cuts. It is periodic with respect to the imaginary component, with period 2ฯi.
### Examples
```
#include <iostream>
#include <cmath>
#include <complex>
int main()
{
std::cout << std::fixed;
std::complex<double> z(1, 0); // behaves like real cosh along the real line
std::cout << "cosh" << z << " = " << std::cosh(z)
<< " (cosh(1) = " << std::cosh(1) << ")\n";
std::complex<double> z2(0, 1); // behaves like real cosine along the imaginary line
std::cout << "cosh" << z2 << " = " << std::cosh(z2)
<< " ( cos(1) = " << std::cos(1) << ")\n";
}
```
Output:
```
cosh(1.000000,0.000000) = (1.543081,0.000000) (cosh(1) = 1.543081)
cosh(0.000000,1.000000) = (0.540302,0.000000) ( cos(1) = 0.540302)
```
### See also
| | |
| --- | --- |
| [sinh(std::complex)](sinh "cpp/numeric/complex/sinh") | computes hyperbolic sine of a complex number (\({\small\sinh{z} }\)sinh(z)) (function template) |
| [tanh(std::complex)](tanh "cpp/numeric/complex/tanh") | computes hyperbolic tangent of a complex number (\({\small\tanh{z} }\)tanh(z)) (function template) |
| [acosh(std::complex)](acosh "cpp/numeric/complex/acosh")
(C++11) | computes area hyperbolic cosine of a complex number (\({\small\operatorname{arcosh}{z} }\)arcosh(z)) (function template) |
| [coshcoshfcoshl](../math/cosh "cpp/numeric/math/cosh")
(C++11)(C++11) | computes hyperbolic cosine (\({\small\cosh{x} }\)cosh(x)) (function) |
| [cosh(std::valarray)](../valarray/cosh "cpp/numeric/valarray/cosh") | applies the function `[std::cosh](../math/cosh "cpp/numeric/math/cosh")` to each element of valarray (function template) |
| [C documentation](https://en.cppreference.com/w/c/numeric/complex/ccosh "c/numeric/complex/ccosh") for `ccosh` |
cpp std::asinh(std::complex) std::asinh(std::complex)
========================
| Defined in header `[<complex>](../../header/complex "cpp/header/complex")` | | |
| --- | --- | --- |
|
```
template< class T >
complex<T> asinh( const complex<T>& z );
```
| | (since C++11) |
Computes complex arc hyperbolic sine of a complex value `z` with branch cuts outside the interval [โi; +i] along the imaginary axis.
### Parameters
| | | |
| --- | --- | --- |
| z | - | complex value |
### Return value
If no errors occur, the complex arc hyperbolic sine of `z` is returned, in the range of a strip mathematically unbounded along the real axis and in the interval [โiฯ/2; +iฯ/2] along the imaginary axis.
### Error handling and special values
Errors are reported consistent with `[math\_errhandling](../math/math_errhandling "cpp/numeric/math/math errhandling")`.
If the implementation supports IEEE floating-point arithmetic,
* `[std::asinh](http://en.cppreference.com/w/cpp/numeric/math/asinh)([std::conj](http://en.cppreference.com/w/cpp/numeric/complex/conj)(z)) == [std::conj](http://en.cppreference.com/w/cpp/numeric/complex/conj)([std::asinh](http://en.cppreference.com/w/cpp/numeric/math/asinh)(z))`
* `[std::asinh](http://en.cppreference.com/w/cpp/numeric/math/asinh)(-z) == -[std::asinh](http://en.cppreference.com/w/cpp/numeric/math/asinh)(z)`
* If `z` is `(+0,+0)`, the result is `(+0,+0)`
* If `z` is `(x,+โ)` (for any positive finite x), the result is `(+โ,ฯ/2)`
* If `z` is `(x,NaN)` (for any finite x), the result is `(NaN,NaN)` and `[FE\_INVALID](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` may be raised
* If `z` is `(+โ,y)` (for any positive finite y), the result is `(+โ,+0)`
* If `z` is `(+โ,+โ)`, the result is `(+โ,ฯ/4)`
* If `z` is `(+โ,NaN)`, the result is `(+โ,NaN)`
* If `z` is `(NaN,+0)`, the result is `(NaN,+0)`
* If `z` is `(NaN,y)` (for any finite nonzero y), the result is `(NaN,NaN)` and `[FE\_INVALID](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` may be raised
* If `z` is `(NaN,+โ)`, the result is `(ยฑโ,NaN)` (the sign of the real part is unspecified)
* If `z` is `(NaN,NaN)`, the result is `(NaN,NaN)`
### Notes
Although the C++ standard names this function "complex arc hyperbolic sine", the inverse functions of the hyperbolic functions are the area functions. Their argument is the area of a hyperbolic sector, not an arc. The correct name is "complex inverse hyperbolic sine", and, less common, "complex area hyperbolic sine".
Inverse hyperbolic sine is a multivalued function and requires a branch cut on the complex plane. The branch cut is conventionally placed at the line segments (-*i*โ,-*i*) and (*i*,*i*โ) of the imaginary axis.
The mathematical definition of the principal value of the inverse hyperbolic sine is asinh z = ln(z + โ1+z2
) For any z, asinh(z) =
asin(iz)/i ### Example
```
#include <iostream>
#include <complex>
int main()
{
std::cout << std::fixed;
std::complex<double> z1(0, -2);
std::cout << "asinh" << z1 << " = " << std::asinh(z1) << '\n';
std::complex<double> z2(-0.0, -2);
std::cout << "asinh" << z2 << " (the other side of the cut) = "
<< std::asinh(z2) << '\n';
// for any z, asinh(z) = asin(iz)/i
std::complex<double> z3(1,2);
std::complex<double> i(0,1);
std::cout << "asinh" << z3 << " = " << std::asinh(z3) << '\n'
<< "asin" << z3*i << "/i = " << std::asin(z3*i)/i << '\n';
}
```
Output:
```
asinh(0.000000,-2.000000) = (1.316958,-1.570796)
asinh(-0.000000,-2.000000) (the other side of the cut) = (-1.316958,-1.570796)
asinh(1.000000,2.000000) = (1.469352,1.063440)
asin(-2.000000,1.000000)/i = (1.469352,1.063440)
```
### See also
| | |
| --- | --- |
| [acosh(std::complex)](acosh "cpp/numeric/complex/acosh")
(C++11) | computes area hyperbolic cosine of a complex number (\({\small\operatorname{arcosh}{z} }\)arcosh(z)) (function template) |
| [atanh(std::complex)](atanh "cpp/numeric/complex/atanh")
(C++11) | computes area hyperbolic tangent of a complex number (\({\small\operatorname{artanh}{z} }\)artanh(z)) (function template) |
| [sinh(std::complex)](sinh "cpp/numeric/complex/sinh") | computes hyperbolic sine of a complex number (\({\small\sinh{z} }\)sinh(z)) (function template) |
| [asinhasinhfasinhl](../math/asinh "cpp/numeric/math/asinh")
(C++11)(C++11)(C++11) | computes the inverse hyperbolic sine (\({\small\operatorname{arsinh}{x} }\)arsinh(x)) (function) |
| [C documentation](https://en.cppreference.com/w/c/numeric/complex/casinh "c/numeric/complex/casinh") for `casinh` |
cpp std::cos(std::complex) std::cos(std::complex)
======================
| Defined in header `[<complex>](../../header/complex "cpp/header/complex")` | | |
| --- | --- | --- |
|
```
template< class T >
complex<T> cos( const complex<T>& z );
```
| | |
Computes complex cosine of a complex value `z`.
### Parameters
| | | |
| --- | --- | --- |
| z | - | complex value |
### Return value
If no errors occur, the complex cosine of `z` is returned.
Errors and special cases are handled as if the operation is implemented by `[std::cosh](cosh "cpp/numeric/complex/cosh")(i*z)`, where `i` is the imaginary unit.
### Notes
The cosine is an entire function on the complex plane, and has no branch cuts. Mathematical definition of the cosine is cos z =
eiz+e-iz/2 ### Example
```
#include <iostream>
#include <cmath>
#include <complex>
int main()
{
std::cout << std::fixed;
std::complex<double> z(1, 0); // behaves like real cosine along the real line
std::cout << "cos" << z << " = " << std::cos(z)
<< " ( cos(1) = " << std::cos(1) << ")\n";
std::complex<double> z2(0, 1); // behaves like real cosh along the imaginary line
std::cout << "cos" << z2 << " = " << std::cos(z2)
<< " (cosh(1) = " << std::cosh(1) << ")\n";
}
```
Output:
```
cos(1.000000,0.000000) = (0.540302,-0.000000) ( cos(1) = 0.540302)
cos(0.000000,1.000000) = (1.543081,-0.000000) (cosh(1) = 1.543081)
```
### See also
| | |
| --- | --- |
| [sin(std::complex)](sin "cpp/numeric/complex/sin") | computes sine of a complex number (\({\small\sin{z} }\)sin(z)) (function template) |
| [tan(std::complex)](tan "cpp/numeric/complex/tan") | computes tangent of a complex number (\({\small\tan{z} }\)tan(z)) (function template) |
| [acos(std::complex)](acos "cpp/numeric/complex/acos")
(C++11) | computes arc cosine of a complex number (\({\small\arccos{z} }\)arccos(z)) (function template) |
| [coscosfcosl](../math/cos "cpp/numeric/math/cos")
(C++11)(C++11) | computes cosine (\({\small\cos{x} }\)cos(x)) (function) |
| [cos(std::valarray)](../valarray/cos "cpp/numeric/valarray/cos") | applies the function `[std::cos](../math/cos "cpp/numeric/math/cos")` to each element of valarray (function template) |
| [C documentation](https://en.cppreference.com/w/c/numeric/complex/ccos "c/numeric/complex/ccos") for `ccos` |
cpp operator+,-,*,/ (std::complex) operator+,-,\*,/ (std::complex)
===============================
| | | |
| --- | --- | --- |
| | (1) | |
|
```
template< class T >
std::complex<T> operator+( const std::complex<T>& lhs, const std::complex<T>& rhs );
```
| (until C++20) |
|
```
template< class T >
constexpr std::complex<T> operator+( const std::complex<T>& lhs, const std::complex<T>& rhs );
```
| (since C++20) |
| | (2) | |
|
```
template< class T >
std::complex<T> operator+( const std::complex<T>& lhs, const T& rhs );
```
| (until C++20) |
|
```
template< class T >
constexpr std::complex<T> operator+( const std::complex<T>& lhs, const T& rhs );
```
| (since C++20) |
| | (3) | |
|
```
template< class T >
std::complex<T> operator+( const T& lhs, const std::complex<T>& rhs );
```
| (until C++20) |
|
```
template< class T >
constexpr std::complex<T> operator+( const T& lhs, const std::complex<T>& rhs );
```
| (since C++20) |
| | (4) | |
|
```
template< class T >
std::complex<T> operator-( const std::complex<T>& lhs, const std::complex<T>& rhs );
```
| (until C++20) |
|
```
template< class T >
constexpr std::complex<T> operator-( const std::complex<T>& lhs, const std::complex<T>& rhs );
```
| (since C++20) |
| | (5) | |
|
```
template< class T >
std::complex<T> operator-( const std::complex<T>& lhs, const T& rhs );
```
| (until C++20) |
|
```
template< class T >
constexpr std::complex<T> operator-( const std::complex<T>& lhs, const T& rhs );
```
| (since C++20) |
| | (6) | |
|
```
template< class T >
std::complex<T> operator-( const T& lhs, const std::complex<T>& rhs );
```
| (until C++20) |
|
```
template< class T >
constexpr std::complex<T> operator-( const T& lhs, const std::complex<T>& rhs );
```
| (since C++20) |
| | (7) | |
|
```
template< class T >
std::complex<T> operator*( const std::complex<T>& lhs, const std::complex<T>& rhs );
```
| (until C++20) |
|
```
template< class T >
constexpr std::complex<T> operator*( const std::complex<T>& lhs, const std::complex<T>& rhs );
```
| (since C++20) |
| | (8) | |
|
```
template< class T >
std::complex<T> operator*( const std::complex<T>& lhs, const T& rhs );
```
| (until C++20) |
|
```
template< class T >
constexpr std::complex<T> operator*( const std::complex<T>& lhs, const T& rhs );
```
| (since C++20) |
| | (9) | |
|
```
template< class T >
std::complex<T> operator*( const T& lhs, const std::complex<T>& rhs );
```
| (until C++20) |
|
```
template< class T >
constexpr std::complex<T> operator*( const T& lhs, const std::complex<T>& rhs );
```
| (since C++20) |
| | (10) | |
|
```
template< class T >
std::complex<T> operator/( const std::complex<T>& lhs, const std::complex<T>& rhs );
```
| (until C++20) |
|
```
template< class T >
constexpr std::complex<T> operator/( const std::complex<T>& lhs, const std::complex<T>& rhs );
```
| (since C++20) |
| | (11) | |
|
```
template< class T >
std::complex<T> operator/( const std::complex<T>& lhs, const T& rhs );
```
| (until C++20) |
|
```
template< class T >
constexpr std::complex<T> operator/( const std::complex<T>& lhs, const T& rhs );
```
| (since C++20) |
| | (12) | |
|
```
template< class T >
std::complex<T> operator/( const T& lhs, const std::complex<T>& rhs );
```
| (until C++20) |
|
```
template< class T >
constexpr std::complex<T> operator/( const T& lhs, const std::complex<T>& rhs );
```
| (since C++20) |
Implements the binary operators for complex arithmetic and for mixed complex/scalar arithmetic. Scalar arguments are treated as complex numbers with the real part equal to the argument and the imaginary part set to zero.
1-3) Returns the sum of its arguments
4-6) Returns the result of subtracting `rhs` from `lhs`
7-9) Multiplies its arguments
10-12) Divides `lhs` by `rhs`
### Parameters
| | | |
| --- | --- | --- |
| lhs, rhs | - | the arguments: either both complex numbers or one complex and one scalar of matching type (`float`, `double`, `long double`) |
### Return value
1-3) `[std::complex](http://en.cppreference.com/w/cpp/numeric/complex)<T>(lhs) += rhs`
4-6) `[std::complex](http://en.cppreference.com/w/cpp/numeric/complex)<T>(lhs) -= rhs`
7-9) `[std::complex](http://en.cppreference.com/w/cpp/numeric/complex)<T>(lhs) \*= rhs`
10-12) `[std::complex](http://en.cppreference.com/w/cpp/numeric/complex)<T>(lhs) /= rhs`
### Notes
Because [template argument deduction](../../language/template_argument_deduction "cpp/language/template argument deduction") does not consider implicit conversions, these operators cannot be used for mixed integer/complex arithmetic. In all cases, the scalar must have the same type as the underlying type of the complex number.
The GCC flag "-fcx-limited-range" (included by "-ffast-math") changes the behavior of complex multiply/division by removing checks for floating point edge cases. This impacts loop vectorization.
### Example
```
#include <iostream>
#include <complex>
int main()
{
std::complex<double> c2(2, 0);
std::complex<double> ci(0, 1);
std::cout << ci << " + " << c2 << " = " << ci+c2 << '\n'
<< ci << " * " << ci << " = " << ci*ci << '\n'
<< ci << " + " << c2 << " / " << ci << " = " << ci+c2/ci << '\n'
<< 1 << " / " << ci << " = " << 1./ci << '\n';
// std::cout << 1.f/ci; // compile error
// std::cout << 1/ci; // compile error
}
```
Output:
```
(0,1) + (2,0) = (2,1)
(0,1) * (0,1) = (-1,0)
(0,1) + (2,0) / (0,1) = (0,-1)
1 / (0,1) = (0,-1)
```
### See also
| | |
| --- | --- |
| [operator+=operator-=operator\*=operator/=](operator_arith "cpp/numeric/complex/operator arith") | compound assignment of two complex numbers or a complex and a scalar (public member function) |
| [operator+operator-](operator_arith2 "cpp/numeric/complex/operator arith2") | applies unary operators to complex numbers (function template) |
cpp std::norm(std::complex) std::norm(std::complex)
=======================
| Defined in header `[<complex>](../../header/complex "cpp/header/complex")` | | |
| --- | --- | --- |
| | (1) | |
|
```
template< class T >
T norm( const std::complex<T>& z );
```
| (until C++20) |
|
```
template< class T >
constexpr T norm( const std::complex<T>& z );
```
| (since C++20) |
| | (2) | |
|
```
float norm( float z );
template< class DoubleOrInteger >
double norm( DoubleOrInteger z );
long double norm( long double z );
```
| (since C++11) (until C++20) |
|
```
constexpr float norm( float z );
template< class DoubleOrInteger >
constexpr double norm( DoubleOrInteger z );
constexpr long double norm( long double z );
```
| (since C++20) |
1) Returns the squared magnitude of the complex number `z`.
| | |
| --- | --- |
| 2) Additional overloads are provided for `float`, `double`, `long double`, and all integer types, which are treated as complex numbers with zero imaginary component. | (since C++11) |
### Parameters
| | | |
| --- | --- | --- |
| z | - | complex value |
### Return value
the squared magnitude of `z`.
### Notes
The norm calculated by this function is also known as [field norm](https://en.wikipedia.org/wiki/Field_norm "enwiki:Field norm") or [absolute square](http://mathworld.wolfram.com/AbsoluteSquare.html).
The [Euclidean norm](https://en.wikipedia.org/wiki/Euclidean_space#Euclidean_norm "enwiki:Euclidean space") of a complex number is provided by [`std::abs`](abs "cpp/numeric/complex/abs"), which is more costly to compute. In some situations, it may be replaced by `std::norm`, for example, if `abs(z1) > abs(z2)` then `norm(z1) > norm(z2)`.
### Example
```
#include <cassert>
#include <complex>
#include <iostream>
int main()
{
constexpr std::complex<double> z{3, 4};
static_assert(std::norm(z) == (z.real() * z.real() + z.imag() * z.imag()));
static_assert(std::norm(z) == (z * std::conj(z)));
assert(std::norm(z) == (std::abs(z) * std::abs(z)));
std::cout << "std::norm(" << z << ") = " << std::norm(z) << '\n';
}
```
Output:
```
std::norm((3,4)) = 25
```
### See also
| | |
| --- | --- |
| [abs(std::complex)](abs "cpp/numeric/complex/abs") | returns the magnitude of a complex number (function template) |
| [conj](conj "cpp/numeric/complex/conj") | returns the complex conjugate (function template) |
| [polar](polar "cpp/numeric/complex/polar") | constructs a complex number from magnitude and phase angle (function template) |
| programming_docs |
cpp std::real(std::complex) std::real(std::complex)
=======================
| Defined in header `[<complex>](../../header/complex "cpp/header/complex")` | | |
| --- | --- | --- |
| | (1) | |
|
```
template< class T >
T real( const std::complex<T>& z );
```
| (until C++14) |
|
```
template< class T >
constexpr T real( const std::complex<T>& z );
```
| (since C++14) |
| | (2) | |
|
```
float real( float z );
template< class DoubleOrInteger >
double real( DoubleOrInteger z );
long double real( long double z );
```
| (since C++11) (until C++14) |
|
```
constexpr float real( float z );
template< class DoubleOrInteger >
constexpr double real( DoubleOrInteger z );
constexpr long double real( long double z );
```
| (since C++14) |
1) Returns the real component of the complex number `z`, i.e. `z.real()`.
| | |
| --- | --- |
| 2) Additional overloads are provided for `float`, `double`, `long double`, and all integer types, which are treated as complex numbers with zero imaginary component. | (since C++11) |
### Parameters
| | | |
| --- | --- | --- |
| z | - | complex value |
### Return value
The real component of `z`.
### See also
| | |
| --- | --- |
| [real](real "cpp/numeric/complex/real") | accesses the real part of the complex number (public member function) |
| [imag](imag2 "cpp/numeric/complex/imag2") | returns the imaginary component (function template) |
| [C documentation](https://en.cppreference.com/w/c/numeric/complex/creal "c/numeric/complex/creal") for `creal` |
cpp std::sqrt(std::complex) std::sqrt(std::complex)
=======================
| Defined in header `[<complex>](../../header/complex "cpp/header/complex")` | | |
| --- | --- | --- |
|
```
template< class T >
complex<T> sqrt( const complex<T>& z );
```
| | |
Computes the square root of the complex number `z` with a branch cut along the negative real axis.
### Parameters
| | | |
| --- | --- | --- |
| z | - | complex number to take the square root of |
### Return value
If no errors occur, returns the square root of `z`, in the range of the right half-plane, including the imaginary axis ([0; +โ) along the real axis and (โโ; +โ) along the imaginary axis.).
### Error handling and special values
Errors are reported consistent with `[math\_errhandling](../math/math_errhandling "cpp/numeric/math/math errhandling")`.
If the implementation supports IEEE floating-point arithmetic,
* The function is continuous onto the branch cut taking into account the sign of imaginary part
* `[std::sqrt](http://en.cppreference.com/w/cpp/numeric/math/sqrt)([std::conj](http://en.cppreference.com/w/cpp/numeric/complex/conj)(z)) == [std::conj](http://en.cppreference.com/w/cpp/numeric/complex/conj)([std::sqrt](http://en.cppreference.com/w/cpp/numeric/math/sqrt)(z))`
* If `z` is `(ยฑ0,+0)`, the result is `(+0,+0)`
* If `z` is `(x,+โ)`, the result is `(+โ,+โ)` even if x is NaN
* If `z` is `(x,NaN)`, the result is `(NaN,NaN)` (unless x is ยฑโ) and `[FE\_INVALID](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` may be raised
* If `z` is `(-โ,y)`, the result is `(+0,+โ)` for finite positive y
* If `z` is `(+โ,y)`, the result is `(+โ,+0)` for finite positive y
* If `z` is `(-โ,NaN)`, the result is `(NaN,โ)` (sign of imaginary part unspecified)
* If `z` is `(+โ,NaN)`, the result is `(+โ,NaN)`
* If `z` is `(NaN,y)`, the result is `(NaN,NaN)` and `[FE\_INVALID](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` may be raised
* If `z` is `(NaN,NaN)`, the result is `(NaN,NaN)`
### Notes
The semantics of this function are intended to be consistent with the C function [`csqrt`](https://en.cppreference.com/w/c/numeric/complex/csqrt "c/numeric/complex/csqrt").
### Example
```
#include <iostream>
#include <complex>
int main()
{
std::cout << "Square root of -4 is "
<< std::sqrt(std::complex<double>(-4, 0)) << '\n'
<< "Square root of (-4,-0), the other side of the cut, is "
<< std::sqrt(std::complex<double>(-4, -0.0)) << '\n';
}
```
Output:
```
Square root of -4 is (0,2)
Square root of (-4,-0), the other side of the cut, is (0,-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 2597](https://cplusplus.github.io/LWG/issue2597) | C++98 | specification mishandles signed zero imaginary parts | erroneous requirement removed |
### See also
| | |
| --- | --- |
| [pow(std::complex)](pow "cpp/numeric/complex/pow") | complex power, one or both arguments may be a complex number (function template) |
| [sqrtsqrtfsqrtl](../math/sqrt "cpp/numeric/math/sqrt")
(C++11)(C++11) | computes square root (\(\small{\sqrt{x} }\)โx) (function) |
| [sqrt(std::valarray)](../valarray/sqrt "cpp/numeric/valarray/sqrt") | applies the function `[std::sqrt](../math/sqrt "cpp/numeric/math/sqrt")` to each element of valarray (function template) |
| [C documentation](https://en.cppreference.com/w/c/numeric/complex/csqrt "c/numeric/complex/csqrt") for `csqrt` |
cpp std::polar(std::complex) std::polar(std::complex)
========================
| Defined in header `[<complex>](../../header/complex "cpp/header/complex")` | | |
| --- | --- | --- |
|
```
template< class T >
complex<T> polar( const T& r, const T& theta = T() );
```
| | |
Returns a complex number with magnitude `r` and phase angle `theta`.
The behavior is undefined if `r` is negative or NaN, or if `theta` is infinite.
### Parameters
| | | |
| --- | --- | --- |
| r | - | magnitude |
| theta | - | phase angle |
### Return value
a complex number determined by `r` and `theta`.
### Notes
`std::polar(r, theta)` is equivalent to any of the following expressions:
* `r \* [std::exp](http://en.cppreference.com/w/cpp/numeric/math/exp)(theta \* 1i)`
* `r * (cos(theta) + sin(theta) * 1i)`
* `[std::complex](http://en.cppreference.com/w/cpp/numeric/complex)(r \* cos(theta), r \* sin(theta))`.
Using polar instead of exp can be about **4.5x** faster in vectorized loops.
### Example
```
#include <cmath>
#include <complex>
#include <iomanip>
#include <iostream>
#include <numbers>
using namespace std::complex_literals;
int main()
{
constexpr auto ฯ_2 {std::numbers::pi / 2.0};
constexpr auto mag {1.0};
std::cout
<< std::fixed << std::showpos << std::setprecision(1)
<< " ฮธ: โ polar: โ exp: โ complex: โ trig:\n";
for (int n{}; n != 4; ++n) {
const auto ฮธ {n * ฯ_2};
std::cout
<< std::setw(4) << 90 * n << "ยฐ โ "
<< std::polar(mag, ฮธ) << " โ "
<< mag * std::exp(ฮธ * 1.0i) << " โ "
<< std::complex(mag * cos(ฮธ), mag * sin(ฮธ)) << " โ "
<< mag * (cos(ฮธ) + 1.0i * sin(ฮธ)) << '\n';
}
}
```
Output:
```
ฮธ: โ polar: โ exp: โ complex: โ trig:
+0ยฐ โ (+1.0,+0.0) โ (+1.0,+0.0) โ (+1.0,+0.0) โ (+1.0,+0.0)
+90ยฐ โ (+0.0,+1.0) โ (+0.0,+1.0) โ (+0.0,+1.0) โ (+0.0,+1.0)
+180ยฐ โ (-1.0,+0.0) โ (-1.0,+0.0) โ (-1.0,+0.0) โ (-1.0,+0.0)
+270ยฐ โ (-0.0,-1.0) โ (-0.0,-1.0) โ (-0.0,-1.0) โ (-0.0,-1.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 2459](https://cplusplus.github.io/LWG/issue2459) | C++98 | behavior unclear for some inputs | made undefined |
| [LWG 2870](https://cplusplus.github.io/LWG/issue2870) | C++98 | default value of parameter `theta` not dependent | made dependent |
### See also
| | |
| --- | --- |
| [abs(std::complex)](abs "cpp/numeric/complex/abs") | returns the magnitude of a complex number (function template) |
| [arg](arg "cpp/numeric/complex/arg") | returns the phase angle (function template) |
| [exp(std::complex)](exp "cpp/numeric/complex/exp") | complex base *e* exponential (function template) |
cpp std::tanh(std::complex) std::tanh(std::complex)
=======================
| Defined in header `[<complex>](../../header/complex "cpp/header/complex")` | | |
| --- | --- | --- |
|
```
template< class T >
complex<T> tanh( const complex<T>& z );
```
| | (since C++11) |
Computes complex hyperbolic tangent of a complex value `z`.
### Parameters
| | | |
| --- | --- | --- |
| z | - | complex value |
### Return value
If no errors occur, complex hyperbolic tangent of `z` is returned.
### Error handling and special values
Errors are reported consistent with `[math\_errhandling](../math/math_errhandling "cpp/numeric/math/math errhandling")`.
If the implementation supports IEEE floating-point arithmetic,
* `[std::tanh](http://en.cppreference.com/w/cpp/numeric/math/tanh)([std::conj](http://en.cppreference.com/w/cpp/numeric/complex/conj)(z)) == [std::conj](http://en.cppreference.com/w/cpp/numeric/complex/conj)([std::tanh](http://en.cppreference.com/w/cpp/numeric/math/tanh)(z))`
* `[std::tanh](http://en.cppreference.com/w/cpp/numeric/math/tanh)(-z) == -[std::tanh](http://en.cppreference.com/w/cpp/numeric/math/tanh)(z)`
* If `z` is `(+0,+0)`, the result is `(+0,+0)`
* If `z` is `(x,+โ)` (for any[[1]](#cite_note-1) finite x), the result is `(NaN,NaN)` and `[FE\_INVALID](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` is raised
* If `z` is `(x,NaN)` (for any[[2]](#cite_note-2) finite x), the result is `(NaN,NaN)` and `[FE\_INVALID](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` may be raised
* If `z` is `(+โ,y)` (for any finite positive y), the result is `(1,+0)`
* If `z` is `(+โ,+โ)`, the result is `(1,ยฑ0)` (the sign of the imaginary part is unspecified)
* If `z` is `(+โ,NaN)`, the result is `(1,ยฑ0)` (the sign of the imaginary part is unspecified)
* If `z` is `(NaN,+0)`, the result is `(NaN,+0)`
* If `z` is `(NaN,y)` (for any non-zero y), the result is `(NaN,NaN)` and `[FE\_INVALID](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` may be raised
* If `z` is `(NaN,NaN)`, the result is `(NaN,NaN)`
1. per [C11 DR471](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1892.htm#dr_471), this only holds for non-zero x. If `z` is `(0,โ)`, the result should be `(0,NaN)`
2. per [C11 DR471](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1892.htm#dr_471), this only holds for non-zero x. If `z` is `(0,NaN)`, the result should be `(0,NaN)`
### Notes
Mathematical definition of hyperbolic tangent is tanh z = ez-e-z/ez+e-z Hyperbolic tangent is an analytical function on the complex plane and has no branch cuts. It is periodic with respect to the imaginary component, with period ฯi, and has poles of the first order along the imaginary line, at coordinates (0, ฯ(1/2 + n)). However no common floating-point representation is able to represent ฯ/2 exactly, thus there is no value of the argument for which a pole error occurs.
### Example
```
#include <iostream>
#include <cmath>
#include <complex>
int main()
{
std::cout << std::fixed;
std::complex<double> z(1, 0); // behaves like real tanh along the real line
std::cout << "tanh" << z << " = " << std::tanh(z)
<< " (tanh(1) = " << std::tanh(1) << ")\n";
std::complex<double> z2(0, 1); // behaves like tangent along the imaginary line
std::cout << "tanh" << z2 << " = " << std::tanh(z2)
<< " ( tan(1) = " << std::tan(1) << ")\n";
}
```
Output:
```
tanh(1.000000,0.000000) = (0.761594,0.000000) (tanh(1) = 0.761594)
tanh(0.000000,1.000000) = (0.000000,1.557408) ( tan(1) = 1.557408)
```
### See also
| | |
| --- | --- |
| [sinh(std::complex)](sinh "cpp/numeric/complex/sinh") | computes hyperbolic sine of a complex number (\({\small\sinh{z} }\)sinh(z)) (function template) |
| [cosh(std::complex)](cosh "cpp/numeric/complex/cosh") | computes hyperbolic cosine of a complex number (\({\small\cosh{z} }\)cosh(z)) (function template) |
| [atanh(std::complex)](atanh "cpp/numeric/complex/atanh")
(C++11) | computes area hyperbolic tangent of a complex number (\({\small\operatorname{artanh}{z} }\)artanh(z)) (function template) |
| [tanhtanhftanhl](../math/tanh "cpp/numeric/math/tanh")
(C++11)(C++11) | computes hyperbolic tangent (\({\small\tanh{x} }\)tanh(x)) (function) |
| [tanh(std::valarray)](../valarray/tanh "cpp/numeric/valarray/tanh") | applies the function `[std::tanh](../math/tanh "cpp/numeric/math/tanh")` to each element of valarray (function template) |
| [C documentation](https://en.cppreference.com/w/c/numeric/complex/ctanh "c/numeric/complex/ctanh") for `ctanh` |
cpp std::pow(std::complex) std::pow(std::complex)
======================
| Defined in header `[<complex>](../../header/complex "cpp/header/complex")` | | |
| --- | --- | --- |
|
```
template< class T >
complex<T> pow( const complex<T>& x, const complex<T>& y );
```
| (1) | |
|
```
template< class T >
complex<T> pow( const complex<T>& x, const T& y );
```
| (2) | |
|
```
template< class T >
complex<T> pow( const T& x, const complex<T>& y );
```
| (3) | |
|
```
template< class T, class U >
complex</*Promoted*/> pow( const complex<T>& x, const complex<U>& y );
```
| (4) | (since C++11) |
|
```
template< class T, class U >
complex</*Promoted*/> pow( const complex<T>& x, const U& y );
```
| (5) | (since C++11) |
|
```
template< class T, class U >
complex</*Promoted*/> pow( const T& x, const complex<U>& y );
```
| (6) | (since C++11) |
1-3) Computes complex `x` raised to a complex power `y` with a branch cut along the negative real axis for the first argument.
| | |
| --- | --- |
| 4-6) Additional overloads are provided for all arithmetic types, such that
1. If either argument is `long double` or `[std::complex](http://en.cppreference.com/w/cpp/numeric/complex)<long double>`, then both arguments are cast to `[std::complex](http://en.cppreference.com/w/cpp/numeric/complex)<long double>`
2. Otherwise, if either argument is `double`, `[std::complex](http://en.cppreference.com/w/cpp/numeric/complex)<double>` or integer type, then both arguments are cast to `[std::complex](http://en.cppreference.com/w/cpp/numeric/complex)<double>`
3. Otherwise, if either argument is `float` or `[std::complex](http://en.cppreference.com/w/cpp/numeric/complex)<float>`, then both arguments are cast to `[std::complex](http://en.cppreference.com/w/cpp/numeric/complex)<float>`
| (since C++11) |
### Parameters
| | | |
| --- | --- | --- |
| x | - | base as a complex value |
| y | - | exponent as a complex value |
### Return value
If no errors occur, the complex power xy
, is returned.
Errors and special cases are handled as if the operation is implemented by `[std::exp](http://en.cppreference.com/w/cpp/numeric/math/exp)(y\*[std::log](http://en.cppreference.com/w/cpp/numeric/math/log)(x))`.
The result of `[std::pow](http://en.cppreference.com/w/cpp/numeric/math/pow)(0, 0)` is implementation-defined.
### Example
```
#include <iostream>
#include <complex>
int main()
{
std::cout << std::fixed;
std::complex<double> z(1, 2);
std::cout << "(1,2)^2 = " << std::pow(z, 2) << '\n';
std::complex<double> z2(-1, 0); // square root of -1
std::cout << "-1^0.5 = " << std::pow(z2, 0.5) << '\n';
std::complex<double> z3(-1, -0.0); // other side of the cut
std::cout << "(-1, -0)^0.5 = " << std::pow(z3, 0.5) << '\n';
std::complex<double> i(0, 1); // i^i = exp(-pi/2)
std::cout << "i^i = " << std::pow(i, i) << '\n';
}
```
Output:
```
(1,2)^2 = (-3.000000,4.000000)
-1^0.5 = (0.000000,1.000000)
(-1, -0)^0.5 = (0.000000,-1.000000)
i^i = (0.207880,0.000000)
```
### See also
| | |
| --- | --- |
| [sqrt(std::complex)](sqrt "cpp/numeric/complex/sqrt") | complex square root in the range of the right half-plane (function template) |
| [powpowfpowl](../math/pow "cpp/numeric/math/pow")
(C++11)(C++11) | raises a number to the given power (\(\small{x^y}\)xy) (function) |
| [pow(std::valarray)](../valarray/pow "cpp/numeric/valarray/pow") | applies the function `[std::pow](../math/pow "cpp/numeric/math/pow")` to two valarrays or a valarray and a value (function template) |
| [C documentation](https://en.cppreference.com/w/c/numeric/complex/cpow "c/numeric/complex/cpow") for `cpow` |
cpp std::exp(std::complex) std::exp(std::complex)
======================
| Defined in header `[<complex>](../../header/complex "cpp/header/complex")` | | |
| --- | --- | --- |
|
```
template< class T >
complex<T> exp( const complex<T>& z );
```
| | |
Compute base-e exponential of `z`, that is *e* (Euler's number, `2.7182818`) raised to the `z` power.
### Parameters
| | | |
| --- | --- | --- |
| z | - | complex value |
### Return value
If no errors occur, *e* raised to the power of `z`, ez
, is returned.
### Error handling and special values
Errors are reported consistent with `[math\_errhandling](../math/math_errhandling "cpp/numeric/math/math errhandling")`.
If the implementation supports IEEE floating-point arithmetic,
* `[std::exp](http://en.cppreference.com/w/cpp/numeric/math/exp)([std::conj](http://en.cppreference.com/w/cpp/numeric/complex/conj)(z)) == [std::conj](http://en.cppreference.com/w/cpp/numeric/complex/conj)([std::exp](http://en.cppreference.com/w/cpp/numeric/math/exp)(z))`
* If `z` is `(ยฑ0,+0)`, the result is `(1,+0)`
* If `z` is `(x,+โ)` (for any finite x), the result is `(NaN,NaN)` and `[FE\_INVALID](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` is raised.
* If `z` is `(x,NaN)` (for any finite x), the result is `(NaN,NaN)` and `[FE\_INVALID](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` may be raised.
* If `z` is `(+โ,+0)`, the result is `(+โ,+0)`
* If `z` is `(-โ,y)` (for any finite y), the result is `+0cis(y)`
* If `z` is `(+โ,y)` (for any finite nonzero y), the result is `+โcis(y)`
* If `z` is `(-โ,+โ)`, the result is `(ยฑ0,ยฑ0)` (signs are unspecified)
* If `z` is `(+โ,+โ)`, the result is `(ยฑโ,NaN)` and `[FE\_INVALID](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` is raised (the sign of the real part is unspecified)
* If `z` is `(-โ,NaN)`, the result is `(ยฑ0,ยฑ0)` (signs are unspecified)
* If `z` is `(+โ,NaN)`, the result is `(ยฑโ,NaN)` (the sign of the real part is unspecified)
* If `z` is `(NaN,+0)`, the result is `(NaN,+0)`
* If `z` is `(NaN,y)` (for any nonzero y), the result is `(NaN,NaN)` and `[FE\_INVALID](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` may be raised
* If `z` is `(NaN,NaN)`, the result is `(NaN,NaN)`
where cis(y) is cos(y) + i sin(y).
### Notes
The complex exponential function ez
for z = x+iy equals ex
cis(y), or, ex
(cos(y) + i sin(y)).
The exponential function is an *entire function* in the complex plane and has no branch cuts.
The following have equivalent results when the real part is 0:
* `[std::exp](http://en.cppreference.com/w/cpp/numeric/math/exp)([std::complex](http://en.cppreference.com/w/cpp/numeric/complex)<float>(0, theta))`
* `[std::complex](http://en.cppreference.com/w/cpp/numeric/complex)<float>(cosf(theta), sinf(theta))`
* `[std::polar](http://en.cppreference.com/w/cpp/numeric/complex/polar)(1.f, theta)`
In this case exp can be about 4.5x slower. One of the other forms should be used instead of using exp with a literal 0 component. There is no benefit in trying to avoid exp with a runtime check of `z.real() == 0` though.
### Example
```
#include <complex>
#include <iostream>
int main()
{
const double pi = std::acos(-1);
const std::complex<double> i(0, 1);
std::cout << std::fixed << " exp(i*pi) = " << std::exp(i * pi) << '\n';
}
```
Output:
```
exp(i*pi) = (-1.000000,0.000000)
```
### See also
| | |
| --- | --- |
| [log(std::complex)](log "cpp/numeric/complex/log") | complex natural logarithm with the branch cuts along the negative real axis (function template) |
| [expexpfexpl](../math/exp "cpp/numeric/math/exp")
(C++11)(C++11) | returns *e* raised to the given power (\({\small e^x}\)ex) (function) |
| [exp(std::valarray)](../valarray/exp "cpp/numeric/valarray/exp") | applies the function `[std::exp](../math/exp "cpp/numeric/math/exp")` to each element of valarray (function template) |
| [polar](polar "cpp/numeric/complex/polar") | constructs a complex number from magnitude and phase angle (function template) |
| [C documentation](https://en.cppreference.com/w/c/numeric/complex/cexp "c/numeric/complex/cexp") for `cexp` |
| programming_docs |
cpp std::literals::complex_literals::operator""i, operator""if, operator""il std::literals::complex\_literals::operator""i, operator""if, operator""il
=========================================================================
| Defined in header `[<complex>](../../header/complex "cpp/header/complex")` | | |
| --- | --- | --- |
|
```
constexpr complex< double > operator""i( long double arg );
constexpr complex< double > operator""i( unsigned long long arg );
```
| (1) | (since C++14) |
|
```
constexpr complex< float > operator""if( long double arg );
constexpr complex< float > operator""if( unsigned long long arg );
```
| (2) | (since C++14) |
|
```
constexpr complex< long double > operator""il( long double arg );
constexpr complex< long double > operator""il( unsigned long long arg );
```
| (3) | (since C++14) |
Forms a `[std::complex](../complex "cpp/numeric/complex")` literal representing an imaginary number.
1) forms a literal `[std::complex](http://en.cppreference.com/w/cpp/numeric/complex)<double>` with the real part zero and imaginary part `arg`
2) forms a literal `[std::complex](http://en.cppreference.com/w/cpp/numeric/complex)<float>` with the real part zero and imaginary part `arg`
3) forms a literal `[std::complex](http://en.cppreference.com/w/cpp/numeric/complex)<long double>` with the real part zero and imaginary part `arg`
### Parameters
| | | |
| --- | --- | --- |
| arg | - | the value of the imaginary number |
### Return value
The `[std::complex](../complex "cpp/numeric/complex")` literal with the real part zero and imaginary part `arg`.
### Notes
These operators are declared in the namespace `std::literals::complex_literals`, where both `literals` and `complex_literals` are inline namespaces. Access to these operators can be gained with `using namespace std::literals`, `using namespace std::complex_literals`, and `using namespace std::literals::complex_literals`.
Even though `if` is a [keyword](../../keywords/if "cpp/keywords/if") in C++, it is a ud-suffix of the [literal operator](../../language/user_literal "cpp/language/user literal") of the form `operator ""if` and in the literal expressions such as `1if` or `1.0if` because it is not separated by whitespace and is not a standalone token.
| [Feature-test](../../utility/feature_test "cpp/utility/feature test") macro |
| --- |
| [`__cpp_lib_complex_udls`](../../feature_test#Library_features "cpp/feature test") |
### Possible implementation
| First version |
| --- |
|
```
constexpr std::complex<double> operator""i(unsigned long long d)
{
return std::complex<double>{0.0, static_cast<double>(d)};
}
constexpr std::complex<double> operator""i(long double d)
{
return std::complex<double>{0.0, static_cast<double>(d)};
}
```
|
| Second version |
|
```
constexpr std::complex<float> operator""if(unsigned long long d)
{
return std::complex<float>{0.0f, static_cast<float>(d)};
}
constexpr std::complex<float> operator""if(long double d)
{
return std::complex<float>{0.0f, static_cast<float>(d)};
}
```
|
| Third version |
|
```
constexpr std::complex<long double> operator""il(unsigned long long d)
{
return std::complex<long double>{0.0L, static_cast<long double>(d)};
}
constexpr std::complex<long double> operator""il(long double d)
{
return std::complex<long double>{0.0L, d};
}
```
|
### Example
```
#include <iostream>
#include <complex>
int main()
{
using namespace std::complex_literals;
std::complex<double> c = 1.0 + 1i;
std::cout << "abs" << c << " = " << std::abs(c) << '\n';
std::complex<float> z = 3.0f + 4.0if;
std::cout << "abs" << z << " = " << std::abs(z) << '\n';
}
```
Output:
```
abs(1,1) = 1.41421
abs(3,4) = 5
```
### See also
| | |
| --- | --- |
| [(constructor)](complex "cpp/numeric/complex/complex") | constructs a complex number (public member function) |
| [operator=](operator= "cpp/numeric/complex/operator=") | assigns the contents (public member function) |
| [C documentation](https://en.cppreference.com/w/c/numeric/complex/I "c/numeric/complex/I") for `I` |
cpp std::complex<T>::real std::complex<T>::real
=====================
| | | |
| --- | --- | --- |
| primary template complex<T> | | |
| | (1) | |
|
```
T real() const;
```
| (until C++14) |
|
```
constexpr T real() const;
```
| (since C++14) |
| | (2) | |
|
```
void real( T value );
```
| (until C++20) |
|
```
constexpr void real( T value );
```
| (since C++20) |
| specialization complex<float> | | |
| | (1) | |
|
```
float real() const;
```
| (until C++11) |
|
```
constexpr float real() const;
```
| (since C++11) |
| | (2) | |
|
```
void real( float value );
```
| (until C++20) |
|
```
constexpr void real( float value );
```
| (since C++20) |
| specialization complex<double> | | |
| | (1) | |
|
```
double real() const;
```
| (until C++11) |
|
```
constexpr double real() const;
```
| (since C++11) |
| | (2) | |
|
```
void real( double value );
```
| (until C++20) |
|
```
constexpr void real( double value );
```
| (since C++20) |
| specialization complex<long double> | | |
| | (1) | |
|
```
long double real() const;
```
| (until C++11) |
|
```
constexpr long double real() const;
```
| (since C++11) |
| | (2) | |
|
```
void real( long double value );
```
| (until C++20) |
|
```
constexpr void real( long double value );
```
| (since C++20) |
Accesses the real part of the complex number.
1) Returns the real part.
2) Sets the real part to `value`. ### Parameters
| | | |
| --- | --- | --- |
| value | - | the value to set the real part to |
### Return value
1) The real part.
2) (none) ### Notes
In C++11, overload (1) in `complex` specializations used to be specified without `const` qualifier. However, in C++11, a [`constexpr`](../../language/constexpr "cpp/language/constexpr") specifier used in a non-static member function implies `const`, and thus the behavior is as if `const` is specified.
### See also
| | |
| --- | --- |
| [real](real2 "cpp/numeric/complex/real2") | returns the real component (function template) |
| [imag](imag "cpp/numeric/complex/imag") | accesses the imaginary part of the complex number (public member function) |
cpp std::sinh(std::complex) std::sinh(std::complex)
=======================
| Defined in header `[<complex>](../../header/complex "cpp/header/complex")` | | |
| --- | --- | --- |
|
```
template< class T >
complex<T> sinh( const complex<T>& z );
```
| | (since C++11) |
Computes complex hyperbolic sine of a complex value `z`.
### Parameters
| | | |
| --- | --- | --- |
| z | - | complex value |
### Return value
If no errors occur, complex hyperbolic sine of `z` is returned.
### Error handling and special values
Errors are reported consistent with `[math\_errhandling](../math/math_errhandling "cpp/numeric/math/math errhandling")`.
If the implementation supports IEEE floating-point arithmetic,
* `[std::sinh](http://en.cppreference.com/w/cpp/numeric/math/sinh)([std::conj](http://en.cppreference.com/w/cpp/numeric/complex/conj)(z)) == [std::conj](http://en.cppreference.com/w/cpp/numeric/complex/conj)([std::sinh](http://en.cppreference.com/w/cpp/numeric/math/sinh)(z))`
* `[std::sinh](http://en.cppreference.com/w/cpp/numeric/math/sinh)(z) == -[std::sinh](http://en.cppreference.com/w/cpp/numeric/math/sinh)(-z)`
* If `z` is `(+0,+0)`, the result is `(+0,+0)`
* If `z` is `(+0,+โ)`, the result is `(ยฑ0,NaN)` (the sign of the real part is unspecified) and `[FE\_INVALID](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` is raised
* If `z` is `(+0,NaN)`, the result is `(ยฑ0,NaN)`
* If `z` is `(x,+โ)` (for any positive finite x), the result is `(NaN,NaN)` and `[FE\_INVALID](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` is raised
* If `z` is `(x,NaN)` (for any positive finite x), the result is `(NaN,NaN)` and `[FE\_INVALID](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` may be raised
* If `z` is `(+โ,+0)`, the result is `(+โ,+0)`
* If `z` is `(+โ,y)` (for any positive finite y), the result is `+โcis(y)`
* If `z` is `(+โ,+โ)`, the result is `(ยฑโ,NaN)` (the sign of the real part is unspecified) and `[FE\_INVALID](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` is raised
* If `z` is `(+โ,NaN)`, the result is `(ยฑโ,NaN)` (the sign of the real part is unspecified)
* If `z` is `(NaN,+0)`, the result is `(NaN,+0)`
* If `z` is `(NaN,y)` (for any finite nonzero y), the result is `(NaN,NaN)` and `[FE\_INVALID](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` may be raised
* If `z` is `(NaN,NaN)`, the result is `(NaN,NaN)`
where cis(y) is cos(y) + i sin(y).
### Notes
Mathematical definition of hyperbolic sine is sinh z = ez-e-z/2 Hyperbolic sine is an entire function in the complex plane and has no branch cuts. It is periodic with respect to the imaginary component, with period 2ฯi.
### Example
```
#include <iostream>
#include <cmath>
#include <complex>
int main()
{
std::cout << std::fixed;
std::complex<double> z(1, 0); // behaves like real sinh along the real line
std::cout << "sinh" << z << " = " << std::sinh(z)
<< " (sinh(1) = " << std::sinh(1) << ")\n";
std::complex<double> z2(0, 1); // behaves like sine along the imaginary line
std::cout << "sinh" << z2 << " = " << std::sinh(z2)
<< " ( sin(1) = " << std::sin(1) << ")\n";
}
```
Output:
```
sinh(1.000000,0.000000) = (1.175201,0.000000) (sinh(1) = 1.175201)
sinh(0.000000,1.000000) = (0.000000,0.841471) ( sin(1) = 0.841471)
```
### See also
| | |
| --- | --- |
| [cosh(std::complex)](cosh "cpp/numeric/complex/cosh") | computes hyperbolic cosine of a complex number (\({\small\cosh{z} }\)cosh(z)) (function template) |
| [tanh(std::complex)](tanh "cpp/numeric/complex/tanh") | computes hyperbolic tangent of a complex number (\({\small\tanh{z} }\)tanh(z)) (function template) |
| [asinh(std::complex)](asinh "cpp/numeric/complex/asinh")
(C++11) | computes area hyperbolic sine of a complex number (\({\small\operatorname{arsinh}{z} }\)arsinh(z)) (function template) |
| [sinhsinhfsinhl](../math/sinh "cpp/numeric/math/sinh")
(C++11)(C++11) | computes hyperbolic sine (\({\small\sinh{x} }\)sinh(x)) (function) |
| [sinh(std::valarray)](../valarray/sinh "cpp/numeric/valarray/sinh") | applies the function `[std::sinh](../math/sinh "cpp/numeric/math/sinh")` to each element of valarray (function template) |
| [C documentation](https://en.cppreference.com/w/c/numeric/complex/csinh "c/numeric/complex/csinh") for `csinh` |
cpp std::acosh(std::complex) std::acosh(std::complex)
========================
| Defined in header `[<complex>](../../header/complex "cpp/header/complex")` | | |
| --- | --- | --- |
|
```
template< class T >
complex<T> acosh( const complex<T>& z );
```
| | (since C++11) |
Computes complex arc hyperbolic cosine of a complex value `z` with branch cut at values less than 1 along the real axis.
### Parameters
| | | |
| --- | --- | --- |
| z | - | complex value |
### Return value
If no errors occur, the complex arc hyperbolic cosine of `z` is returned, in the range of a half-strip of nonnegative values along the real axis and in the interval [โiฯ; +iฯ] along the imaginary axis.
### Error handling and special values
Errors are reported consistent with `[math\_errhandling](../math/math_errhandling "cpp/numeric/math/math errhandling")`.
If the implementation supports IEEE floating-point arithmetic,
* `[std::acosh](http://en.cppreference.com/w/cpp/numeric/math/acosh)([std::conj](http://en.cppreference.com/w/cpp/numeric/complex/conj)(z)) == [std::conj](http://en.cppreference.com/w/cpp/numeric/complex/conj)([std::acosh](http://en.cppreference.com/w/cpp/numeric/math/acosh)(z))`
* If `z` is `(ยฑ0,+0)`, the result is `(+0,ฯ/2)`
* If `z` is `(x,+โ)` (for any finite x), the result is `(+โ,ฯ/2)`
* If `z` is `(x,NaN)` (for any[[1]](#cite_note-1) finite x), the result is `(NaN,NaN)` and `[FE\_INVALID](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` may be raised.
* If `z` is `(-โ,y)` (for any positive finite y), the result is `(+โ,ฯ)`
* If `z` is `(+โ,y)` (for any positive finite y), the result is `(+โ,+0)`
* If `z` is `(-โ,+โ)`, the result is `(+โ,3ฯ/4)`
* If `z` is `(ยฑโ,NaN)`, the result is `(+โ,NaN)`
* If `z` is `(NaN,y)` (for any finite y), the result is `(NaN,NaN)` and `[FE\_INVALID](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` may be raised.
* If `z` is `(NaN,+โ)`, the result is `(+โ,NaN)`
* If `z` is `(NaN,NaN)`, the result is `(NaN,NaN)`
1. per [C11 DR471](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1892.htm#dr_471), this holds for non-zero x only. If `z` is `(0,NaN)`, the result should be `(NaN,ฯ/2)`
### Notes
Although the C++ standard names this function "complex arc hyperbolic cosine", the inverse functions of the hyperbolic functions are the area functions. Their argument is the area of a hyperbolic sector, not an arc. The correct name is "complex inverse hyperbolic cosine", and, less common, "complex area hyperbolic cosine".
Inverse hyperbolic cosine is a multivalued function and requires a branch cut on the complex plane. The branch cut is conventionally placed at the line segment (-โ,+1) of the real axis.
The mathematical definition of the principal value of the inverse hyperbolic cosine is acosh z = ln(z + โz+1 โz-1) For any z, acosh(z) =
โz-1/โ1-z acos(z), or simply i acos(z) in the upper half of the complex plane. ### Example
```
#include <iostream>
#include <complex>
int main()
{
std::cout << std::fixed;
std::complex<double> z1(0.5, 0);
std::cout << "acosh" << z1 << " = " << std::acosh(z1) << '\n';
std::complex<double> z2(0.5, -0.0);
std::cout << "acosh" << z2 << " (the other side of the cut) = "
<< std::acosh(z2) << '\n';
// in upper half-plane, acosh = i acos
std::complex<double> z3(1, 1), i(0, 1);
std::cout << "acosh" << z3 << " = " << std::acosh(z3) << '\n'
<< "i*acos" << z3 << " = " << i*std::acos(z3) << '\n';
}
```
Output:
```
acosh(0.500000,0.000000) = (0.000000,-1.047198)
acosh(0.500000,-0.000000) (the other side of the cut) = (0.000000,1.047198)
acosh(1.000000,1.000000) = (1.061275,0.904557)
i*acos(1.000000,1.000000) = (1.061275,0.904557)
```
### See also
| | |
| --- | --- |
| [acos(std::complex)](acos "cpp/numeric/complex/acos")
(C++11) | computes arc cosine of a complex number (\({\small\arccos{z} }\)arccos(z)) (function template) |
| [asinh(std::complex)](asinh "cpp/numeric/complex/asinh")
(C++11) | computes area hyperbolic sine of a complex number (\({\small\operatorname{arsinh}{z} }\)arsinh(z)) (function template) |
| [atanh(std::complex)](atanh "cpp/numeric/complex/atanh")
(C++11) | computes area hyperbolic tangent of a complex number (\({\small\operatorname{artanh}{z} }\)artanh(z)) (function template) |
| [cosh(std::complex)](cosh "cpp/numeric/complex/cosh") | computes hyperbolic cosine of a complex number (\({\small\cosh{z} }\)cosh(z)) (function template) |
| [acoshacoshfacoshl](../math/acosh "cpp/numeric/math/acosh")
(C++11)(C++11)(C++11) | computes the inverse hyperbolic cosine (\({\small\operatorname{arcosh}{x} }\)arcosh(x)) (function) |
| [C documentation](https://en.cppreference.com/w/c/numeric/complex/cacosh "c/numeric/complex/cacosh") for `cacosh` |
cpp std::log(std::complex) std::log(std::complex)
======================
| Defined in header `[<complex>](../../header/complex "cpp/header/complex")` | | |
| --- | --- | --- |
|
```
template< class T >
complex<T> log( const complex<T>& z );
```
| | |
Computes complex natural (base *e*) logarithm of a complex value `z` with a branch cut along the negative real axis.
### Parameters
| | | |
| --- | --- | --- |
| z | - | complex value |
### Return value
If no errors occur, the complex natural logarithm of `z` is returned, in the range of a strip in the interval [โiฯ, +iฯ] along the imaginary axis and mathematically unbounded along the real axis.
### Error handling and special values
Errors are reported consistent with [math\_errhandling](../math/math_errhandling "cpp/numeric/math/math errhandling").
If the implementation supports IEEE floating-point arithmetic,
* The function is continuous onto the branch cut taking into account the sign of imaginary part
* `[std::log](http://en.cppreference.com/w/cpp/numeric/math/log)([std::conj](http://en.cppreference.com/w/cpp/numeric/complex/conj)(z)) == [std::conj](http://en.cppreference.com/w/cpp/numeric/complex/conj)([std::log](http://en.cppreference.com/w/cpp/numeric/math/log)(z))`
* If `z` is `(-0,+0)`, the result is `(-โ,ฯ)` and `[FE\_DIVBYZERO](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` is raised
* If `z` is `(+0,+0)`, the result is `(-โ,+0)` and `[FE\_DIVBYZERO](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` is raised
* If `z` is `(x,+โ)` (for any finite x), the result is `(+โ,ฯ/2)`
* If `z` is `(x,NaN)` (for any finite x), the result is `(NaN,NaN)` and `[FE\_INVALID](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` may be raised
* If `z` is `(-โ,y)` (for any finite positive y), the result is `(+โ,ฯ)`
* If `z` is `(+โ,y)` (for any finite positive y), the result is `(+โ,+0)`
* If `z` is `(-โ,+โ)`, the result is `(+โ,3ฯ/4)`
* If `z` is `(+โ,+โ)`, the result is `(+โ,ฯ/4)`
* If `z` is `(ยฑโ,NaN)`, the result is `(+โ,NaN)`
* If `z` is `(NaN,y)` (for any finite y), the result is `(NaN,NaN)` and `[FE\_INVALID](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` may be raised
* If `z` is `(NaN,+โ)`, the result is `(+โ,NaN)`
* If `z` is `(NaN,NaN)`, the result is `(NaN,NaN)`
### Notes
The natural logarithm of a complex number z with polar coordinate components (r,ฮธ) equals ln r + i(ฮธ+2nฯ), with the principal value ln r + iฮธ
The semantics of this function are intended to be consistent with the C function [`clog`](https://en.cppreference.com/w/c/numeric/complex/clog "c/numeric/complex/clog").
### 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 2597](https://cplusplus.github.io/LWG/issue2597) | C++98 | specification mishandles signed zero imaginary parts | erroneous requirement removed |
### Example
```
#include <iostream>
#include <cmath>
#include <complex>
int main()
{
std::complex<double> z{0, 1}; // r = 1, ฮธ = pi/2
std::cout << "2*log" << z << " = " << 2.*std::log(z) << '\n';
std::complex<double> z2{sqrt(2)/2, sqrt(2)/2}; // r = 1, ฮธ = pi/4
std::cout << "4*log" << z2 << " = " << 4.*std::log(z2) << '\n';
std::complex<double> z3{-1, 0}; // r = 1, ฮธ = pi
std::cout << "log" << z3 << " = " << std::log(z3) << '\n';
std::complex<double> z4{-1, -0.0}; // the other side of the cut
std::cout << "log" << z4 << " (the other side of the cut) = " << std::log(z4) << '\n';
}
```
Output:
```
2*log(0,1) = (0,3.14159)
4*log(0.707107,0.707107) = (0,3.14159)
log(-1,0) = (0,3.14159)
log(-1,-0) (the other side of the cut) = (0,-3.14159)
```
### See also
| | |
| --- | --- |
| [log10(std::complex)](log10 "cpp/numeric/complex/log10") | complex common logarithm with the branch cuts along the negative real axis (function template) |
| [exp(std::complex)](exp "cpp/numeric/complex/exp") | complex base *e* exponential (function template) |
| [loglogflogl](../math/log "cpp/numeric/math/log")
(C++11)(C++11) | computes natural (base *e*) logarithm (\({\small \ln{x} }\)ln(x)) (function) |
| [log(std::valarray)](../valarray/log "cpp/numeric/valarray/log") | applies the function `[std::log](../math/log "cpp/numeric/math/log")` to each element of valarray (function template) |
| [C documentation](https://en.cppreference.com/w/c/numeric/complex/clog "c/numeric/complex/clog") for `clog` |
| programming_docs |
cpp std::abs(std::complex) std::abs(std::complex)
======================
| Defined in header `[<complex>](../../header/complex "cpp/header/complex")` | | |
| --- | --- | --- |
|
```
template< class T >
T abs( const complex<T>& z );
```
| | |
Returns the magnitude of the complex number `z`.
### Parameters
| | | |
| --- | --- | --- |
| z | - | complex value |
### Return value
If no errors occur, returns the absolute value (also known as norm, modulus, or magnitude) of `z`.
Errors and special cases are handled as if the function is implemented as `[std::hypot](http://en.cppreference.com/w/cpp/numeric/math/hypot)([std::real](http://en.cppreference.com/w/cpp/numeric/complex/real2)(z), [std::imag](http://en.cppreference.com/w/cpp/numeric/complex/imag2)(z))`.
### Example
```
#include <iostream>
#include <complex>
int main()
{
std::complex<double> z(1, 1);
std::cout << z << " cartesian is rho = " << std::abs(z)
<< " theta = " << std::arg(z) << " polar\n";
}
```
Output:
```
(1,1) cartesian is rho = 1.41421 theta = 0.785398 polar
```
### See also
| | |
| --- | --- |
| [arg](arg "cpp/numeric/complex/arg") | returns the phase angle (function template) |
| [polar](polar "cpp/numeric/complex/polar") | constructs a complex number from magnitude and phase angle (function template) |
| [abs(int)labsllabs](../math/abs "cpp/numeric/math/abs")
(C++11) | computes absolute value of an integral value (\(\small{|x|}\)|x|) (function) |
| [abs(float)fabsfabsffabsl](../math/fabs "cpp/numeric/math/fabs")
(C++11)(C++11) | absolute value of a floating point value (\(\small{|x|}\)|x|) (function) |
| [hypothypotfhypotl](../math/hypot "cpp/numeric/math/hypot")
(C++11)(C++11)(C++11) | computes square root of the sum of the squares of two or three (C++17) given numbers (\(\scriptsize{\sqrt{x^2+y^2} }\)โx2+y2), (\(\scriptsize{\sqrt{x^2+y^2+z^2} }\)โx2+y2+z2) (function) |
| [abs(std::valarray)](../valarray/abs "cpp/numeric/valarray/abs") | applies the function `abs` to each element of valarray (function template) |
| [C documentation](https://en.cppreference.com/w/c/numeric/complex/cabs "c/numeric/complex/cabs") for `cabs` |
cpp std::complex<T>::operator= std::complex<T>::operator=
==========================
| | | |
| --- | --- | --- |
| Primary template `complex<T>` | | |
| | (1) | |
|
```
complex& operator=( const T& x );
```
| (until C++20) |
|
```
constexpr complex& operator=( const T& x );
```
| (since C++20) |
| Specialization `complex<float>` | | |
| | (1) | |
|
```
complex& operator=( float x );
```
| (until C++20) |
|
```
constexpr complex& operator=( float x );
```
| (since C++20) |
| Specialization `complex<double>` | | |
| | (1) | |
|
```
complex& operator=( double x );
```
| (until C++20) |
|
```
constexpr complex& operator=( double x );
```
| (since C++20) |
| Specialization `complex<long double>` | | |
| | (1) | |
|
```
complex& operator=( long double x );
```
| (until C++20) |
|
```
constexpr complex& operator=( long double x );
```
| (since C++20) |
| All specializations | | |
| | (2) | |
|
```
complex& operator=( const complex& cx );
```
| (until C++20) |
|
```
constexpr complex& operator=( const complex& cx );
```
| (since C++20) |
| | (3) | |
|
```
template< class X >
complex& operator=( const std::complex<X>& cx );
```
| (until C++20) |
|
```
template< class X >
constexpr complex& operator=( const std::complex<X>& cx );
```
| (since C++20) |
Assigns new values to the contents.
1) Assigns `x` to the real part of the complex number. Imaginary part is set to zero.
2,3) Assigns `[cx.real()](real "cpp/numeric/complex/real")` and `[cx.imag()](imag "cpp/numeric/complex/imag")` to the real and the imaginary parts of the complex number respectively. ### Parameters
| | | |
| --- | --- | --- |
| x | - | value to assign |
| cx | - | complex value to assign |
### Return value
`*this`.
### See also
| | |
| --- | --- |
| [(constructor)](complex "cpp/numeric/complex/complex") | constructs a complex number (public member function) |
| [operator""ifoperator""ioperator""il](operator%22%22i "cpp/numeric/complex/operator\"\"i")
(C++14) | A `[std::complex](../complex "cpp/numeric/complex")` literal representing pure imaginary number (function) |
cpp std::log10(std::complex) std::log10(std::complex)
========================
| Defined in header `[<complex>](../../header/complex "cpp/header/complex")` | | |
| --- | --- | --- |
|
```
template< class T >
complex<T> log10( const complex<T>& z );
```
| | |
Computes complex common (base `10`) logarithm of a complex value `z` with a branch cut along the negative real axis.
The behavior of this function is equivalent to `[std::log](log "cpp/numeric/complex/log")(z)/[std::log](../math/log "cpp/numeric/math/log")(T(10))`.
### Parameters
| | | |
| --- | --- | --- |
| z | - | complex value |
### Return value
Complex common logarithm of `z`.
### Example
```
#include <iostream>
#include <cmath>
#include <complex>
int main()
{
std::complex<double> z(0, 1); // // r = 0, ฮธ = pi/2
std::cout << "2*log10" << z << " = " << 2.*std::log10(z) << '\n';
std::complex<double> z2(sqrt(2)/2, sqrt(2)/2); // r = 1, ฮธ = pi/4
std::cout << "4*log10" << z2 << " = " << 4.*std::log10(z2) << '\n';
std::complex<double> z3(-100, 0); // r = 100, ฮธ = pi
std::cout << "log10" << z3 << " = " << std::log10(z3) << '\n';
std::complex<double> z4(-100, -0.0); // the other side of the cut
std::cout << "log10" << z4 << " (the other side of the cut) = "
<< std::log10(z4) << '\n'
<< "(note: pi/log(10) = " << acos(-1)/log(10) << ")\n";
}
```
Output:
```
2*log10(0,1) = (0,1.36438)
4*log10(0.707107,0.707107) = (0,1.36438)
log10(-100,0) = (2,1.36438)
log10(-100,-0) (the other side of the cut) = (2,-1.36438)
(note: pi/log(10) = 1.36438)
```
### See also
| | |
| --- | --- |
| [log(std::complex)](log "cpp/numeric/complex/log") | complex natural logarithm with the branch cuts along the negative real axis (function template) |
| [log10log10flog10l](../math/log10 "cpp/numeric/math/log10")
(C++11)(C++11) | computes common (base *10*) logarithm (\({\small \log\_{10}{x} }\)log10(x)) (function) |
| [log10(std::valarray)](../valarray/log10 "cpp/numeric/valarray/log10") | applies the function `[std::log10](../math/log10 "cpp/numeric/math/log10")` to each element of valarray (function template) |
cpp std::complex<T>::operator+=,-=,*=,/= std::complex<T>::operator+=,-=,\*=,/=
=====================================
| | | |
| --- | --- | --- |
| Primary template `complex<T>` | | |
| | (1) | |
|
```
complex& operator+=( const T& other );
```
| (until C++20) |
|
```
constexpr complex& operator+=( const T& other );
```
| (since C++20) |
| | (2) | |
|
```
complex& operator-=( const T& other );
```
| (until C++20) |
|
```
constexpr complex& operator-=( const T& other );
```
| (since C++20) |
| | (3) | |
|
```
complex& operator*=( const T& other );
```
| (until C++20) |
|
```
constexpr complex& operator*=( const T& other );
```
| (since C++20) |
| | (4) | |
|
```
complex& operator/=( const T& other );
```
| (until C++20) |
|
```
constexpr complex& operator/=( const T& other );
```
| (since C++20) |
| Specialization `complex<float>` | | |
| | (1) | |
|
```
complex& operator+=( float other );
```
| (until C++20) |
|
```
constexpr complex& operator+=( float other );
```
| (since C++20) |
| | (2) | |
|
```
complex& operator-=( float other );
```
| (until C++20) |
|
```
constexpr complex& operator-=( float other );
```
| (since C++20) |
| | (3) | |
|
```
complex& operator*=( float other );
```
| (until C++20) |
|
```
constexpr complex& operator*=( float other );
```
| (since C++20) |
| | (4) | |
|
```
complex& operator/=( float other );
```
| (until C++20) |
|
```
constexpr complex& operator/=( float other );
```
| (since C++20) |
| Specialization `complex<double>` | | |
| | (1) | |
|
```
complex& operator+=( double other );
```
| (until C++20) |
|
```
constexpr complex& operator+=( double other );
```
| (since C++20) |
| | (2) | |
|
```
complex& operator-=( double other );
```
| (until C++20) |
|
```
constexpr complex& operator-=( double other );
```
| (since C++20) |
| | (3) | |
|
```
complex& operator*=( double other );
```
| (until C++20) |
|
```
constexpr complex& operator*=( double other );
```
| (since C++20) |
| | (4) | |
|
```
complex& operator/=( double other );
```
| (until C++20) |
|
```
constexpr complex& operator/=( double other );
```
| (since C++20) |
| Specialization `complex<long double>` | | |
| | (1) | |
|
```
complex& operator+=( long double other );
```
| (until C++20) |
|
```
constexpr complex& operator+=( long double other );
```
| (since C++20) |
| | (2) | |
|
```
complex& operator-=( long double other );
```
| (until C++20) |
|
```
constexpr complex& operator-=( long double other );
```
| (since C++20) |
| | (3) | |
|
```
complex& operator*=( long double other );
```
| (until C++20) |
|
```
constexpr complex& operator*=( long double other );
```
| (since C++20) |
| | (4) | |
|
```
complex& operator/=( long double other );
```
| (until C++20) |
|
```
constexpr complex& operator/=( long double other );
```
| (since C++20) |
| All specializations | | |
| | (5) | |
|
```
template<class X>
complex& operator+=( const std::complex<X>& other );
```
| (until C++20) |
|
```
template<class X>
constexpr complex& operator+=( const std::complex<X>& other );
```
| (since C++20) |
| | (6) | |
|
```
template<class X>
complex& operator-=( const std::complex<X>& other );
```
| (until C++20) |
|
```
template<class X>
constexpr complex& operator-=( const std::complex<X>& other );
```
| (since C++20) |
| | (7) | |
|
```
template<class X>
complex& operator*=( const std::complex<X>& other );
```
| (until C++20) |
|
```
template<class X>
constexpr complex& operator*=( const std::complex<X>& other );
```
| (since C++20) |
| | (8) | |
|
```
template<class X>
complex& operator/=( const std::complex<X>& other );
```
| (until C++20) |
|
```
template<class X>
constexpr complex& operator/=( const std::complex<X>& other );
```
| (since C++20) |
Implements the compound assignment operators for complex arithmetic and for mixed complex/scalar arithmetic. Scalar arguments are treated as complex numbers with the real part equal to the argument and the imaginary part set to zero.
1,5) Adds `other` to `*this`.
2,6) Subtracts `other` from `*this`.
3,7) Multiplies `*this` by `other`.
4,8) Divides `*this` by `other`. ### Parameters
| | | |
| --- | --- | --- |
| other | - | a complex or scalar value of matching type (`float`, `double`, `long double`) |
### Return value
`*this`.
### See also
| | |
| --- | --- |
| [operator+operator-](operator_arith2 "cpp/numeric/complex/operator arith2") | applies unary operators to complex numbers (function template) |
| [operator+operator-operator\*operator/](operator_arith3 "cpp/numeric/complex/operator arith3") | performs complex number arithmetics on two complex values or a complex and a scalar (function template) |
cpp std::acos(std::complex) std::acos(std::complex)
=======================
| Defined in header `[<complex>](../../header/complex "cpp/header/complex")` | | |
| --- | --- | --- |
|
```
template< class T >
complex<T> acos( const complex<T>& z );
```
| | (since C++11) |
Computes complex arc cosine of a complex value `z`. Branch cuts exist outside the interval [โ1 ; +1] along the real axis.
### Parameters
| | | |
| --- | --- | --- |
| z | - | complex value |
### Return value
If no errors occur, complex arc cosine of `z` is returned, in the range of a strip unbounded along the imaginary axis and in the interval [0; +ฯ] along the real axis.
### Error handling and special values
Errors are reported consistent with `[math\_errhandling](../math/math_errhandling "cpp/numeric/math/math errhandling")`.
If the implementation supports IEEE floating-point arithmetic,
* `[std::acos](http://en.cppreference.com/w/cpp/numeric/math/acos)([std::conj](http://en.cppreference.com/w/cpp/numeric/complex/conj)(z)) == [std::conj](http://en.cppreference.com/w/cpp/numeric/complex/conj)([std::acos](http://en.cppreference.com/w/cpp/numeric/math/acos)(z))`
* If `z` is `(ยฑ0,+0)`, the result is `(ฯ/2,-0)`
* If `z` is `(ยฑ0,NaN)`, the result is `(ฯ/2,NaN)`
* If `z` is `(x,+โ)` (for any finite x), the result is `(ฯ/2,-โ)`
* If `z` is `(x,NaN)` (for any nonzero finite x), the result is `(NaN,NaN)` and `[FE\_INVALID](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` may be raised.
* If `z` is `(-โ,y)` (for any positive finite y), the result is `(ฯ,-โ)`
* If `z` is `(+โ,y)` (for any positive finite y), the result is `(+0,-โ)`
* If `z` is `(-โ,+โ)`, the result is `(3ฯ/4,-โ)`
* If `z` is `(+โ,+โ)`, the result is `(ฯ/4,-โ)`
* If `z` is `(ยฑโ,NaN)`, the result is `(NaN,ยฑโ)` (the sign of the imaginary part is unspecified)
* If `z` is `(NaN,y)` (for any finite y), the result is `(NaN,NaN)` and `[FE\_INVALID](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` may be raised
* If `z` is `(NaN,+โ)`, the result is `(NaN,-โ)`
* If `z` is `(NaN,NaN)`, the result is `(NaN,NaN)`
### Notes
Inverse cosine (or arc cosine) is a multivalued function and requires a branch cut on the complex plane. The branch cut is conventionally placed at the line segments (-โ,-1) and (1,โ) of the real axis. The mathematical definition of the principal value of arc cosine is acos z =
1/2ฯ + *i*ln(*i*z + โ1-z2
) For any z, acos(z) = ฯ - acos(-z).
### Example
```
#include <iostream>
#include <cmath>
#include <complex>
int main()
{
std::cout << std::fixed;
std::complex<double> z1(-2, 0);
std::cout << "acos" << z1 << " = " << std::acos(z1) << '\n';
std::complex<double> z2(-2, -0.0);
std::cout << "acos" << z2 << " (the other side of the cut) = "
<< std::acos(z2) << '\n';
// for any z, acos(z) = pi - acos(-z)
const double pi = std::acos(-1);
std::complex<double> z3 = pi - std::acos(z2);
std::cout << "cos(pi - acos" << z2 << ") = " << std::cos(z3) << '\n';
}
```
Output:
```
acos(-2.000000,0.000000) = (3.141593,-1.316958)
acos(-2.000000,-0.000000) (the other side of the cut) = (3.141593,1.316958)
cos(pi - acos(-2.000000,-0.000000)) = (2.000000,0.000000)
```
### See also
| | |
| --- | --- |
| [asin(std::complex)](asin "cpp/numeric/complex/asin")
(C++11) | computes arc sine of a complex number (\({\small\arcsin{z} }\)arcsin(z)) (function template) |
| [atan(std::complex)](atan "cpp/numeric/complex/atan")
(C++11) | computes arc tangent of a complex number (\({\small\arctan{z} }\)arctan(z)) (function template) |
| [cos(std::complex)](cos "cpp/numeric/complex/cos") | computes cosine of a complex number (\({\small\cos{z} }\)cos(z)) (function template) |
| [acosacosfacosl](../math/acos "cpp/numeric/math/acos")
(C++11)(C++11) | computes arc cosine (\({\small\arccos{x} }\)arccos(x)) (function) |
| [acos(std::valarray)](../valarray/acos "cpp/numeric/valarray/acos") | applies the function `[std::acos](../math/acos "cpp/numeric/math/acos")` to each element of valarray (function template) |
| [C documentation](https://en.cppreference.com/w/c/numeric/complex/cacos "c/numeric/complex/cacos") for `cacos` |
cpp operator==,!=(std::complex)
operator==,!=(std::complex)
===========================
| Defined in header `[<complex>](../../header/complex "cpp/header/complex")` | | |
| --- | --- | --- |
| | (1) | |
|
```
template< class T >
bool operator==( const complex<T>& lhs, const complex<T>& rhs );
```
| (until C++14) |
|
```
template< class T >
constexpr bool operator==( const complex<T>& lhs, const complex<T>& rhs );
```
| (since C++14) |
| | (2) | |
|
```
template< class T >
bool operator==( const complex<T>& lhs, const T& rhs );
```
| (until C++14) |
|
```
template< class T >
constexpr bool operator==( const complex<T>& lhs, const T& rhs );
```
| (since C++14) |
| | (3) | |
|
```
template< class T >
bool operator==( const T& lhs, const complex<T>& rhs );
```
| (until C++14) |
|
```
template< class T >
constexpr bool operator==( const T& lhs, const complex<T>& rhs );
```
| (since C++14) (until C++20) |
| | (4) | |
|
```
template< class T >
bool operator!=( const complex<T>& lhs, const complex<T>& rhs );
```
| (until C++14) |
|
```
template< class T >
constexpr bool operator!=( const complex<T>& lhs, const complex<T>& rhs );
```
| (since C++14) (until C++20) |
| | (5) | |
|
```
template< class T >
bool operator!=( const complex<T>& lhs, const T& rhs );
```
| (until C++14) |
|
```
template< class T >
constexpr bool operator!=( const complex<T>& lhs, const T& rhs );
```
| (since C++14) (until C++20) |
| | (6) | |
|
```
template< class T >
bool operator!=( const T& lhs, const complex<T>& rhs );
```
| (until C++14) |
|
```
template< class T >
constexpr bool operator!=( const T& lhs, const complex<T>& rhs );
```
| (since C++14) (until C++20) |
Compares two complex numbers. Scalar arguments are treated as complex numbers with the real part equal to the argument and the imaginary part set to zero.
1-3) Compares `lhs` and `rhs` for equality.
4-6) Compares `lhs` and `rhs` for inequality.
| | |
| --- | --- |
| The `!=` operator is [synthesized](../../language/operators#Relational_operators "cpp/language/operators") from `operator==`. | (since C++20) |
### Parameters
| | | |
| --- | --- | --- |
| lhs, rhs | - | the arguments to compare: either both complex numbers or one complex and one scalar of matching type (`float`, `double`, `long double`) |
### Return value
1-3) `true` if respective parts of `lhs` are equal to `rhs`, `false` otherwise.
4-6) `!(lhs == rhs)`
### Example
```
#include <complex>
int main()
{
using std::operator""i; // or: using namespace std::complex_literals;
static_assert(1.0i == 1.0i);
static_assert(2.0i != 1.0i);
constexpr std::complex z(1.0, 0.0);
static_assert(z == 1.0);
static_assert(1.0 == z);
static_assert(2.0 != z);
static_assert(z != 2.0);
}
```
cpp std::atanh(std::complex) std::atanh(std::complex)
========================
| Defined in header `[<complex>](../../header/complex "cpp/header/complex")` | | |
| --- | --- | --- |
|
```
template< class T >
complex<T> atanh( const complex<T>& z );
```
| | (since C++11) |
Computes the complex arc hyperbolic tangent of `z` with branch cuts outside the interval [โ1; +1] along the real axis.
### Parameters
| | | |
| --- | --- | --- |
| z | - | complex value |
### Return value
If no errors occur, the complex arc hyperbolic tangent of `z` is returned, in the range of a half-strip mathematically unbounded along the real axis and in the interval [โiฯ/2; +iฯ/2] along the imaginary axis.
### Error handling and special values
Errors are reported consistent with `[math\_errhandling](../math/math_errhandling "cpp/numeric/math/math errhandling")`.
If the implementation supports IEEE floating-point arithmetic,
* `[std::atanh](http://en.cppreference.com/w/cpp/numeric/math/atanh)([std::conj](http://en.cppreference.com/w/cpp/numeric/complex/conj)(z)) == [std::conj](http://en.cppreference.com/w/cpp/numeric/complex/conj)([std::atanh](http://en.cppreference.com/w/cpp/numeric/math/atanh)(z))`
* `[std::atanh](http://en.cppreference.com/w/cpp/numeric/math/atanh)(-z) == -[std::atanh](http://en.cppreference.com/w/cpp/numeric/math/atanh)(z)`
* If `z` is `(+0,+0)`, the result is `(+0,+0)`
* If `z` is `(+0,NaN)`, the result is `(+0,NaN)`
* If `z` is `(+1,+0)`, the result is `(+โ,+0)` and `[FE\_DIVBYZERO](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` is raised
* If `z` is `(x,+โ)` (for any finite positive x), the result is `(+0,ฯ/2)`
* If `z` is `(x,NaN)` (for any finite nonzero x), the result is `(NaN,NaN)` and `[FE\_INVALID](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` may be raised
* If `z` is `(+โ,y)` (for any finite positive y), the result is `(+0,ฯ/2)`
* If `z` is `(+โ,+โ)`, the result is `(+0,ฯ/2)`
* If `z` is `(+โ,NaN)`, the result is `(+0,NaN)`
* If `z` is `(NaN,y)` (for any finite y), the result is `(NaN,NaN)` and `[FE\_INVALID](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` may be raised
* If `z` is `(NaN,+โ)`, the result is `(ยฑ0,ฯ/2)` (the sign of the real part is unspecified)
* If `z` is `(NaN,NaN)`, the result is `(NaN,NaN)`
### Notes
Although the C++ standard names this function "complex arc hyperbolic tangent", the inverse functions of the hyperbolic functions are the area functions. Their argument is the area of a hyperbolic sector, not an arc. The correct name is "complex inverse hyperbolic tangent", and, less common, "complex area hyperbolic tangent".
Inverse hyperbolic tangent is a multivalued function and requires a branch cut on the complex plane. The branch cut is conventionally placed at the line segments (-โ,-1] and [+1,+โ) of the real axis. The mathematical definition of the principal value of the inverse hyperbolic tangent is atanh z =
ln(1+z)-ln(1-z)/2.
For any z, atanh(z) =
atan(iz)/i ### Example
```
#include <iostream>
#include <complex>
int main()
{
std::cout << std::fixed;
std::complex<double> z1(2, 0);
std::cout << "atanh" << z1 << " = " << std::atanh(z1) << '\n';
std::complex<double> z2(2, -0.0);
std::cout << "atanh" << z2 << " (the other side of the cut) = "
<< std::atanh(z2) << '\n';
// for any z, atanh(z) = atanh(iz)/i
std::complex<double> z3(1,2);
std::complex<double> i(0,1);
std::cout << "atanh" << z3 << " = " << std::atanh(z3) << '\n'
<< "atan" << z3*i << "/i = " << std::atan(z3*i)/i << '\n';
}
```
Output:
```
atanh(2.000000,0.000000) = (0.549306,1.570796)
atanh(2.000000,-0.000000) (the other side of the cut) = (0.549306,-1.570796)
atanh(1.000000,2.000000) = (0.173287,1.178097)
atan(-2.000000,1.000000)/i = (0.173287,1.178097)
```
### See also
| | |
| --- | --- |
| [asinh(std::complex)](asinh "cpp/numeric/complex/asinh")
(C++11) | computes area hyperbolic sine of a complex number (\({\small\operatorname{arsinh}{z} }\)arsinh(z)) (function template) |
| [acosh(std::complex)](acosh "cpp/numeric/complex/acosh")
(C++11) | computes area hyperbolic cosine of a complex number (\({\small\operatorname{arcosh}{z} }\)arcosh(z)) (function template) |
| [tanh(std::complex)](tanh "cpp/numeric/complex/tanh") | computes hyperbolic tangent of a complex number (\({\small\tanh{z} }\)tanh(z)) (function template) |
| [atanhatanhfatanhl](../math/atanh "cpp/numeric/math/atanh")
(C++11)(C++11)(C++11) | computes the inverse hyperbolic tangent (\({\small\operatorname{artanh}{x} }\)artanh(x)) (function) |
| [C documentation](https://en.cppreference.com/w/c/numeric/complex/catanh "c/numeric/complex/catanh") for `catanh` |
| programming_docs |
cpp std::complex<T>::complex std::complex<T>::complex
========================
| | | |
| --- | --- | --- |
| Primary template `complex<T>` | | |
|
```
complex( const T& re = T(), const T& im = T() );
```
| (1) | (until C++14) |
|
```
constexpr complex( const T& re = T(), const T& im = T() );
```
| (1) | (since C++14) |
|
```
complex( const complex& other );
```
| (2) | (until C++14) |
|
```
constexpr complex( const complex& other );
```
| (2) | (since C++14) |
|
```
template< class X >
complex( const complex<X>& other);
```
| (3) | (until C++14) |
|
```
template< class X >
constexpr complex( const complex<X>& other);
```
| (3) | (since C++14) |
| Specialization `complex<float>` | | |
|
```
complex( float re = 0.0f, float im = 0.0f );
```
| (1) | (until C++11) |
|
```
constexpr complex(float re = 0.0f, float im = 0.0f);
```
| (1) | (since C++11) |
|
```
explicit complex( const complex<double>& other );
explicit complex( const complex<long double>& other );
```
| (3) | (until C++11) |
|
```
explicit constexpr complex( const complex<double>& other );
explicit constexpr complex( const complex<long double>& other );
```
| (3) | (since C++11) |
| Specialization `complex<double>` | | |
|
```
complex( double re = 0.0, double im = 0.0 );
```
| (1) | (until C++11) |
|
```
constexpr complex( double re = 0.0, double im = 0.0 );
```
| (1) | (since C++11) |
|
```
complex( const complex<float>& other );
explicit complex( const complex<long double>& other );
```
| (3) | (until C++11) |
|
```
constexpr complex( const complex<float>& other );
explicit constexpr complex( const complex<long double>& other );
```
| (3) | (since C++11) |
| Specialization `complex<long double>` | | |
|
```
complex( long double re = 0.0L, long double im = 0.0L );
```
| (1) | (until C++11) |
|
```
constexpr complex( long double re = 0.0L, long double im = 0.0L );
```
| (1) | (since C++11) |
|
```
complex( const complex<float>& other );
complex( const complex<double>& other );
```
| (3) | (until C++11) |
|
```
constexpr complex( const complex<float>& other );
constexpr complex( const complex<double>& other );
```
| (3) | (since C++11) |
Constructs the `[std::complex](../complex "cpp/numeric/complex")` object.
1) Constructs the complex number from real and imaginary parts.
2) Copy constructor. Constructs the object with the copy of the contents of `other`. The copy constructor is implicit in the standard specializations.
3) [Converting constructor](../../language/converting_constructor "cpp/language/converting constructor"). Constructs the object from a complex number of a different type. ### Parameters
| | | |
| --- | --- | --- |
| re | - | the real part |
| im | - | the imaginary part |
| other | - | another complex to use as source |
### See also
| | |
| --- | --- |
| [operator=](operator= "cpp/numeric/complex/operator=") | assigns the contents (public member function) |
| [operator""ifoperator""ioperator""il](operator%22%22i "cpp/numeric/complex/operator\"\"i")
(C++14) | A `[std::complex](../complex "cpp/numeric/complex")` literal representing pure imaginary number (function) |
| [C documentation](https://en.cppreference.com/w/c/numeric/complex/CMPLX "c/numeric/complex/CMPLX") for `CMPLX` |
cpp std::sin(std::complex) std::sin(std::complex)
======================
| Defined in header `[<complex>](../../header/complex "cpp/header/complex")` | | |
| --- | --- | --- |
|
```
template< class T >
complex<T> sin( const complex<T>& z );
```
| | |
Computes complex sine of a complex value `z`.
### Parameters
| | | |
| --- | --- | --- |
| z | - | complex value |
### Return value
If no errors occur, the complex sine of `z` is returned.
Errors and special cases are handled as if the operation is implemented by `-i * [std::sinh](sinh "cpp/numeric/complex/sinh")(i*z)`, where `i` is the imaginary unit.
### Notes
The sine is an entire function on the complex plane, and has no branch cuts. Mathematical definition of the sine is sin z =
eiz-e-iz/2i ### Example
```
#include <iostream>
#include <cmath>
#include <complex>
int main()
{
std::cout << std::fixed;
std::complex<double> z(1, 0); // behaves like real sine along the real line
std::cout << "sin" << z << " = " << std::sin(z)
<< " ( sin(1) = " << std::sin(1) << ")\n";
std::complex<double> z2(0, 1); // behaves like sinh along the imaginary line
std::cout << "sin" << z2 << " = " << std::sin(z2)
<< " (sinh(1) = " << std::sinh(1) << ")\n";
}
```
Output:
```
sin(1.000000,0.000000) = (0.841471,0.000000) ( sin(1) = 0.841471)
sin(0.000000,1.000000) = (0.000000,1.175201) (sinh(1) = 1.175201)
```
### See also
| | |
| --- | --- |
| [cos(std::complex)](cos "cpp/numeric/complex/cos") | computes cosine of a complex number (\({\small\cos{z} }\)cos(z)) (function template) |
| [tan(std::complex)](tan "cpp/numeric/complex/tan") | computes tangent of a complex number (\({\small\tan{z} }\)tan(z)) (function template) |
| [asin(std::complex)](asin "cpp/numeric/complex/asin")
(C++11) | computes arc sine of a complex number (\({\small\arcsin{z} }\)arcsin(z)) (function template) |
| [sinsinfsinl](../math/sin "cpp/numeric/math/sin")
(C++11)(C++11) | computes sine (\({\small\sin{x} }\)sin(x)) (function) |
| [sin(std::valarray)](../valarray/sin "cpp/numeric/valarray/sin") | applies the function `[std::sin](../math/sin "cpp/numeric/math/sin")` to each element of valarray (function template) |
| [C documentation](https://en.cppreference.com/w/c/numeric/complex/csin "c/numeric/complex/csin") for `csin` |
cpp std::tan(std::complex) std::tan(std::complex)
======================
| Defined in header `[<complex>](../../header/complex "cpp/header/complex")` | | |
| --- | --- | --- |
|
```
template< class T >
complex<T> tan( const complex<T>& z );
```
| | |
Computes complex tangent of a complex value `z`.
### Parameters
| | | |
| --- | --- | --- |
| z | - | complex value |
### Return value
If no errors occur, the complex tangent of `z` is returned.
Errors and special cases are handled as if the operation is implemented by `-i * [std::tanh](tanh "cpp/numeric/complex/tanh")(i*z)`, where `i` is the imaginary unit.
### Notes
Tangent is an analytical function on the complex plain and has no branch cuts. It is periodic with respect to the real component, with period ฯi, and has poles of the first order along the real line, at coordinates (ฯ(1/2 + n), 0). However no common floating-point representation is able to represent ฯ/2 exactly, thus there is no value of the argument for which a pole error occurs. Mathematical definition of the tangent is tan z =
i(e-iz-eiz)/e-iz+eiz ### Example
```
#include <iostream>
#include <cmath>
#include <complex>
int main()
{
std::cout << std::fixed;
std::complex<double> z(1, 0); // behaves like real tangent along the real line
std::cout << "tan" << z << " = " << std::tan(z)
<< " ( tan(1) = " << std::tan(1) << ")\n";
std::complex<double> z2(0, 1); // behaves like tanh along the imaginary line
std::cout << "tan" << z2 << " = " << std::tan(z2)
<< " (tanh(1) = " << std::tanh(1) << ")\n";
}
```
Output:
```
tan(1.000000,0.000000) = (1.557408,0.000000) ( tan(1) = 1.557408)
tan(0.000000,1.000000) = (0.000000,0.761594) (tanh(1) = 0.761594)
```
### See also
| | |
| --- | --- |
| [sin(std::complex)](sin "cpp/numeric/complex/sin") | computes sine of a complex number (\({\small\sin{z} }\)sin(z)) (function template) |
| [cos(std::complex)](cos "cpp/numeric/complex/cos") | computes cosine of a complex number (\({\small\cos{z} }\)cos(z)) (function template) |
| [atan(std::complex)](atan "cpp/numeric/complex/atan")
(C++11) | computes arc tangent of a complex number (\({\small\arctan{z} }\)arctan(z)) (function template) |
| [tantanftanl](../math/tan "cpp/numeric/math/tan")
(C++11)(C++11) | computes tangent (\({\small\tan{x} }\)tan(x)) (function) |
| [tan(std::valarray)](../valarray/tan "cpp/numeric/valarray/tan") | applies the function `[std::tan](../math/tan "cpp/numeric/math/tan")` to each element of valarray (function template) |
| [C documentation](https://en.cppreference.com/w/c/numeric/complex/ctan "c/numeric/complex/ctan") for `ctan` |
cpp std::proj(std::complex) std::proj(std::complex)
=======================
| Defined in header `[<complex>](../../header/complex "cpp/header/complex")` | | |
| --- | --- | --- |
|
```
template< class T >
std::complex<T> proj( const std::complex<T>& z );
```
| (1) | (since C++11) |
|
```
std::complex<long double> proj( long double z );
```
| (2) | (since C++11) |
|
```
template< class DoubleOrInteger >
std::complex<double> proj( DoubleOrInteger z );
```
| (3) | (since C++11) |
|
```
std::complex<float> proj( float z );
```
| (4) | (since C++11) |
Returns the projection of the complex number `z` onto the [Riemann sphere](https://en.wikipedia.org/wiki/Riemann_sphere "enwiki:Riemann sphere").
For most `z`, `std::proj(z)==z`, but all complex infinities, even the numbers where one component is infinite and the other is NaN, become positive real infinity, `([INFINITY](http://en.cppreference.com/w/cpp/numeric/math/INFINITY), 0.0)` or `([INFINITY](http://en.cppreference.com/w/cpp/numeric/math/INFINITY), -0.0)`. The sign of the imaginary (zero) component is the sign of `[std::imag](http://en.cppreference.com/w/cpp/numeric/complex/imag2)(z)`.
Additional overloads are provided for `float`, `double`, `long double`, and all integer types, which are treated as complex numbers with positive zero imaginary component.
### Parameters
| | | |
| --- | --- | --- |
| z | - | complex value |
### Return value
the projection of `z` onto the Riemann sphere.
### Notes
The `proj` function helps model the Riemann sphere by mapping all infinities to one (give or take the sign of the imaginary zero), and should be used just before any operation, especially comparisons, that might give spurious results for any of the other infinities.
### Example
```
#include <iostream>
#include <complex>
int main()
{
std::complex<double> c1(1, 2);
std::cout << "proj" << c1 << " = " << std::proj(c1) << '\n';
std::complex<double> c2(INFINITY, -1);
std::cout << "proj" << c2 << " = " << std::proj(c2) << '\n';
std::complex<double> c3(0, -INFINITY);
std::cout << "proj" << c3 << " = " << std::proj(c3) << '\n';
}
```
Output:
```
proj(1,2) = (1,2)
proj(inf,-1) = (inf,-0)
proj(0,-inf) = (inf,-0)
```
### See also
| | |
| --- | --- |
| [abs(std::complex)](abs "cpp/numeric/complex/abs") | returns the magnitude of a complex number (function template) |
| [norm](norm "cpp/numeric/complex/norm") | returns the squared magnitude (function template) |
| [polar](polar "cpp/numeric/complex/polar") | constructs a complex number from magnitude and phase angle (function template) |
| [C documentation](https://en.cppreference.com/w/c/numeric/complex/cproj "c/numeric/complex/cproj") for `cproj` |
cpp std::conj(std::complex) std::conj(std::complex)
=======================
| Defined in header `[<complex>](../../header/complex "cpp/header/complex")` | | |
| --- | --- | --- |
| | (1) | |
|
```
template< class T >
std::complex<T> conj( const std::complex<T>& z );
```
| (until C++20) |
|
```
template< class T >
constexpr std::complex<T> conj( const std::complex<T>& z );
```
| (since C++20) |
| | (2) | |
|
```
std::complex<float> conj( float z );
template< class DoubleOrInteger >
std::complex<double> conj( DoubleOrInteger z );
std::complex<long double> conj( long double z );
```
| (since C++11) (until C++20) |
|
```
constexpr std::complex<float> conj( float z );
template< class DoubleOrInteger >
constexpr std::complex<double> conj( DoubleOrInteger z );
constexpr std::complex<long double> conj( long double z );
```
| (since C++20) |
1) Computes the [complex conjugate](https://en.wikipedia.org/wiki/Complex_conjugate "enwiki:Complex conjugate") of `z` by reversing the sign of the imaginary part.
| | |
| --- | --- |
| 2) Additional overloads are provided for `float`, `double`, `long double`, and all integer types, which are treated as complex numbers with zero imaginary component. | (since C++11) |
### Parameters
| | | |
| --- | --- | --- |
| z | - | complex value |
### Return value
The complex conjugate of `z`.
### Example
```
#include <iostream>
#include <complex>
int main()
{
std::complex<double> z(1,2);
std::cout << "The conjugate of " << z << " is " << std::conj(z) << '\n'
<< "Their product is " << z*std::conj(z) << '\n';
}
```
Output:
```
The conjugate of (1,2) is (1,-2)
Their product is (5,0)
```
### See also
| | |
| --- | --- |
| [abs(std::complex)](abs "cpp/numeric/complex/abs") | returns the magnitude of a complex number (function template) |
| [norm](norm "cpp/numeric/complex/norm") | returns the squared magnitude (function template) |
| [polar](polar "cpp/numeric/complex/polar") | constructs a complex number from magnitude and phase angle (function template) |
| [C documentation](https://en.cppreference.com/w/c/numeric/complex/conj "c/numeric/complex/conj") for `conj` |
cpp std::fetestexcept std::fetestexcept
=================
| Defined in header `[<cfenv>](../../header/cfenv "cpp/header/cfenv")` | | |
| --- | --- | --- |
|
```
int fetestexcept( int excepts );
```
| | (since C++11) |
Determines which of the specified subset of the floating point exceptions are currently set. The argument `excepts` is a bitwise OR of the [floating point exception macros](fe_exceptions "cpp/numeric/fenv/FE exceptions").
### Parameters
| | | |
| --- | --- | --- |
| excepts | - | bitmask listing the exception flags to test |
### Return value
Bitwise OR of the floating-point exception macros that are both included in `excepts` and correspond to floating-point exceptions currently set.
### Example
```
#include <iostream>
#include <cfenv>
#include <cmath>
#pragma STDC FENV_ACCESS ON
volatile double zero = 0.0; // volatile not needed where FENV_ACCESS is supported
volatile double one = 1.0; // volatile not needed where FENV_ACCESS is supported
int main()
{
std::feclearexcept(FE_ALL_EXCEPT);
std::cout << "1.0/0.0 = " << 1.0 / zero << '\n';
if(std::fetestexcept(FE_DIVBYZERO)) {
std::cout << "division by zero reported\n";
} else {
std::cout << "divsion by zero not reported\n";
}
std::feclearexcept(FE_ALL_EXCEPT);
std::cout << "1.0/10 = " << one/10 << '\n';
if(std::fetestexcept(FE_INEXACT)) {
std::cout << "inexact result reported\n";
} else {
std::cout << "inexact result not reported\n";
}
std::feclearexcept(FE_ALL_EXCEPT);
std::cout << "sqrt(-1) = " << std::sqrt(-1) << '\n';
if(std::fetestexcept(FE_INVALID)) {
std::cout << "invalid result reported\n";
} else {
std::cout << "invalid result not reported\n";
}
}
```
Output:
```
1.0/0.0 = inf
division by zero reported
1.0/10 = 0.1
inexact result reported
sqrt(-1) = -nan
invalid result reported
```
### See also
| | |
| --- | --- |
| [feclearexcept](feclearexcept "cpp/numeric/fenv/feclearexcept")
(C++11) | clears the specified floating-point status flags (function) |
| [C documentation](https://en.cppreference.com/w/c/numeric/fenv/fetestexcept "c/numeric/fenv/fetestexcept") for `fetestexcept` |
cpp std::fegetexceptflag, std::fesetexceptflag std::fegetexceptflag, std::fesetexceptflag
==========================================
| Defined in header `[<cfenv>](../../header/cfenv "cpp/header/cfenv")` | | |
| --- | --- | --- |
|
```
int fegetexceptflag( std::fexcept_t* flagp, int excepts );
```
| (1) | (since C++11) |
|
```
int fesetexceptflag( const std::fexcept_t* flagp, int excepts );
```
| (2) | (since C++11) |
1) Attempts to obtain the full contents of the floating-point exception flags that are listed in the bitmask argument `excepts`, which is a bitwise OR of the [floating point exception macros](fe_exceptions "cpp/numeric/fenv/FE exceptions").
2) Attempts to copy the full contents of the floating-point exception flags that are listed in `excepts` from `flagp` into the floating-point environment. Does not raise any exceptions, only modifies the flags.
The full contents of a floating-point exception flag is not necessarily a boolean value indicating whether the exception is raised or cleared. For example, it may be a struct which includes the boolean status and the address of the code that triggered the exception. These functions obtain all such content and obtain/store it in `flagp` in implementation-defined format.
### Parameters
| | | |
| --- | --- | --- |
| flagp | - | pointer to an `std::fexcept_t` object where the flags will be stored or read from |
| excepts | - | bitmask listing the exception flags to get/set |
### Return value
`โ0โ` on success, non-zero otherwise.
### See also
| |
| --- |
| [C documentation](https://en.cppreference.com/w/c/numeric/fenv/feexceptflag "c/numeric/fenv/feexceptflag") for `fegetexceptflag, fesetexceptflag` |
cpp std::feraiseexcept std::feraiseexcept
==================
| Defined in header `[<cfenv>](../../header/cfenv "cpp/header/cfenv")` | | |
| --- | --- | --- |
|
```
int feraiseexcept( int excepts );
```
| | (since C++11) |
Attempts to raise all floating point exceptions listed in `excepts` (a bitwise OR of the [floating point exception macros](fe_exceptions "cpp/numeric/fenv/FE exceptions")). If one of the exceptions is `[FE\_OVERFLOW](fe_exceptions "cpp/numeric/fenv/FE exceptions")` or `[FE\_UNDERFLOW](http://en.cppreference.com/w/cpp/numeric/fenv/FE_exceptions)`, this function may additionally raise `[FE\_INEXACT](fe_exceptions "cpp/numeric/fenv/FE exceptions")`. The order in which the exceptions are raised is unspecified, except that `[FE\_OVERFLOW](fe_exceptions "cpp/numeric/fenv/FE exceptions")` and `[FE\_UNDERFLOW](http://en.cppreference.com/w/cpp/numeric/fenv/FE_exceptions)` are always raised before `[FE\_INEXACT](fe_exceptions "cpp/numeric/fenv/FE exceptions")`.
### Parameters
| | | |
| --- | --- | --- |
| excepts | - | bitmask listing the exception flags to raise |
### Return value
`โ0โ` if all listed exceptions were raised, non-zero value otherwise.
### Example
```
#include <iostream>
#include <cfenv>
#pragma STDC FENV_ACCESS ON
int main()
{
std::feclearexcept(FE_ALL_EXCEPT);
int r = std::feraiseexcept(FE_UNDERFLOW | FE_DIVBYZERO);
std::cout << "Raising divbyzero and underflow simultaneously "
<< (r?"fails":"succeeds") << " and results in\n";
int e = std::fetestexcept(FE_ALL_EXCEPT);
if (e & FE_DIVBYZERO) {
std::cout << "division by zero\n";
}
if (e & FE_INEXACT) {
std::cout << "inexact\n";
}
if (e & FE_INVALID) {
std::cout << "invalid\n";
}
if (e & FE_UNDERFLOW) {
std::cout << "underflow\n";
}
if (e & FE_OVERFLOW) {
std::cout << "overflow\n";
}
}
```
Output:
```
Raising divbyzero and underflow simultaneously succeeds and results in
division by zero
underflow
```
### See also
| | |
| --- | --- |
| [feclearexcept](feclearexcept "cpp/numeric/fenv/feclearexcept")
(C++11) | clears the specified floating-point status flags (function) |
| [fetestexcept](fetestexcept "cpp/numeric/fenv/fetestexcept")
(C++11) | determines which of the specified floating-point status flags are set (function) |
| [C documentation](https://en.cppreference.com/w/c/numeric/fenv/feraiseexcept "c/numeric/fenv/feraiseexcept") for `feraiseexcept` |
| programming_docs |
cpp std::fegetenv, std::fesetenv std::fegetenv, std::fesetenv
============================
| Defined in header `[<cfenv>](../../header/cfenv "cpp/header/cfenv")` | | |
| --- | --- | --- |
|
```
int fegetenv( std::fenv_t* envp )
```
| (1) | (since C++11) |
|
```
int fesetenv( const std::fenv_t* envp );
```
| (2) | (since C++11) |
Manages the status of the floating-point environment.
1) Attempts to store the status of the floating-point environment in the object pointed to by `envp`.
2) Attempts to establish the floating-point environment from the object pointed to by `envp`. The value of that object must be previously obtained by a call to `[std::feholdexcept](feholdexcept "cpp/numeric/fenv/feholdexcept")` or `std::fegetenv` or be a floating-point macro constant. If any of the floating-point status flags are set in `envp`, they become set in the environment (and are then testable with `[std::fetestexcept](fetestexcept "cpp/numeric/fenv/fetestexcept")`), but the corresponding floating-point exceptions are not raised (execution continues uninterrupted) ### Parameters
| | | |
| --- | --- | --- |
| envp | - | pointer to the object of type `std::fenv_t` which holds the status of the floating-point environment |
### Return value
`โ0โ` on success, non-zero otherwise.
### See also
| | |
| --- | --- |
| [feholdexcept](feholdexcept "cpp/numeric/fenv/feholdexcept")
(C++11) | saves the environment, clears all status flags and ignores all future errors (function) |
| [feupdateenv](feupdateenv "cpp/numeric/fenv/feupdateenv")
(C++11) | restores the floating-point environment and raises the previously raise exceptions (function) |
| [FE\_DFL\_ENV](fe_dfl_env "cpp/numeric/fenv/FE DFL ENV")
(C++11) | default floating-point environment (macro constant) |
| [C documentation](https://en.cppreference.com/w/c/numeric/fenv/feenv "c/numeric/fenv/feenv") for `fegetenv, fesetenv` |
cpp FE_DOWNWARD, FE_TONEAREST, FE_TOWARDZERO, FE_UPWARD FE\_DOWNWARD, FE\_TONEAREST, FE\_TOWARDZERO, FE\_UPWARD
=======================================================
| Defined in header `[<cfenv>](../../header/cfenv "cpp/header/cfenv")` | | |
| --- | --- | --- |
|
```
#define FE_DOWNWARD /*implementation defined*/
```
| | (since C++11) |
|
```
#define FE_TONEAREST /*implementation defined*/
```
| | (since C++11) |
|
```
#define FE_TOWARDZERO /*implementation defined*/
```
| | (since C++11) |
|
```
#define FE_UPWARD /*implementation defined*/
```
| | (since C++11) |
Each of these macro constants expands to a nonnegative integer constant expression, which can be used with `[std::fesetround](feround "cpp/numeric/fenv/feround")` and `[std::fegetround](feround "cpp/numeric/fenv/feround")` to indicate one of the supported floating-point rounding modes. The implementation may define additional rounding mode constants in [`<cfenv>`](../../header/cfenv "cpp/header/cfenv"), which should all begin with `FE_` followed by at least one uppercase letter. Each macro is only defined if it is supported.
| Constant | Explanation |
| --- | --- |
| `FE_DOWNWARD` | rounding towards negative infinity |
| `FE_TONEAREST` | rounding towards nearest representable value |
| `FE_TOWARDZERO` | rounding towards zero |
| `FE_UPWARD` | rounding towards positive infinity |
Additional rounding modes may be supported by an implementation.
The current rounding mode affects the following:
* results of floating-point [arithmetic operators](../../language/operator_arithmetic "cpp/language/operator arithmetic") outside of constant expressions
```
double x = 1;
x/10; // 0.09999999999999999167332731531132594682276248931884765625
// or 0.1000000000000000055511151231257827021181583404541015625
```
* results of standard library [mathematical functions](../math "cpp/numeric/math")
```
std::sqrt(2); // 1.41421356237309492343001693370752036571502685546875
// or 1.4142135623730951454746218587388284504413604736328125
```
* floating-point to floating-point implicit conversion and casts
```
double d = 1 + std::numeric_limits<double>::epsilon();
float f = d; // 1.00000000000000000000000
// or 1.00000011920928955078125
```
* string conversions such as `[std::strtod](../../string/byte/strtof "cpp/string/byte/strtof")` or `[std::printf](../../io/c/fprintf "cpp/io/c/fprintf")`
```
std::stof("0.1"); // 0.0999999940395355224609375
// or 0.100000001490116119384765625
```
* the library rounding functions `[std::nearbyint](../math/nearbyint "cpp/numeric/math/nearbyint")`, `[std::rint](../math/rint "cpp/numeric/math/rint")`, `[std::lrint](../math/rint "cpp/numeric/math/rint")`
```
std::lrint(2.1); // 2 or 3
```
The current rounding mode does NOT affect the following:
* floating-point to integer implicit conversion and casts (always towards zero)
* results of floating-point arithmetic operators in expressions executed at compile time (always to nearest)
* the library functions `[std::round](../math/round "cpp/numeric/math/round")`, `[std::lround](../math/round "cpp/numeric/math/round")`, `[std::llround](../math/round "cpp/numeric/math/round")`, `[std::ceil](../math/ceil "cpp/numeric/math/ceil")`, `[std::floor](../math/floor "cpp/numeric/math/floor")`, `[std::trunc](../math/trunc "cpp/numeric/math/trunc")`
As with any [floating-point environment](../fenv "cpp/numeric/fenv") functionality, rounding is only guaranteed if `#pragma STDC FENV_ACCESS ON` is set.
Compilers that do not support the pragma may offer their own ways to support current rounding mode. For example Clang and GCC have the option `-frounding-math` intended to disable optimizations that would change the meaning of rounding-sensitive code.
### Example
```
#include <iostream>
#include <iomanip>
#include <string>
#include <cfenv>
#include <cmath>
int main()
{
#pragma STDC FENV_ACCESS ON
std::fesetround(FE_DOWNWARD);
std::cout << "rounding down: \n" << std::setprecision(50)
<< " pi = " << std::acos(-1.f) << '\n'
<< "stof(\"1.1\") = " << std::stof("1.1") << '\n'
<< " rint(2.1) = " << std::rint(2.1) << "\n\n";
std::fesetround(FE_UPWARD);
std::cout << "rounding up: \n"
<< " pi = " << std::acos(-1.f) << '\n'
<< "stof(\"1.1\") = " << std::stof("1.1") << '\n'
<< " rint(2.1) = " << std::rint(2.1) << '\n';
}
```
Output:
```
rounding down:
pi = 3.141592502593994140625
stof("1.1") = 1.099999904632568359375
rint(2.1) = 2
rounding up:
pi = 3.1415927410125732421875
stof("1.1") = 1.10000002384185791015625
rint(2.1) = 3
```
### See also
| | |
| --- | --- |
| [float\_round\_style](../../types/numeric_limits/float_round_style "cpp/types/numeric limits/float round style") | indicates floating-point rounding modes (enum) |
| [fegetroundfesetround](feround "cpp/numeric/fenv/feround")
(C++11)(C++11) | gets or sets rounding direction (function) |
| [C documentation](https://en.cppreference.com/w/c/numeric/fenv/FE_round "c/numeric/fenv/FE round") for floating-point rounding macros |
cpp std::fegetround, std::fesetround std::fegetround, std::fesetround
================================
| Defined in header `[<cfenv>](../../header/cfenv "cpp/header/cfenv")` | | |
| --- | --- | --- |
|
```
int fesetround( int round )
```
| (1) | (since C++11) |
|
```
int fegetround()
```
| (2) | (since C++11) |
Manages the floating-point rounding direction.
1) Attempts to establish the floating-point rounding direction equal to the argument `round`, which is expected to be one of the [floating point rounding macros](fe_round "cpp/numeric/fenv/FE round").
2) Returns the value of the [floating point rounding macro](fe_round "cpp/numeric/fenv/FE round") that corresponds to the current rounding direction. ### Parameters
| | | |
| --- | --- | --- |
| round | - | rounding direction, one of [floating point rounding macros](fe_round "cpp/numeric/fenv/FE round") |
### Return value
1) `โ0โ` on success, non-zero otherwise.
2) the [floating point rounding macro](fe_round "cpp/numeric/fenv/FE round") describing the current rounding direction or a negative value if the direction cannot be determined.
### Notes
The current rounding mode, reflecting the effects of the most recent `fesetround`, can also be queried with `[FLT\_ROUNDS](../../types/climits/flt_rounds "cpp/types/climits/FLT ROUNDS")`.
See [floating-point rounding macros](fe_round "cpp/numeric/fenv/FE round") for the effects of rounding.
### Example
```
#include <cfenv>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <utility>
// #pragma STDC FENV_ACCESS ON
int main() {
static constexpr std::pair<const char*, const double> samples[] {
{" 12.0", 12.0}, {" 12.1", 12.1}, {"-12.1", -12.1}, {" 12.5", 12.5},
{"-12.5", -12.5}, {" 12.9", 12.9}, {"-12.9", -12.9}, {" 13.0", 13.0},
};
std::cout <<
"โ sample โ FE_DOWNWARD โ FE_UPWARD โ FE_TONEAREST โ FE_TOWARDZERO โ\n";
for (const auto& [str, fp] : samples) {
std::cout << "โ " << std::setw(6) << str << " โ ";
for (const int dir : {FE_DOWNWARD, FE_UPWARD, FE_TONEAREST, FE_TOWARDZERO}) {
std::fesetround(dir);
std::cout << std::setw(10) << std::fixed << std::nearbyint(fp) << " โ ";
}
std::cout << '\n';
}
}
```
Output:
```
โ sample โ FE_DOWNWARD โ FE_UPWARD โ FE_TONEAREST โ FE_TOWARDZERO โ
โ 12.0 โ 12.000000 โ 12.000000 โ 12.000000 โ 12.000000 โ
โ 12.1 โ 12.000000 โ 13.000000 โ 12.000000 โ 12.000000 โ
โ -12.1 โ -13.000000 โ -12.000000 โ -12.000000 โ -12.000000 โ
โ 12.5 โ 12.000000 โ 13.000000 โ 12.000000 โ 12.000000 โ
โ -12.5 โ -13.000000 โ -12.000000 โ -12.000000 โ -12.000000 โ
โ 12.9 โ 12.000000 โ 13.000000 โ 13.000000 โ 12.000000 โ
โ -12.9 โ -13.000000 โ -12.000000 โ -13.000000 โ -12.000000 โ
โ 13.0 โ 13.000000 โ 13.000000 โ 13.000000 โ 13.000000 โ
```
### See also
| | |
| --- | --- |
| [nearbyintnearbyintfnearbyintl](../math/nearbyint "cpp/numeric/math/nearbyint")
(C++11)(C++11)(C++11) | nearest integer using current rounding mode (function) |
| [rintrintfrintllrintlrintflrintlllrintllrintfllrintl](../math/rint "cpp/numeric/math/rint")
(C++11)(C++11)(C++11)(C++11)(C++11)(C++11)(C++11)(C++11)(C++11) | nearest integer using current rounding mode with exception if the result differs (function) |
| [C documentation](https://en.cppreference.com/w/c/numeric/fenv/feround "c/numeric/fenv/feround") for `fegetround, fesetround` |
cpp std::feupdateenv std::feupdateenv
================
| Defined in header `[<cfenv>](../../header/cfenv "cpp/header/cfenv")` | | |
| --- | --- | --- |
|
```
int feupdateenv( const std::fenv_t* envp )
```
| | (since C++11) |
First, remembers the currently raised floating-point exceptions, then restores the floating-point environment from the object pointed to by `envp` (similar to `[std::fesetenv](feenv "cpp/numeric/fenv/feenv")`), then raises the floating-point exceptions that were saved.
This function may be used to end the non-stop mode established by an earlier call to `[std::feholdexcept](feholdexcept "cpp/numeric/fenv/feholdexcept")`.
### Parameters
| | | |
| --- | --- | --- |
| envp | - | pointer to the object of type `std::fenv_t` set by an earlier call to `[std::feholdexcept](feholdexcept "cpp/numeric/fenv/feholdexcept")` or `std::fegetenv` or equal to `[FE\_DFL\_ENV](fe_dfl_env "cpp/numeric/fenv/FE DFL ENV")` |
### Return value
`โ0โ` on success, non-zero otherwise.
### See also
| | |
| --- | --- |
| [feholdexcept](feholdexcept "cpp/numeric/fenv/feholdexcept")
(C++11) | saves the environment, clears all status flags and ignores all future errors (function) |
| [fegetenvfesetenv](feenv "cpp/numeric/fenv/feenv")
(C++11) | saves or restores the current floating-point environment (function) |
| [FE\_DFL\_ENV](fe_dfl_env "cpp/numeric/fenv/FE DFL ENV")
(C++11) | default floating-point environment (macro constant) |
| [C documentation](https://en.cppreference.com/w/c/numeric/fenv/feupdateenv "c/numeric/fenv/feupdateenv") for `feupdateenv` |
cpp std::feholdexcept std::feholdexcept
=================
| Defined in header `[<cfenv>](../../header/cfenv "cpp/header/cfenv")` | | |
| --- | --- | --- |
|
```
int feholdexcept( std::fenv_t* envp )
```
| | (since C++11) |
First, saves the current floating-point environment to the object pointed to by `envp` (similar to `[std::fegetenv](feenv "cpp/numeric/fenv/feenv")`), then clears all floating-point status flags, and then installs the non-stop mode: future floating-point exceptions will not interrupt execution (will not trap), until the floating-point environment is restored by `[std::feupdateenv](feupdateenv "cpp/numeric/fenv/feupdateenv")` or `[std::fesetenv](feenv "cpp/numeric/fenv/feenv")`.
This function may be used in the beginning of a subroutine that must hide the floating-point exceptions it may raise from the caller. If only some exceptions must be suppressed, while others must be reported, the non-stop mode is usually ended with a call to `[std::feupdateenv](feupdateenv "cpp/numeric/fenv/feupdateenv")` after clearing the unwanted exceptions.
### Parameters
| | | |
| --- | --- | --- |
| envp | - | pointer to the object of type `std::fenv_t` where the floating-point environment will be stored |
### Return value
`โ0โ` on success, non-zero otherwise.
### See also
| | |
| --- | --- |
| [feupdateenv](feupdateenv "cpp/numeric/fenv/feupdateenv")
(C++11) | restores the floating-point environment and raises the previously raise exceptions (function) |
| [fegetenvfesetenv](feenv "cpp/numeric/fenv/feenv")
(C++11) | saves or restores the current floating-point environment (function) |
| [FE\_DFL\_ENV](fe_dfl_env "cpp/numeric/fenv/FE DFL ENV")
(C++11) | default floating-point environment (macro constant) |
| [C documentation](https://en.cppreference.com/w/c/numeric/fenv/feholdexcept "c/numeric/fenv/feholdexcept") for `feholdexcept` |
cpp std::feclearexcept std::feclearexcept
==================
| Defined in header `[<cfenv>](../../header/cfenv "cpp/header/cfenv")` | | |
| --- | --- | --- |
|
```
int feclearexcept( int excepts );
```
| | (since C++11) |
Attempts to clear the floating-point exceptions that are listed in the bitmask argument `excepts`, which is a bitwise OR of the [floating point exception macros](fe_exceptions "cpp/numeric/fenv/FE exceptions").
### Parameters
| | | |
| --- | --- | --- |
| excepts | - | bitmask listing the exception flags to clear |
### Return value
`โ0โ` if all indicated exceptions were successfully cleared or if `excepts` is zero. Returns a non-zero value on error.
### Example
```
#include <iostream>
#include <cfenv>
#include <cmath>
#pragma STDC FENV_ACCESS ON
volatile double zero = 0.0; // volatile not needed where FENV_ACCESS is supported
volatile double one = 1.0; // volatile not needed where FENV_ACCESS is supported
int main()
{
std::feclearexcept(FE_ALL_EXCEPT);
std::cout << "1.0/0.0 = " << 1.0 / zero << '\n';
if(std::fetestexcept(FE_DIVBYZERO)) {
std::cout << "division by zero reported\n";
} else {
std::cout << "divsion by zero not reported\n";
}
std::feclearexcept(FE_ALL_EXCEPT);
std::cout << "1.0/10 = " << one/10 << '\n';
if(std::fetestexcept(FE_INEXACT)) {
std::cout << "inexact result reported\n";
} else {
std::cout << "inexact result not reported\n";
}
std::feclearexcept(FE_ALL_EXCEPT);
std::cout << "sqrt(-1) = " << std::sqrt(-1) << '\n';
if(std::fetestexcept(FE_INVALID)) {
std::cout << "invalid result reported\n";
} else {
std::cout << "invalid result not reported\n";
}
}
```
Output:
```
1.0/0.0 = inf
division by zero reported
1.0/10 = 0.1
inexact result reported
sqrt(-1) = -nan
invalid result reported
```
### See also
| | |
| --- | --- |
| [fetestexcept](fetestexcept "cpp/numeric/fenv/fetestexcept")
(C++11) | determines which of the specified floating-point status flags are set (function) |
| [C documentation](https://en.cppreference.com/w/c/numeric/fenv/feclearexcept "c/numeric/fenv/feclearexcept") for `feclearexcept` |
cpp FE_DIVBYZERO, FE_INEXACT, FE_INVALID, FE_OVERFLOW, FE_UNDERFLOW, FE_ALL_EXCEPT FE\_DIVBYZERO, FE\_INEXACT, FE\_INVALID, FE\_OVERFLOW, FE\_UNDERFLOW, FE\_ALL\_EXCEPT
=====================================================================================
| Defined in header `[<cfenv>](../../header/cfenv "cpp/header/cfenv")` | | |
| --- | --- | --- |
|
```
#define FE_DIVBYZERO /*implementation defined power of 2*/
```
| | (since C++11) |
|
```
#define FE_INEXACT /*implementation defined power of 2*/
```
| | (since C++11) |
|
```
#define FE_INVALID /*implementation defined power of 2*/
```
| | (since C++11) |
|
```
#define FE_OVERFLOW /*implementation defined power of 2*/
```
| | (since C++11) |
|
```
#define FE_UNDERFLOW /*implementation defined power of 2*/
```
| | (since C++11) |
|
```
#define FE_ALL_EXCEPT FE_DIVBYZERO | FE_INEXACT | \
FE_INVALID | FE_OVERFLOW | \
FE_UNDERFLOW
```
| | (since C++11) |
All these macro constants (except `FE_ALL_EXCEPT`) expand to integer constant expressions that are distinct powers of 2, which uniquely identify all supported floating-point exceptions. Each macro is only defined if it is supported.
The macro constant `FE_ALL_EXCEPT`, which expands to the bitwise OR of all other `FE_*`, is always defined and is zero if floating-point exceptions are not supported by the implementation.
| Constant | Explanation |
| --- | --- |
| `FE_DIVBYZERO` | pole error occurred in an earlier floating-point operation |
| `FE_INEXACT` | inexact result: rounding was necessary to store the result of an earlier floating-point operation |
| `FE_INVALID` | domain error occurred in an earlier floating-point operation |
| `FE_OVERFLOW` | the result of the earlier floating-point operation was too large to be representable |
| `FE_UNDERFLOW` | the result of the earlier floating-point operation was subnormal with a loss of precision |
| `FE_ALL_EXCEPT` | bitwise OR of all supported floating-point exceptions |
The implementation may define additional macro constants in `<cfenv>` to identify additional floating-point exceptions. All such constants begin with `FE_` followed by at least one uppercase letter.
See `[math\_errhandling](../math/math_errhandling "cpp/numeric/math/math errhandling")` for further details.
### Example
```
#include <iostream>
#include <cfenv>
#include <cmath>
#pragma STDC FENV_ACCESS ON
volatile double zero = 0.0; // volatile not needed where FENV_ACCESS is supported
volatile double one = 1.0; // volatile not needed where FENV_ACCESS is supported
int main()
{
std::feclearexcept(FE_ALL_EXCEPT);
std::cout << "1.0/0.0 = " << 1.0 / zero << '\n';
if(std::fetestexcept(FE_DIVBYZERO)) {
std::cout << "division by zero reported\n";
} else {
std::cout << "divsion by zero not reported\n";
}
std::feclearexcept(FE_ALL_EXCEPT);
std::cout << "1.0/10 = " << one/10 << '\n';
if(std::fetestexcept(FE_INEXACT)) {
std::cout << "inexact result reported\n";
} else {
std::cout << "inexact result not reported\n";
}
std::feclearexcept(FE_ALL_EXCEPT);
std::cout << "sqrt(-1) = " << std::sqrt(-1) << '\n';
if(std::fetestexcept(FE_INVALID)) {
std::cout << "invalid result reported\n";
} else {
std::cout << "invalid result not reported\n";
}
}
```
Output:
```
1.0/0.0 = inf
division by zero reported
1.0/10 = 0.1
inexact result reported
sqrt(-1) = -nan
invalid result reported
```
### See also
| | |
| --- | --- |
| [math\_errhandlingMATH\_ERRNOMATH\_ERREXCEPT](../math/math_errhandling "cpp/numeric/math/math errhandling")
(C++11)(C++11)(C++11) | defines the error handling mechanism used by the common mathematical functions (macro constant) |
| [C documentation](https://en.cppreference.com/w/c/numeric/fenv/FE_exceptions "c/numeric/fenv/FE exceptions") for floating point exception macros |
| programming_docs |
cpp FE_DFL_ENV FE\_DFL\_ENV
============
| Defined in header `[<cfenv>](../../header/cfenv "cpp/header/cfenv")` | | |
| --- | --- | --- |
|
```
#define FE_DFL_ENV /*implementation defined*/
```
| | (since C++11) |
The macro constant `FE_DFL_ENV` expands to an expression of type `const std::fenv_t*`, which points to a full copy of the default floating-point environment, that is, the environment as loaded at program startup.
Additional macros that begin with `FE_` followed by uppercase letters, and have the type `const std::fenv_t*`, may be supported by an implementation.
### Example
```
#include <iostream>
#include <cfenv>
#pragma STDC FENV_ACCESS ON
void show_env()
{
int e = std::fetestexcept(FE_ALL_EXCEPT);
if(e & FE_DIVBYZERO) std::cout << "division by zero is raised\n";
if(e & FE_INEXACT) std::cout << "inexact is raised\n";
if(e & FE_INVALID) std::cout << "invalid is raised\n";
if(e & FE_UNDERFLOW) std::cout << "underflow is raised\n";
if(e & FE_OVERFLOW) std::cout << "overflow is raised\n";
int r = std::fegetround();
switch(r)
{
case FE_DOWNWARD: std::cout << "rounding down\n"; break;
case FE_TONEAREST: std::cout << "rounding to nearest\n"; break;
case FE_TOWARDZERO: std::cout << "rounding to zero\n"; break;
case FE_UPWARD: std::cout << "rounding up\n"; break;
}
}
int main()
{
std::cout << "On startup: \n";
show_env();
std::feraiseexcept(FE_UNDERFLOW | FE_OVERFLOW);
std::fesetround(FE_UPWARD);
std::cout << "\nBefore restoration: \n";
show_env();
std::fesetenv(FE_DFL_ENV);
std::cout << "\nAfter reset to default: \n";
show_env();
}
```
Output:
```
On startup:
rounding to nearest
Before restoration:
underflow is raised
overflow is raised
rounding up
After reset to default:
rounding to nearest
```
### See also
| | |
| --- | --- |
| [fegetenvfesetenv](feenv "cpp/numeric/fenv/feenv")
(C++11) | saves or restores the current floating-point environment (function) |
| [feupdateenv](feupdateenv "cpp/numeric/fenv/feupdateenv")
(C++11) | restores the floating-point environment and raises the previously raise exceptions (function) |
| [C documentation](https://en.cppreference.com/w/c/numeric/fenv/FE_DFL_ENV "c/numeric/fenv/FE DFL ENV") for `FE_DFL_ENV` |
cpp std::fpclassify std::fpclassify
===============
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
|
```
int fpclassify( float arg );
```
| (1) | (since C++11) (constexpr since C++23) |
|
```
int fpclassify( double arg );
```
| (2) | (since C++11) (constexpr since C++23) |
|
```
int fpclassify( long double arg );
```
| (3) | (since C++11) (constexpr since C++23) |
|
```
int fpclassify( IntegralType arg );
```
| (4) | (since C++11) (constexpr since C++23) |
1-3) Categorizes floating point value `arg` into the following categories: zero, subnormal, normal, infinite, NAN, or implementation-defined category.
4) A set of overloads or a function template accepting the `arg` argument of any [integral type](../../types/is_integral "cpp/types/is integral"). Equivalent to (2) (the argument is cast to `double`). ### Parameters
| | | |
| --- | --- | --- |
| arg | - | floating point value |
### Return value
one of `[FP\_INFINITE](fp_categories "cpp/numeric/math/FP categories")`, `[FP\_NAN](fp_categories "cpp/numeric/math/FP categories")`, `[FP\_NORMAL](fp_categories "cpp/numeric/math/FP categories")`, `[FP\_SUBNORMAL](fp_categories "cpp/numeric/math/FP categories")`, `[FP\_ZERO](fp_categories "cpp/numeric/math/FP categories")` or implementation-defined type, specifying the category of `arg`.
### Example
```
#include <iostream>
#include <cmath>
#include <cfloat>
const char* show_classification(double x) {
switch(std::fpclassify(x)) {
case FP_INFINITE: return "Inf";
case FP_NAN: return "NaN";
case FP_NORMAL: return "normal";
case FP_SUBNORMAL: return "subnormal";
case FP_ZERO: return "zero";
default: return "unknown";
}
}
int main()
{
std::cout << "1.0/0.0 is " << show_classification(1/0.0) << '\n'
<< "0.0/0.0 is " << show_classification(0.0/0.0) << '\n'
<< "DBL_MIN/2 is " << show_classification(DBL_MIN/2) << '\n'
<< "-0.0 is " << show_classification(-0.0) << '\n'
<< "1.0 is " << show_classification(1.0) << '\n';
}
```
Output:
```
1.0/0.0 is Inf
0.0/0.0 is NaN
DBL_MIN/2 is subnormal
-0.0 is zero
1.0 is normal
```
### See also
| | |
| --- | --- |
| [isfinite](isfinite "cpp/numeric/math/isfinite")
(C++11) | checks if the given number has finite value (function) |
| [isinf](isinf "cpp/numeric/math/isinf")
(C++11) | checks if the given number is infinite (function) |
| [isnan](isnan "cpp/numeric/math/isnan")
(C++11) | checks if the given number is NaN (function) |
| [isnormal](isnormal "cpp/numeric/math/isnormal")
(C++11) | checks if the given number is normal (function) |
| [numeric\_limits](../../types/numeric_limits "cpp/types/numeric limits") | provides an interface to query properties of all fundamental numeric types. (class template) |
| [C documentation](https://en.cppreference.com/w/c/numeric/math/fpclassify "c/numeric/math/fpclassify") for `fpclassify` |
cpp std::remquo, std::remquof, std::remquol std::remquo, std::remquof, std::remquol
=======================================
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
|
```
float remquo ( float x, float y, int* quo );
```
| (1) | (since C++11) (constexpr since C++23) |
|
```
float remquof( float x, float y, int* quo );
```
| (2) | (since C++11) (constexpr since C++23) |
|
```
double remquo ( double x, double y, int* quo );
```
| (3) | (since C++11) (constexpr since C++23) |
|
```
long double remquo ( long double x, long double y, int* quo );
```
| (4) | (since C++11) (constexpr since C++23) |
|
```
long double remquol( long double x, long double y, int* quo );
```
| (5) | (since C++11) (constexpr since C++23) |
|
```
Promoted remquo ( Arithmetic1 x, Arithmetic2 y, int* quo );
```
| (6) | (since C++11) (constexpr since C++23) |
1-5) Computes the floating-point remainder of the division operation `x/y` as the `[std::remainder()](remainder "cpp/numeric/math/remainder")` function does. Additionally, the sign and at least the three of the last bits of `x/y` will be stored in `quo`, sufficient to determine the octant of the result within a period.
6) A set of overloads or a function template for all combinations of arguments of [arithmetic type](../../types/is_arithmetic "cpp/types/is arithmetic") not covered by (1-5). If any non-pointer argument has [integral type](../../types/is_integral "cpp/types/is integral"), it is cast to `double`. If any other non-pointer argument is `long double`, then the return type is `long double`, otherwise it is `double`. ### Parameters
| | | |
| --- | --- | --- |
| x, y | - | floating point values |
| quo | - | pointer to an integer value to store the sign and some bits of `x/y` |
### Return value
If successful, returns the floating-point remainder of the division `x/y` as defined in `[std::remainder](remainder "cpp/numeric/math/remainder")`, and stores, in `*quo`, the sign and at least three of the least significant bits of `x/y` (formally, stores a value whose sign is the sign of `x/y` and whose magnitude is congruent modulo 2n
to the magnitude of the integral quotient of `x/y`, where n is an implementation-defined integer greater than or equal to 3).
If `y` is zero, the value stored in `*quo` is unspecified.
If a domain error occurs, an implementation-defined value is returned (NaN where supported).
If a range error occurs due to underflow, the correct result is returned if subnormals are supported.
If `y` is zero, but the domain error does not occur, zero is returned.
### Error handling
Errors are reported as specified in `[math\_errhandling](math_errhandling "cpp/numeric/math/math errhandling")`.
Domain error may occur if `y` is zero.
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* The current [rounding mode](../fenv/fe_round "cpp/numeric/fenv/FE round") has no effect.
* `[FE\_INEXACT](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` is never raised
* If `x` is ยฑโ and `y` is not NaN, NaN is returned and `[FE\_INVALID](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` is raised
* If `y` is ยฑ0 and `x` is not NaN, NaN is returned and `[FE\_INVALID](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` is raised
* If either `x` or `y` is NaN, NaN is returned
### Notes
[POSIX requires](http://pubs.opengroup.org/onlinepubs/9699919799/functions/remquo.html) that a domain error occurs if `x` is infinite or `y` is zero.
This function is useful when implementing periodic functions with the period exactly representable as a floating-point value: when calculating sin(ฯx) for a very large `x`, calling `[std::sin](sin "cpp/numeric/math/sin")` directly may result in a large error, but if the function argument is first reduced with `std::remquo`, the low-order bits of the quotient may be used to determine the sign and the octant of the result within the period, while the remainder may be used to calculate the value with high precision.
On some platforms this operation is supported by hardware (and, for example, on Intel CPUs, `FPREM1` leaves exactly 3 bits of precision in the quotient when complete).
### Example
```
#include <iostream>
#include <cmath>
#include <cfenv>
#ifndef __GNUC__
#pragma STDC FENV_ACCESS ON
#endif
const double pi = std::acos(-1); // or std::numbers::pi since C++20
double cos_pi_x_naive(double x) { return std::cos(pi * x); }
// the period is 2, values are (0;0.5) positive, (0.5;1.5) negative, (1.5,2) positive
double cos_pi_x_smart(double x)
{
int quadrant;
double rem = std::remquo(x, 1, &quadrant);
quadrant = static_cast<unsigned>(quadrant) % 2; // The period is 2.
return quadrant == 0 ? std::cos(pi * rem)
:- std::cos(pi * rem);
}
int main()
{
std::cout << std::showpos
<< "naive:\n"
<< " cos(pi * 0.25) = " << cos_pi_x_naive(0.25) << '\n'
<< " cos(pi * 1.25) = " << cos_pi_x_naive(1.25) << '\n'
<< " cos(pi * 2.25) = " << cos_pi_x_naive(2.25) << '\n'
<< "smart:\n"
<< " cos(pi * 0.25) = " << cos_pi_x_smart(0.25) << '\n'
<< " cos(pi * 1.25) = " << cos_pi_x_smart(1.25) << '\n'
<< " cos(pi * 2.25) = " << cos_pi_x_smart(2.25) << '\n'
<< "naive:\n"
<< " cos(pi * 1000000000000.25) = "
<< cos_pi_x_naive(1000000000000.25) << '\n'
<< " cos(pi * 1000000000001.25) = "
<< cos_pi_x_naive(1000000000001.25) << '\n'
<< "smart:\n"
<< " cos(pi * 1000000000000.25) = "
<< cos_pi_x_smart(1000000000000.25) << '\n'
<< " cos(pi * 1000000000001.25) = "
<< cos_pi_x_smart(1000000000001.25) << '\n';
// error handling
std::feclearexcept(FE_ALL_EXCEPT);
int quo;
std::cout << "remquo(+Inf, 1) = " << std::remquo(INFINITY, 1, &quo) << '\n';
if(fetestexcept(FE_INVALID)) std::cout << " FE_INVALID raised\n";
}
```
Possible output:
```
naive:
cos(pi * 0.25) = +0.707107
cos(pi * 1.25) = -0.707107
cos(pi * 2.25) = +0.707107
smart:
cos(pi * 0.25) = +0.707107
cos(pi * 1.25) = -0.707107
cos(pi * 2.25) = +0.707107
naive:
cos(pi * 1000000000000.25) = +0.707123
cos(pi * 1000000000001.25) = -0.707117
smart:
cos(pi * 1000000000000.25) = +0.707107
cos(pi * 1000000000001.25) = -0.707107
remquo(+Inf, 1) = -nan
FE_INVALID raised
```
### See also
| | |
| --- | --- |
| [div(int)ldivlldiv](div "cpp/numeric/math/div")
(C++11) | computes quotient and remainder of integer division (function) |
| [fmodfmodffmodl](fmod "cpp/numeric/math/fmod")
(C++11)(C++11) | remainder of the floating point division operation (function) |
| [remainderremainderfremainderl](remainder "cpp/numeric/math/remainder")
(C++11)(C++11)(C++11) | signed remainder of the division operation (function) |
| [C documentation](https://en.cppreference.com/w/c/numeric/math/remquo "c/numeric/math/remquo") for `remquo` |
cpp INFINITY INFINITY
========
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
|
```
#define INFINITY /*implementation defined*/
```
| | (since C++11) |
If the implementation supports floating-point infinities, the macro `INFINITY` expands to constant expression of type `float` which evaluates to positive or unsigned infinity.
If the implementation does not support floating-point infinities, the macro `INFINITY` expands to a positive value that is guaranteed to overflow a `float` at compile time, and the use of this macro generates a compiler warning.
### See also
| | |
| --- | --- |
| [isinf](isinf "cpp/numeric/math/isinf")
(C++11) | checks if the given number is infinite (function) |
| [HUGE\_VALFHUGE\_VALHUGE\_VALL](huge_val "cpp/numeric/math/HUGE VAL")
(C++11)(C++11) | indicates the overflow value for `float`, `double` and `long double` respectively (macro constant) |
| [has\_infinity](../../types/numeric_limits/has_infinity "cpp/types/numeric limits/has infinity")
[static] | identifies floating-point types that can represent the special value "positive infinity" (public static member constant of `std::numeric_limits<T>`) |
| [infinity](../../types/numeric_limits/infinity "cpp/types/numeric limits/infinity")
[static] | returns the positive infinity value of the given floating-point type (public static member function of `std::numeric_limits<T>`) |
| [C documentation](https://en.cppreference.com/w/c/numeric/math/INFINITY "c/numeric/math/INFINITY") for `INFINITY` |
cpp std::atan, std::atanf, std::atanl std::atan, std::atanf, std::atanl
=================================
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
| | (1) | |
|
```
float atan ( float arg );
```
| |
|
```
float atanf( float arg );
```
| (since C++11) |
|
```
double atan ( double arg );
```
| (2) | |
| | (3) | |
|
```
long double atan ( long double arg );
```
| |
|
```
long double atanl( long double arg );
```
| (since C++11) |
|
```
double atan ( IntegralType arg );
```
| (4) | (since C++11) |
1-3) Computes the principal value of the arc tangent of `arg`
4) A set of overloads or a function template accepting an argument of any [integral type](../../types/is_integral "cpp/types/is integral"). Equivalent to 2) (the argument is cast to `double`). ### Parameters
| | | |
| --- | --- | --- |
| arg | - | value of a floating-point or [Integral type](../../types/is_integral "cpp/types/is integral") |
### Return value
If no errors occur, the arc tangent of `arg` (arctan(arg)) in the range [- ฯ/2 , +ฯ/2] radians, is returned. If a range error occurs due to underflow, the correct result (after rounding) is returned.
### Error handling
Errors are reported as specified in `[math\_errhandling](math_errhandling "cpp/numeric/math/math errhandling")`.
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* If the argument is ยฑ0, it is returned unmodified
* If the argument is +โ, +ฯ/2 is returned
* If the argument is -โ, -ฯ/2 is returned
* if the argument is NaN, NaN is returned
### Notes
[POSIX specifies](http://pubs.opengroup.org/onlinepubs/9699919799/functions/atan.html) that in case of underflow, `arg` is returned unmodified, and if that is not supported, an implementation-defined value no greater than [`DBL_MIN`](../../types/climits#Limits_of_floating_point_types "cpp/types/climits"), `[FLT\_MIN](../../types/climits "cpp/types/climits")`, and `[LDBL\_MIN](../../types/climits "cpp/types/climits")` is returned.
### Examples
```
#include <iostream>
#include <cmath>
int main()
{
std::cout << "atan(1) = " << atan(1) << " 4*atan(1) = " << 4*atan(1) << '\n';
// special values
std::cout << "atan(Inf) = " << atan(INFINITY)
<< " 2*atan(Inf) = " << 2*atan(INFINITY) << '\n'
<< "atan(-0.0) = " << atan(-0.0) << '\n'
<< "atan(+0.0) = " << atan(0) << '\n';
}
```
Output:
```
atan(1) = 0.785398 4*atan(1) = 3.14159
atan(Inf) = 1.5708 2*atan(Inf) = 3.14159
atan(-0.0) = -0
atan(+0.0) = 0
```
### See also
| | |
| --- | --- |
| [asinasinfasinl](asin "cpp/numeric/math/asin")
(C++11)(C++11) | computes arc sine (\({\small\arcsin{x} }\)arcsin(x)) (function) |
| [acosacosfacosl](acos "cpp/numeric/math/acos")
(C++11)(C++11) | computes arc cosine (\({\small\arccos{x} }\)arccos(x)) (function) |
| [atan2atan2fatan2l](atan2 "cpp/numeric/math/atan2")
(C++11)(C++11) | arc tangent, using signs to determine quadrants (function) |
| [tantanftanl](tan "cpp/numeric/math/tan")
(C++11)(C++11) | computes tangent (\({\small\tan{x} }\)tan(x)) (function) |
| [atan(std::complex)](../complex/atan "cpp/numeric/complex/atan")
(C++11) | computes arc tangent of a complex number (\({\small\arctan{z} }\)arctan(z)) (function template) |
| [atan(std::valarray)](../valarray/atan "cpp/numeric/valarray/atan") | applies the function `std::atan` to each element of valarray (function template) |
| [C documentation](https://en.cppreference.com/w/c/numeric/math/atan "c/numeric/math/atan") for `atan` |
cpp std::asin, std::asinf, std::asinl std::asin, std::asinf, std::asinl
=================================
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
| | (1) | |
|
```
float asin ( float arg );
```
| |
|
```
float asinf( float arg );
```
| (since C++11) |
|
```
double asin ( double arg );
```
| (2) | |
| | (3) | |
|
```
long double asin ( long double arg );
```
| |
|
```
long double asinl( long double arg );
```
| (since C++11) |
|
```
double asin ( IntegralType arg );
```
| (4) | (since C++11) |
1-3) Computes the principal value of the arc sine of `arg`.
4) A set of overloads or a function template accepting an argument of any [integral type](../../types/is_integral "cpp/types/is integral"). Equivalent to 2) (the argument is cast to `double`). ### Parameters
| | | |
| --- | --- | --- |
| arg | - | value of a floating-point or [Integral type](../../types/is_integral "cpp/types/is integral") |
### Return value
If no errors occur, the arc sine of `arg` (arcsin(arg)) in the range [- ฯ/2 , +ฯ/2], is returned. If a domain error occurs, an implementation-defined value is returned (NaN where supported).
If a range error occurs due to underflow, the correct result (after rounding) is returned.
### Error handling
Errors are reported as specified in `[math\_errhandling](math_errhandling "cpp/numeric/math/math errhandling")`.
Domain error occurs if `arg` is outside the range `[-1.0, 1.0]`
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* If the argument is ยฑ0, it is returned unmodified
* If |arg| > 1, a domain error occurs and NaN is returned.
* if the argument is NaN, NaN is returned
### Example
```
#include <cmath>
#include <iostream>
#include <cerrno>
#include <cfenv>
#include <cstring>
#pragma STDC FENV_ACCESS ON
int main()
{
std::cout << "asin(1.0) = " << asin(1) << '\n'
<< "2*asin(1.0) = " << 2*asin(1) << '\n'
<< "asin(-0.5) = " << asin(-0.5) << '\n'
<< "6*asin(-0.5) =" << 6*asin(-0.5) << '\n';
// special values
std::cout << "asin(0.0) = " << asin(0) << " asin(-0.0)=" << asin(-0.0) << '\n';
// error handling
errno = 0;
std::feclearexcept(FE_ALL_EXCEPT);
std::cout << "asin(1.1) = " << asin(1.1) << '\n';
if (errno == EDOM)
std::cout << " errno == EDOM: " << std::strerror(errno) << '\n';
if (std::fetestexcept(FE_INVALID))
std::cout << " FE_INVALID raised" << '\n';
}
```
Possible output:
```
asin(1.0) = 1.5708
2*asin(1.0) = 3.14159
asin(-0.5) = -0.523599
6*asin(-0.5) = -3.14159
asin(0.0) = 0 asin(-0.0)=-0
asin(1.1) = nan
errno == EDOM: Numerical argument out of domain
FE_INVALID raised
```
### See also
| | |
| --- | --- |
| [acosacosfacosl](acos "cpp/numeric/math/acos")
(C++11)(C++11) | computes arc cosine (\({\small\arccos{x} }\)arccos(x)) (function) |
| [atanatanfatanl](atan "cpp/numeric/math/atan")
(C++11)(C++11) | computes arc tangent (\({\small\arctan{x} }\)arctan(x)) (function) |
| [atan2atan2fatan2l](atan2 "cpp/numeric/math/atan2")
(C++11)(C++11) | arc tangent, using signs to determine quadrants (function) |
| [sinsinfsinl](sin "cpp/numeric/math/sin")
(C++11)(C++11) | computes sine (\({\small\sin{x} }\)sin(x)) (function) |
| [asin(std::complex)](../complex/asin "cpp/numeric/complex/asin")
(C++11) | computes arc sine of a complex number (\({\small\arcsin{z} }\)arcsin(z)) (function template) |
| [asin(std::valarray)](../valarray/asin "cpp/numeric/valarray/asin") | applies the function `std::asin` to each element of valarray (function template) |
| [C documentation](https://en.cppreference.com/w/c/numeric/math/asin "c/numeric/math/asin") for `asin` |
| programming_docs |
cpp std::cosh, std::coshf, std::coshl std::cosh, std::coshf, std::coshl
=================================
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
| | (1) | |
|
```
float cosh ( float arg );
```
| |
|
```
float coshf( float arg );
```
| (since C++11) |
|
```
double cosh ( double arg );
```
| (2) | |
| | (3) | |
|
```
long double cosh ( long double arg );
```
| |
|
```
long double coshl( long double arg );
```
| (since C++11) |
|
```
double cosh ( IntegralType arg );
```
| (4) | (since C++11) |
1-3) Computes the hyperbolic cosine of `arg`
4) A set of overloads or a function template accepting an argument of any [integral type](../../types/is_integral "cpp/types/is integral"). Equivalent to (2) (the argument is cast to `double`). ### Parameters
| | | |
| --- | --- | --- |
| arg | - | value of a floating-point or [Integral type](../../types/is_integral "cpp/types/is integral") |
### Return value
If no errors occur, the hyperbolic cosine of `arg` (cosh(arg), or earg+e-arg/2) is returned. If a range error due to overflow occurs, `[+HUGE\_VAL](huge_val "cpp/numeric/math/HUGE VAL")`, `+HUGE_VALF`, or `+HUGE_VALL` is returned.
### Error handling
Errors are reported as specified in `[math\_errhandling](math_errhandling "cpp/numeric/math/math errhandling")`.
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* if the argument is ยฑ0, 1 is returned
* If the argument is ยฑโ, +โ is returned
* if the argument is NaN, NaN is returned
### Notes
For the IEEE-compatible type `double`, if |arg| > 710.5, then `cosh(arg)` overflows.
### Example
```
#include <iostream>
#include <cmath>
#include <cerrno>
#include <cstring>
#include <cfenv>
// #pragma STDC FENV_ACCESS ON
int main()
{
std::cout << "cosh(1) = " << std::cosh(1) << '\n'
<< "cosh(-1) = " << std::cosh(-1) << '\n'
<< "log(sinh(1)+cosh(1)=" << std::log(std::sinh(1)+std::cosh(1)) << '\n';
// special values
std::cout << "cosh(+0) = " << std::cosh(0.0) << '\n'
<< "cosh(-0) = " << std::cosh(-0.0) << '\n';
// error handling
errno=0;
std::feclearexcept(FE_ALL_EXCEPT);
std::cout << "cosh(710.5) = " << std::cosh(710.5) << '\n';
if (errno == ERANGE)
std::cout << " errno == ERANGE: " << std::strerror(errno) << '\n';
if (std::fetestexcept(FE_OVERFLOW))
std::cout << " FE_OVERFLOW raised\n";
}
```
Possible output:
```
cosh(1) = 1.54308
cosh(-1) = 1.54308
log(sinh(1)+cosh(1)=1
cosh(+0) = 1
cosh(-0) = 1
cosh(710.5) = inf
errno == ERANGE: Numerical result out of range
FE_OVERFLOW raised
```
### See also
| | |
| --- | --- |
| [sinhsinhfsinhl](sinh "cpp/numeric/math/sinh")
(C++11)(C++11) | computes hyperbolic sine (\({\small\sinh{x} }\)sinh(x)) (function) |
| [tanhtanhftanhl](tanh "cpp/numeric/math/tanh")
(C++11)(C++11) | computes hyperbolic tangent (\({\small\tanh{x} }\)tanh(x)) (function) |
| [acoshacoshfacoshl](acosh "cpp/numeric/math/acosh")
(C++11)(C++11)(C++11) | computes the inverse hyperbolic cosine (\({\small\operatorname{arcosh}{x} }\)arcosh(x)) (function) |
| [cosh(std::complex)](../complex/cosh "cpp/numeric/complex/cosh") | computes hyperbolic cosine of a complex number (\({\small\cosh{z} }\)cosh(z)) (function template) |
| [cosh(std::valarray)](../valarray/cosh "cpp/numeric/valarray/cosh") | applies the function `std::cosh` to each element of valarray (function template) |
| [C documentation](https://en.cppreference.com/w/c/numeric/math/cosh "c/numeric/math/cosh") for `cosh` |
cpp std::isgreater std::isgreater
==============
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
|
```
bool isgreater( float x, float y );
```
| (1) | (since C++11) (constexpr since C++23) |
|
```
bool isgreater( double x, double y );
```
| (2) | (since C++11) (constexpr since C++23) |
|
```
bool isgreater( long double x, long double y );
```
| (3) | (since C++11) (constexpr since C++23) |
|
```
bool isgreater( Arithmetic x, Arithmetic y );
```
| (4) | (since C++11) (constexpr since C++23) |
1-3) Determines if the floating point number `x` is greater than the floating-point number `y`, without setting floating-point exceptions.
4) A set of overloads or a function template for all combinations of arguments of arithmetic type not covered by (1-3). If any argument has [integral type](../../types/is_integral "cpp/types/is integral"), it is cast to `double`. ### Parameters
| | | |
| --- | --- | --- |
| x | - | floating point value |
| y | - | floating point value |
### Return value
`true` if `x > y`, `false` otherwise.
### Notes
The built-in `operator>` for floating-point numbers may set `[FE\_INVALID](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` if one or both of the arguments is NaN. This function is a "quiet" version of `operator>`.
### See also
| | |
| --- | --- |
| [greater](../../utility/functional/greater "cpp/utility/functional/greater") | function object implementing `x > y` (class template) |
| [isless](isless "cpp/numeric/math/isless")
(C++11) | checks if the first floating-point argument is less than the second (function) |
| [C documentation](https://en.cppreference.com/w/c/numeric/math/isgreater "c/numeric/math/isgreater") for `isgreater` |
cpp std::rint, std::rintf, std::rintl, std::lrint, std::lrintf, std::lrintl, std::llrint, std::llrintf std::rint, std::rintf, std::rintl, std::lrint, std::lrintf, std::lrintl, std::llrint, std::llrintf
==================================================================================================
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
|
```
float rint ( float arg );
float rintf( float arg );
```
| (1) | (since C++11) |
|
```
double rint ( double arg );
```
| (2) | (since C++11) |
|
```
long double rint ( long double arg );
long double rintl( long double arg );
```
| (3) | (since C++11) |
|
```
double rint ( IntegralType arg );
```
| (4) | (since C++11) |
|
```
long lrint ( float arg );
long lrintf( float arg );
```
| (5) | (since C++11) |
|
```
long lrint ( double arg );
```
| (6) | (since C++11) |
|
```
long lrint ( long double arg );
long lrintl( long double arg );
```
| (7) | (since C++11) |
|
```
long lrint ( IntegralType arg );
```
| (8) | (since C++11) |
|
```
long long llrint ( float arg );
long long llrintf( float arg );
```
| (9) | (since C++11) |
|
```
long long llrint ( double arg );
```
| (10) | (since C++11) |
|
```
long long llrint ( long double arg );
long long llrintl( long double arg );
```
| (11) | (since C++11) |
|
```
long long llrint ( IntegralType arg );
```
| (12) | (since C++11) |
1-3) Rounds the floating-point argument `arg` to an integer value (in floating-point format), using the [current rounding mode](../fenv/fe_round "cpp/numeric/fenv/FE round").
5-7, 9-11) Rounds the floating-point argument `arg` to an integer value, using the [current rounding mode](../fenv/fe_round "cpp/numeric/fenv/FE round").
4,8,12) A set of overloads or a function template accepting an argument of any [integral type](../../types/is_integral "cpp/types/is integral"). Equivalent to (2,6,10), respectively (the argument is cast to `double`). ### Parameters
| | | |
| --- | --- | --- |
| arg | - | floating point value |
### Return value
If no errors occur, the nearest integer value to `arg`, according to the [current rounding mode](../fenv/fe_round "cpp/numeric/fenv/FE round"), is returned.
### Error handling
Errors are reported as specified in `[math\_errhandling](math_errhandling "cpp/numeric/math/math errhandling")`.
If the result of `std::lrint` or `std::llrint` is outside the range representable by the return type, a domain error or a range error may occur.
If the implementation supports IEEE floating-point arithmetic (IEC 60559), For the `std::rint` function:
* If `arg` is ยฑโ, it is returned, unmodified
* If `arg` is ยฑ0, it is returned, unmodified
* If `arg` is NaN, NaN is returned
For `std::lrint` and `std::llrint` functions: * If `arg` is ยฑโ, `[FE\_INVALID](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` is raised and an implementation-defined value is returned
* If the result of the rounding is outside the range of the return type, `[FE\_INVALID](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` is raised and an implementation-defined value is returned
* If `arg` is NaN, `[FE\_INVALID](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` is raised and an implementation-defined value is returned
### Notes
[POSIX specifies](http://pubs.opengroup.org/onlinepubs/9699919799/functions/lrint.html) that all cases where `std::lrint` or `std::llrint` raise `[FE\_INEXACT](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` are domain errors.
As specified in `[math\_errhandling](math_errhandling "cpp/numeric/math/math errhandling")`, `[FE\_INEXACT](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` may be (but isn't required to be on non-IEEE floating-point platforms) raised by `std::rint` when rounding a non-integer finite value.
The only difference between `std::rint` and `[std::nearbyint](nearbyint "cpp/numeric/math/nearbyint")` is that `[std::nearbyint](nearbyint "cpp/numeric/math/nearbyint")` never raises `[FE\_INEXACT](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")`.
The largest representable floating-point values are exact integers in all standard floating-point formats, so `std::rint` never overflows on its own; however the result may overflow any integer type (including `[std::intmax\_t](../../types/integer "cpp/types/integer")`), when stored in an integer variable.
If the current rounding mode is...
* `[FE\_DOWNWARD](../fenv/fe_round "cpp/numeric/fenv/FE round")`, then `std::rint` is equivalent to `[std::floor](floor "cpp/numeric/math/floor")`.
* `[FE\_UPWARD](../fenv/fe_round "cpp/numeric/fenv/FE round")`, then `std::rint` is equivalent to `[std::ceil](ceil "cpp/numeric/math/ceil")`.
* `[FE\_TOWARDZERO](../fenv/fe_round "cpp/numeric/fenv/FE round")`, then `std::rint` is equivalent to `[std::trunc](trunc "cpp/numeric/math/trunc")`
* `[FE\_TONEAREST](../fenv/fe_round "cpp/numeric/fenv/FE round")`, then `std::rint` differs from `[std::round](round "cpp/numeric/math/round")` in that halfway cases are rounded to even rather than away from zero.
### Example
```
#include <iostream>
#include <cmath>
#include <cfenv>
#include <climits>
int main()
{
#pragma STDC FENV_ACCESS ON
std::fesetround(FE_TONEAREST);
std::cout << "rounding to nearest (halfway cases to even):\n"
<< "rint(+2.3) = " << std::rint(2.3)
<< " rint(+2.5) = " << std::rint(2.5)
<< " rint(+3.5) = " << std::rint(3.5) << '\n'
<< "rint(-2.3) = " << std::rint(-2.3)
<< " rint(-2.5) = " << std::rint(-2.5)
<< " rint(-3.5) = " << std::rint(-3.5) << '\n';
std::fesetround(FE_DOWNWARD);
std::cout << "rounding down:\n"
<< "rint(+2.3) = " << std::rint(2.3)
<< " rint(+2.5) = " << std::rint(2.5)
<< " rint(+3.5) = " << std::rint(3.5) << '\n'
<< "rint(-2.3) = " << std::rint(-2.3)
<< " rint(-2.5) = " << std::rint(-2.5)
<< " rint(-3.5) = " << std::rint(-3.5) << '\n'
<< "rounding down with lrint\n"
<< "lrint(+2.3) = " << std::lrint(2.3)
<< " lrint(+2.5) = " << std::lrint(2.5)
<< " lrint(+3.5) = " << std::lrint(3.5) << '\n'
<< "lrint(-2.3) = " << std::lrint(-2.3)
<< " lrint(-2.5) = " << std::lrint(-2.5)
<< " lrint(-3.5) = " << std::lrint(-3.5) << '\n';
std::cout << "lrint(-0.0) = " << std::lrint(-0.0) << '\n'
<< "lrint(-Inf) = " << std::lrint(-INFINITY) << '\n';
// error handling
std::feclearexcept(FE_ALL_EXCEPT);
std::cout << "std::rint(0.1) = " << std::rint(.1) << '\n';
if (std::fetestexcept(FE_INEXACT))
std::cout << " FE_INEXACT was raised\n";
std::feclearexcept(FE_ALL_EXCEPT);
std::cout << "std::lrint(LONG_MIN-2048.0) = "
<< std::lrint(LONG_MIN-2048.0) << '\n';
if (std::fetestexcept(FE_INVALID))
std::cout << " FE_INVALID was raised\n";
}
```
Possible output:
```
rounding to nearest (halfway cases to even):
rint(+2.3) = 2 rint(+2.5) = 2 rint(+3.5) = 4
rint(-2.3) = -2 rint(-2.5) = -2 rint(-3.5) = -4
rounding down:
rint(+2.3) = 2 rint(+2.5) = 2 rint(+3.5) = 3
rint(-2.3) = -3 rint(-2.5) = -3 rint(-3.5) = -4
rounding down with lrint
lrint(+2.3) = 2 lrint(+2.5) = 2 lrint(+3.5) = 3
lrint(-2.3) = -3 lrint(-2.5) = -3 lrint(-3.5) = -4
lrint(-0.0) = 0
lrint(-Inf) = -9223372036854775808
std::rint(0.1) = 0
FE_INEXACT was raised
std::lrint(LONG_MIN-2048.0) = -9223372036854775808
FE_INVALID was raised
```
### See also
| | |
| --- | --- |
| [trunctruncftruncl](trunc "cpp/numeric/math/trunc")
(C++11)(C++11)(C++11) | nearest integer not greater in magnitude than the given value (function) |
| [nearbyintnearbyintfnearbyintl](nearbyint "cpp/numeric/math/nearbyint")
(C++11)(C++11)(C++11) | nearest integer using current rounding mode (function) |
| [fegetroundfesetround](../fenv/feround "cpp/numeric/fenv/feround")
(C++11)(C++11) | gets or sets rounding direction (function) |
| [C documentation](https://en.cppreference.com/w/c/numeric/math/rint "c/numeric/math/rint") for `rint` |
cpp std::asinh, std::asinhf, std::asinhl std::asinh, std::asinhf, std::asinhl
====================================
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
|
```
float asinh ( float arg );
float asinhf( float arg );
```
| (1) | (since C++11) |
|
```
double asinh ( double arg );
```
| (2) | (since C++11) |
|
```
long double asinh ( long double arg );
long double asinhl( long double arg );
```
| (3) | (since C++11) |
|
```
double asinh ( IntegralType arg );
```
| (4) | (since C++11) |
1-3) Computes the inverse hyperbolic sine of `arg`.
4) A set of overloads or a function template accepting an argument of any [integral type](../../types/is_integral "cpp/types/is integral"). Equivalent to 2) (the argument is cast to `double`). ### Parameters
| | | |
| --- | --- | --- |
| arg | - | value of a floating-point or [Integral type](../../types/is_integral "cpp/types/is integral") |
### Return value
If no errors occur, the inverse hyperbolic sine of `arg` (sinh-1
(arg), or arsinh(arg)), is returned.
If a range error occurs due to underflow, the correct result (after rounding) is returned.
### Error handling
Errors are reported as specified in `[math\_errhandling](math_errhandling "cpp/numeric/math/math errhandling")`.
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* if the argument is ยฑ0 or ยฑโ, it is returned unmodified
* if the argument is NaN, NaN is returned
### Notes
Although the C standard (to which C++ refers for this function) names this function "arc hyperbolic sine", the inverse functions of the hyperbolic functions are the area functions. Their argument is the area of a hyperbolic sector, not an arc. The correct name is "inverse hyperbolic sine" (used by POSIX) or "area hyperbolic sine".
### Examples
```
#include <iostream>
#include <cmath>
int main()
{
std::cout << "asinh(1) = " << std::asinh(1) << '\n'
<< "asinh(-1) = " << std::asinh(-1) << '\n';
// special values
std::cout << "asinh(+0) = " << std::asinh(+0.0) << '\n'
<< "asinh(-0) = " << std::asinh(-0.0) << '\n';
}
```
Output:
```
asinh(1) = 0.881374
asinh(-1) = -0.881374
asinh(+0) = 0
asinh(-0) = -0
```
### See also
| | |
| --- | --- |
| [acoshacoshfacoshl](acosh "cpp/numeric/math/acosh")
(C++11)(C++11)(C++11) | computes the inverse hyperbolic cosine (\({\small\operatorname{arcosh}{x} }\)arcosh(x)) (function) |
| [atanhatanhfatanhl](atanh "cpp/numeric/math/atanh")
(C++11)(C++11)(C++11) | computes the inverse hyperbolic tangent (\({\small\operatorname{artanh}{x} }\)artanh(x)) (function) |
| [sinhsinhfsinhl](sinh "cpp/numeric/math/sinh")
(C++11)(C++11) | computes hyperbolic sine (\({\small\sinh{x} }\)sinh(x)) (function) |
| [asinh(std::complex)](../complex/asinh "cpp/numeric/complex/asinh")
(C++11) | computes area hyperbolic sine of a complex number (\({\small\operatorname{arsinh}{z} }\)arsinh(z)) (function template) |
| [C documentation](https://en.cppreference.com/w/c/numeric/math/asinh "c/numeric/math/asinh") for `asinh` |
### External links
[Weisstein, Eric W. "Inverse Hyperbolic Sine."](http://mathworld.wolfram.com/InverseHyperbolicSine.html) From MathWorld--A Wolfram Web Resource.
cpp std::trunc, std::truncf, std::truncl std::trunc, std::truncf, std::truncl
====================================
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
|
```
float trunc ( float arg );
```
| (1) | (since C++11) (constexpr since C++23) |
|
```
float truncf( float arg );
```
| (2) | (since C++11) (constexpr since C++23) |
|
```
double trunc ( double arg );
```
| (3) | (since C++11) (constexpr since C++23) |
|
```
long double trunc ( long double arg );
```
| (4) | (since C++11) (constexpr since C++23) |
|
```
long double truncl( long double arg );
```
| (5) | (since C++11) (constexpr since C++23) |
|
```
double trunc ( IntegralType arg );
```
| (6) | (since C++11) (constexpr since C++23) |
1-5) Computes the nearest integer not greater in magnitude than `arg`.
6) A set of overloads or a function template accepting an argument of any [integral type](../../types/is_integral "cpp/types/is integral"). Equivalent to (3) (the argument is cast to `double`). ### Parameters
| | | |
| --- | --- | --- |
| arg | - | floating point value |
### Return value
If no errors occur, the nearest integer value not greater in magnitude than `arg` (in other words, `arg` rounded towards zero) is returned.
Return value ![math-trunc.svg]() Argument ### Error handling
Errors are reported as specified in `[math\_errhandling](math_errhandling "cpp/numeric/math/math errhandling")`.
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* The current [rounding mode](../fenv/fe_round "cpp/numeric/fenv/FE round") has no effect.
* If `arg` is ยฑโ, it is returned, unmodified
* If `arg` is ยฑ0, it is returned, unmodified
* If arg is NaN, NaN is returned
### Notes
`[FE\_INEXACT](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` may be (but isn't required to be) raised when truncating a non-integer finite value.
The largest representable floating-point values are exact integers in all standard floating-point formats, so this function never overflows on its own; however the result may overflow any integer type (including `[std::intmax\_t](../../types/integer "cpp/types/integer")`), when stored in an integer variable.
The [implicit conversion](../../language/implicit_conversion "cpp/language/implicit conversion") from floating-point to integral types also rounds towards zero, but is limited to the values that can be represented by the target type.
### Example
```
#include <cmath>
#include <iostream>
#include <initializer_list>
int main()
{
const auto data = std::initializer_list<double>{
+2.7, -2.9, +0.7, -0.9, +0.0, 0.0, -INFINITY, +INFINITY, -NAN, +NAN
};
std::cout << std::showpos;
for (double const x : data) {
std::cout << "trunc(" << x << ") == " << std::trunc(x) << '\n';
}
}
```
Possible output:
```
trunc(+2.7) == +2
trunc(-2.9) == -2
trunc(+0.7) == +0
trunc(-0.9) == -0
trunc(+0) == +0
trunc(+0) == +0
trunc(-inf) == -inf
trunc(+inf) == +inf
trunc(-nan) == -nan
trunc(+nan) == +nan
```
### See also
| | |
| --- | --- |
| [floorfloorffloorl](floor "cpp/numeric/math/floor")
(C++11)(C++11) | nearest integer not greater than the given value (function) |
| [ceilceilfceill](ceil "cpp/numeric/math/ceil")
(C++11)(C++11) | nearest integer not less than the given value (function) |
| [roundroundfroundllroundlroundflroundlllroundllroundfllroundl](round "cpp/numeric/math/round")
(C++11)(C++11)(C++11)(C++11)(C++11)(C++11)(C++11)(C++11)(C++11) | nearest integer, rounding away from zero in halfway cases (function) |
| [C documentation](https://en.cppreference.com/w/c/numeric/math/trunc "c/numeric/math/trunc") for `trunc` |
| programming_docs |
cpp std::log2, std::log2f, std::log2l std::log2, std::log2f, std::log2l
=================================
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
|
```
float log2 ( float arg );
float log2f( float arg );
```
| (1) | (since C++11) |
|
```
double log2 ( double arg );
```
| (2) | (since C++11) |
|
```
long double log2 ( long double arg );
long double log2l( long double arg );
```
| (3) | (since C++11) |
|
```
double log2 ( IntegralType arg );
```
| (4) | (since C++11) |
1-3) Computes the binary (base-*2*) logarithm of `arg`.
4) A set of overloads or a function template accepting an argument of any [integral type](../../types/is_integral "cpp/types/is integral"). Equivalent to (2) (the argument is cast to `double`). ### Parameters
| | | |
| --- | --- | --- |
| arg | - | value of floating-point or [Integral type](../../types/is_integral "cpp/types/is integral") |
### Return value
If no errors occur, the base-*2* logarithm of `arg` (log
2(arg) or lb(arg)) is returned.
If a domain error occurs, an implementation-defined value is returned (NaN where supported).
If a pole error occurs, `[-HUGE\_VAL](huge_val "cpp/numeric/math/HUGE VAL")`, `-HUGE_VALF`, or `-HUGE_VALL` is returned.
### Error handling
Errors are reported as specified in `[math\_errhandling](math_errhandling "cpp/numeric/math/math errhandling")`.
Domain error occurs if `arg` is less than zero.
Pole error may occur if `arg` is zero.
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* If the argument is ยฑ0, -โ is returned and `[FE\_DIVBYZERO](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` is raised.
* If the argument is 1, +0 is returned
* If the argument is negative, NaN is returned and `[FE\_INVALID](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` is raised.
* If the argument is +โ, +โ is returned
* If the argument is NaN, NaN is returned
### Notes
For integer `arg`, the binary logarithm can be interpreted as the zero-based index of the most significant 1 bit in the input.
### Example
```
#include <iostream>
#include <cmath>
#include <cerrno>
#include <cstring>
#include <cfenv>
// #pragma STDC FENV_ACCESS ON
int main()
{
std::cout << "log2(65536) = " << std::log2(65536) << '\n'
<< "log2(0.125) = " << std::log2(0.125) << '\n'
<< "log2(0x020f) = " << std::log2(0x020f)
<< " (highest set bit is in position 9)\n"
<< "base-5 logarithm of 125 = " << std::log2(125)/std::log2(5) << '\n';
// special values
std::cout << "log2(1) = " << std::log2(1) << '\n'
<< "log2(+Inf) = " << std::log2(INFINITY) << '\n';
// error handling
errno = 0;
std::feclearexcept(FE_ALL_EXCEPT);
std::cout << "log2(0) = " << std::log2(0) << '\n';
if (errno == ERANGE)
std::cout << " errno == ERANGE: " << std::strerror(errno) << '\n';
if (std::fetestexcept(FE_DIVBYZERO))
std::cout << " FE_DIVBYZERO raised\n";
}
```
Possible output:
```
log2(65536) = 16
log2(0.125) = -3
log2(0x020f) = 9.04166 (highest set bit is in position 9)
base-5 logarithm of 125 = 3
log2(1) = 0
log2(+Inf) = inf
log2(0) = -inf
errno == ERANGE: Numerical result out of range
FE_DIVBYZERO raised
```
### See also
| | |
| --- | --- |
| [loglogflogl](log "cpp/numeric/math/log")
(C++11)(C++11) | computes natural (base *e*) logarithm (\({\small \ln{x} }\)ln(x)) (function) |
| [log10log10flog10l](log10 "cpp/numeric/math/log10")
(C++11)(C++11) | computes common (base *10*) logarithm (\({\small \log\_{10}{x} }\)log10(x)) (function) |
| [log1plog1pflog1pl](log1p "cpp/numeric/math/log1p")
(C++11)(C++11)(C++11) | natural logarithm (to base *e*) of 1 plus the given number (\({\small \ln{(1+x)} }\)ln(1+x)) (function) |
| [exp2exp2fexp2l](exp2 "cpp/numeric/math/exp2")
(C++11)(C++11)(C++11) | returns *2* raised to the given power (\({\small 2^x}\)2x) (function) |
| [C documentation](https://en.cppreference.com/w/c/numeric/math/log2 "c/numeric/math/log2") for `log2` |
cpp std::round, std::roundf, std::roundl, std::lround, std::lroundf, std::lroundl, std::llround, std::llroundf std::round, std::roundf, std::roundl, std::lround, std::lroundf, std::lroundl, std::llround, std::llroundf
==========================================================================================================
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
|
```
float round ( float arg );
```
| (1) | (since C++11) (constexpr since C++23) |
|
```
float roundf( float arg );
```
| (2) | (since C++11) (constexpr since C++23) |
|
```
double round ( double arg );
```
| (3) | (since C++11) (constexpr since C++23) |
|
```
long double round ( long double arg );
```
| (4) | (since C++11) (constexpr since C++23) |
|
```
long double roundl( long double arg );
```
| (5) | (since C++11) (constexpr since C++23) |
|
```
double round ( IntegralType arg );
```
| (6) | (since C++11) (constexpr since C++23) |
|
```
long lround ( float arg );
```
| (7) | (since C++11) (constexpr since C++23) |
|
```
long lroundf( float arg );
```
| (8) | (since C++11) (constexpr since C++23) |
|
```
long lround ( double arg );
```
| (9) | (since C++11) (constexpr since C++23) |
|
```
long lround ( long double arg );
```
| (10) | (since C++11) (constexpr since C++23) |
|
```
long lroundl( long double arg );
```
| (11) | (since C++11) (constexpr since C++23) |
|
```
long lround ( IntegralType arg );
```
| (12) | (since C++11) (constexpr since C++23) |
|
```
long long llround ( float arg );
```
| (13) | (since C++11) (constexpr since C++23) |
|
```
long long llroundf( float arg );
```
| (14) | (since C++11) (constexpr since C++23) |
|
```
long long llround ( double arg );
```
| (15) | (since C++11) (constexpr since C++23) |
|
```
long long llround ( long double arg );
```
| (16) | (since C++11) (constexpr since C++23) |
|
```
long long llroundl( long double arg );
```
| (17) | (since C++11) (constexpr since C++23) |
|
```
long long llround ( IntegralType arg );
```
| (18) | (since C++11) (constexpr since C++23) |
1-5) Computes the nearest integer value to `arg` (in floating-point format), rounding halfway cases away from zero, regardless of the current rounding mode.
7-11,13-17) Computes the nearest integer value to `arg` (in integer format), rounding halfway cases away from zero, regardless of the current rounding mode.
6,12,18) A set of overloads or a function template accepting an argument of any [integral type](../../types/is_integral "cpp/types/is integral"). Equivalent to (3), (9), or (15), respectively (the argument is cast to `double`). ### Parameters
| | | |
| --- | --- | --- |
| arg | - | floating point value. |
### Return value
If no errors occur, the nearest integer value to `arg`, rounding halfway cases away from zero, is returned.
Return value ![math-round away zero.svg]() Argument If a domain error occurs, an implementation-defined value is returned.
### Error handling
Errors are reported as specified in `[math\_errhandling](math_errhandling "cpp/numeric/math/math errhandling")`.
If the result of `std::lround` or `std::llround` is outside the range representable by the return type, a domain error or a range error may occur.
If the implementation supports IEEE floating-point arithmetic (IEC 60559), For the `std::round` function:
* The current [rounding mode](../fenv/fe_round "cpp/numeric/fenv/FE round") has no effect.
* If `arg` is ยฑโ, it is returned, unmodified
* If `arg` is ยฑ0, it is returned, unmodified
* If `arg` is NaN, NaN is returned
For `std::lround` and `std::llround` functions: * `[FE\_INEXACT](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` is never raised
* The current [rounding mode](../fenv/fe_round "cpp/numeric/fenv/FE round") has no effect.
* If `arg` is ยฑโ, `[FE\_INVALID](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` is raised and an implementation-defined value is returned
* If the result of the rounding is outside the range of the return type, `[FE\_INVALID](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` is raised and an implementation-defined value is returned
* If `arg` is NaN, `[FE\_INVALID](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` is raised and an implementation-defined value is returned.
### Notes
`[FE\_INEXACT](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` may be (but isn't required to be) raised by `std::round` when rounding a non-integer finite value.
The largest representable floating-point values are exact integers in all standard floating-point formats, so `std::round` never overflows on its own; however the result may overflow any integer type (including `[std::intmax\_t](../../types/integer "cpp/types/integer")`), when stored in an integer variable.
[POSIX specifies](http://pubs.opengroup.org/onlinepubs/9699919799/functions/lround.html) that all cases where `std::lround` or `std::llround` raise `[FE\_INEXACT](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` are domain errors.
The `double` version of `std::round` behaves as if implemented as follows:
```
#include <cmath>
#include <cfenv>
#pragma STDC FENV_ACCESS ON
double round(double x)
{
std::fenv_t save_env;
std::feholdexcept(&save_env);
double result = std::rint(x);
if (std::fetestexcept(FE_INEXACT)) {
auto const save_round = std::fegetround();
std::fesetround(FE_TOWARDZERO);
result = std::rint(std::copysign(0.5 + std::fabs(x), x));
std::fesetround(save_round);
}
std::feupdateenv(&save_env);
return result;
}
```
### Example
```
#include <iostream>
#include <cmath>
#include <cfenv>
#include <climits>
// #pragma STDC FENV_ACCESS ON
int main()
{
// round
std::cout << "round(+2.3) = " << std::round(2.3)
<< " round(+2.5) = " << std::round(2.5)
<< " round(+2.7) = " << std::round(2.7) << '\n'
<< "round(-2.3) = " << std::round(-2.3)
<< " round(-2.5) = " << std::round(-2.5)
<< " round(-2.7) = " << std::round(-2.7) << '\n';
std::cout << "round(-0.0) = " << std::round(-0.0) << '\n'
<< "round(-Inf) = " << std::round(-INFINITY) << '\n';
// lround
std::cout << "lround(+2.3) = " << std::lround(2.3)
<< " lround(+2.5) = " << std::lround(2.5)
<< " lround(+2.7) = " << std::lround(2.7) << '\n'
<< "lround(-2.3) = " << std::lround(-2.3)
<< " lround(-2.5) = " << std::lround(-2.5)
<< " lround(-2.7) = " << std::lround(-2.7) << '\n';
std::cout << "lround(-0.0) = " << std::lround(-0.0) << '\n'
<< "lround(-Inf) = " << std::lround(-INFINITY) << '\n';
// error handling
std::feclearexcept(FE_ALL_EXCEPT);
std::cout << "std::lround(LONG_MAX+1.5) = "
<< std::lround(LONG_MAX+1.5) << '\n';
if (std::fetestexcept(FE_INVALID))
std::cout << " FE_INVALID was raised\n";
}
```
Possible output:
```
round(+2.3) = 2 round(+2.5) = 3 round(+2.7) = 3
round(-2.3) = -2 round(-2.5) = -3 round(-2.7) = -3
round(-0.0) = -0
round(-Inf) = -inf
lround(+2.3) = 2 lround(+2.5) = 3 lround(+2.7) = 3
lround(-2.3) = -2 lround(-2.5) = -3 lround(-2.7) = -3
lround(-0.0) = 0
lround(-Inf) = -9223372036854775808
std::lround(LONG_MAX+1.5) = -9223372036854775808
FE_INVALID was raised
```
### See also
| | |
| --- | --- |
| [floorfloorffloorl](floor "cpp/numeric/math/floor")
(C++11)(C++11) | nearest integer not greater than the given value (function) |
| [ceilceilfceill](ceil "cpp/numeric/math/ceil")
(C++11)(C++11) | nearest integer not less than the given value (function) |
| [trunctruncftruncl](trunc "cpp/numeric/math/trunc")
(C++11)(C++11)(C++11) | nearest integer not greater in magnitude than the given value (function) |
| [C documentation](https://en.cppreference.com/w/c/numeric/math/round "c/numeric/math/round") for `round` |
cpp std::cos, std::cosf, std::cosl std::cos, std::cosf, std::cosl
==============================
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
| | (1) | |
|
```
float cos ( float arg );
```
| |
|
```
float cosf( float arg );
```
| (since C++11) |
|
```
double cos ( double arg );
```
| (2) | |
| | (3) | |
|
```
long double cos ( long double arg );
```
| |
|
```
long double cosl( long double arg );
```
| (since C++11) |
|
```
double cos ( IntegralType arg );
```
| (4) | (since C++11) |
1-3) Computes the cosine of `arg` (measured in radians).
4) A set of overloads or a function template accepting an argument of any [integral type](../../types/is_integral "cpp/types/is integral"). Equivalent to 2) (the argument is cast to `double`). ### Parameters
| | | |
| --- | --- | --- |
| arg | - | value representing angle in radians, of a floating-point or [Integral type](../../types/is_integral "cpp/types/is integral") |
### Return value
If no errors occur, the cosine of `arg` (cos(arg)) in the range [-1 ; +1], is returned.
| | |
| --- | --- |
| The result may have little or no significance if the magnitude of `arg` is large. | (until C++11) |
If a domain error occurs, an implementation-defined value is returned (NaN where supported).
If a range error occurs due to underflow, the correct result (after rounding) is returned.
### Error handling
Errors are reported as specified in `[math\_errhandling](math_errhandling "cpp/numeric/math/math errhandling")`.
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* if the argument is ยฑ0, the result is 1.0
* if the argument is ยฑโ, NaN is returned and `[FE\_INVALID](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` is raised
* if the argument is NaN, NaN is returned
### Notes
The case where the argument is infinite is not specified to be a domain error in C, but it is defined as a [domain error in POSIX](http://pubs.opengroup.org/onlinepubs/9699919799/functions/cos.html).
### Example
```
#include <iostream>
#include <cmath>
#include <cerrno>
#include <cfenv>
#pragma STDC FENV_ACCESS ON
const double pi = std::acos(-1);
int main()
{
// typical usage
std::cout << "cos(pi/3) = " << std::cos(pi/3) << '\n'
<< "cos(pi/2) = " << std::cos(pi/2) << '\n'
<< "cos(-3*pi/4) = " << std::cos(-3*pi/4) << '\n';
// special values
std::cout << "cos(+0) = " << std::cos(0.0) << '\n'
<< "cos(-0) = " << std::cos(-0.0) << '\n';
// error handling
std::feclearexcept(FE_ALL_EXCEPT);
std::cout << "cos(INFINITY) = " << std::cos(INFINITY) << '\n';
if (std::fetestexcept(FE_INVALID))
std::cout << " FE_INVALID raised\n";
}
```
Possible output:
```
cos(pi/3) = 0.5
cos(pi/2) = 6.12323e-17
cos(-3*pi/4) = -0.707107
cos(+0) = 1
cos(-0) = 1
cos(INFINITY) = -nan
FE_INVALID raised
```
### See also
| | |
| --- | --- |
| [sinsinfsinl](sin "cpp/numeric/math/sin")
(C++11)(C++11) | computes sine (\({\small\sin{x} }\)sin(x)) (function) |
| [tantanftanl](tan "cpp/numeric/math/tan")
(C++11)(C++11) | computes tangent (\({\small\tan{x} }\)tan(x)) (function) |
| [acosacosfacosl](acos "cpp/numeric/math/acos")
(C++11)(C++11) | computes arc cosine (\({\small\arccos{x} }\)arccos(x)) (function) |
| [cos(std::complex)](../complex/cos "cpp/numeric/complex/cos") | computes cosine of a complex number (\({\small\cos{z} }\)cos(z)) (function template) |
| [cos(std::valarray)](../valarray/cos "cpp/numeric/valarray/cos") | applies the function `std::cos` to each element of valarray (function template) |
| [C documentation](https://en.cppreference.com/w/c/numeric/math/cos "c/numeric/math/cos") for `cos` |
cpp std::remainder, std::remainderf, std::remainderl std::remainder, std::remainderf, std::remainderl
================================================
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
|
```
float remainder ( float x, float y );
```
| (1) | (since C++11) (constexpr since C++23) |
|
```
float remainderf( float x, float y );
```
| (2) | (since C++11) (constexpr since C++23) |
|
```
double remainder ( double x, double y );
```
| (3) | (since C++11) (constexpr since C++23) |
|
```
long double remainder ( long double x, long double y );
```
| (4) | (since C++11) (constexpr since C++23) |
|
```
long double remainderl( long double x, long double y );
```
| (5) | (since C++11) (constexpr since C++23) |
|
```
Promoted remainder ( Arithmetic1 x, Arithmetic2 y );
```
| (6) | (since C++11) (constexpr since C++23) |
1-5) Computes the IEEE remainder of the floating point division operation `x/y`.
6) A set of overloads or a function template for all combinations of arguments of [arithmetic type](../../types/is_arithmetic "cpp/types/is arithmetic") not covered by (1-5). If any argument has [integral type](../../types/is_integral "cpp/types/is integral"), it is cast to `double`. If any other argument is `long double`, then the return type is `long double`, otherwise it is `double`. The IEEE floating-point remainder of the division operation `x/y` calculated by this function is exactly the value `x - n*y`, where the value `n` is the integral value nearest the exact value `x/y`. When |n-x/y| = ยฝ, the value `n` is chosen to be even.
In contrast to `[std::fmod()](fmod "cpp/numeric/math/fmod")`, the returned value is not guaranteed to have the same sign as `x`.
If the returned value is `0`, it will have the same sign as `x`.
### Parameters
| | | |
| --- | --- | --- |
| x, y | - | values of floating-point or [integral types](../../types/is_integral "cpp/types/is integral") |
### Return value
If successful, returns the IEEE floating-point remainder of the division `x/y` as defined above.
If a domain error occurs, an implementation-defined value is returned (NaN where supported).
If a range error occurs due to underflow, the correct result is returned.
If `y` is zero, but the domain error does not occur, zero is returned.
### Error handling
Errors are reported as specified in `[math\_errhandling](math_errhandling "cpp/numeric/math/math errhandling")`.
Domain error may occur if `y` is zero.
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* The current [rounding mode](../fenv/fe_round "cpp/numeric/fenv/FE round") has no effect.
* `[FE\_INEXACT](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` is never raised, the result is always exact.
* If `x` is ยฑโ and `y` is not NaN, NaN is returned and `[FE\_INVALID](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` is raised
* If `y` is ยฑ0 and `x` is not NaN, NaN is returned and `[FE\_INVALID](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` is raised
* If either argument is NaN, NaN is returned
### Notes
[POSIX requires](http://pubs.opengroup.org/onlinepubs/9699919799/functions/remainder.html) that a domain error occurs if `x` is infinite or `y` is zero.
`[std::fmod](fmod "cpp/numeric/math/fmod")`, but not `std::remainder` is useful for doing silent wrapping of floating-point types to unsigned integer types: `(0.0 <= (y = [std::fmod](http://en.cppreference.com/w/cpp/numeric/math/fmod)( [std::rint](http://en.cppreference.com/w/cpp/numeric/math/rint)(x), 65536.0 )) ? y : 65536.0 + y)` is in the range `[-0.0 .. 65535.0]`, which corresponds to `unsigned short`, but `std::remainder([std::rint](http://en.cppreference.com/w/cpp/numeric/math/rint)(x), 65536.0)` is in the range `[-32767.0, +32768.0]`, which is outside of the range of `signed short`.
### Example
```
#include <iostream>
#include <cmath>
#include <cfenv>
// #pragma STDC FENV_ACCESS ON
int main()
{
std::cout << "remainder(+5.1, +3.0) = " << std::remainder(5.1,3) << '\n'
<< "remainder(-5.1, +3.0) = " << std::remainder(-5.1,3) << '\n'
<< "remainder(+5.1, -3.0) = " << std::remainder(5.1,-3) << '\n'
<< "remainder(-5.1, -3.0) = " << std::remainder(-5.1,-3) << '\n';
// special values
std::cout << "remainder(-0.0, 1.0) = " << std::remainder(-0.0, 1) << '\n'
<< "remainder(5.1, Inf) = " << std::remainder(5.1, INFINITY) << '\n';
// error handling
std::feclearexcept(FE_ALL_EXCEPT);
std::cout << "remainder(+5.1, 0) = " << std::remainder(5.1, 0) << '\n';
if(fetestexcept(FE_INVALID))
std::cout << " FE_INVALID raised\n";
}
```
Possible output:
```
remainder(+5.1, +3.0) = -0.9
remainder(-5.1, +3.0) = 0.9
remainder(+5.1, -3.0) = -0.9
remainder(-5.1, -3.0) = 0.9
remainder(-0.0, 1.0) = -0
remainder(5.1, Inf) = 5.1
remainder(+5.1, 0) = -nan
FE_INVALID raised
```
### See also
| | |
| --- | --- |
| [div(int)ldivlldiv](div "cpp/numeric/math/div")
(C++11) | computes quotient and remainder of integer division (function) |
| [fmodfmodffmodl](fmod "cpp/numeric/math/fmod")
(C++11)(C++11) | remainder of the floating point division operation (function) |
| [remquoremquofremquol](remquo "cpp/numeric/math/remquo")
(C++11)(C++11)(C++11) | signed remainder as well as the three last bits of the division operation (function) |
| [C documentation](https://en.cppreference.com/w/c/numeric/math/remainder "c/numeric/math/remainder") for `remainder` |
| programming_docs |
cpp std::erf, std::erff, std::erfl std::erf, std::erff, std::erfl
==============================
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
|
```
float erf ( float arg );
float erff( float arg );
```
| (1) | (since C++11) |
|
```
double erf ( double arg );
```
| (2) | (since C++11) |
|
```
long double erf ( long double arg );
long double erfl( long double arg );
```
| (3) | (since C++11) |
|
```
double erf ( IntegralType arg );
```
| (4) | (since C++11) |
1-3) Computes the [error function](https://en.wikipedia.org/wiki/Error_function "enwiki:Error function") of `arg`.
4) A set of overloads or a function template accepting an argument of any [integral type](../../types/is_integral "cpp/types/is integral"). Equivalent to (2) (the argument is cast to `double`). ### Parameters
| | | |
| --- | --- | --- |
| arg | - | value of a floating-point or [integral type](../../types/is_integral "cpp/types/is integral") |
### Return value
If no errors occur, value of the error function of `arg`, that is \(\frac{2}{\sqrt{\pi} }\int\_{0}^{arg}{e^{-{t^2} }\mathsf{d}t}\)2/โฯโซarg
0*e*-t2d*t*, is returned.
If a range error occurs due to underflow, the correct result (after rounding), that is \(\frac{2\cdot arg}{\sqrt{\pi} }\).
2\*arg/โฯ is returned ### Error handling
Errors are reported as specified in `[math\_errhandling](math_errhandling "cpp/numeric/math/math errhandling")`.
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* If the argument is ยฑ0, ยฑ0 is returned
* If the argument is ยฑโ, ยฑ1 is returned
* If the argument is NaN, NaN is returned
### Notes
Underflow is guaranteed if `|arg| < [DBL\_MIN](http://en.cppreference.com/w/cpp/types/climits)\*(sqrt(ฯ)/2)` \(\operatorname{erf}(\frac{x}{\sigma \sqrt{2} })\)erf(
x/ฯโ2) is the probability that a measurement whose errors are subject to a normal distribution with standard deviation \(\sigma\)ฯ is less than \(x\)x away from the mean value. ### Example
The following example calculates the probability that a normal variate is on the interval (x1, x2).
```
#include <iostream>
#include <cmath>
#include <iomanip>
double phi(double x1, double x2)
{
return (std::erf(x2/std::sqrt(2)) - std::erf(x1/std::sqrt(2)))/2;
}
int main()
{
std::cout << "normal variate probabilities:\n"
<< std::fixed << std::setprecision(2);
for(int n=-4; n<4; ++n)
std::cout << "[" << std::setw(2) << n << ":" << std::setw(2) << n+1 << "]: "
<< std::setw(5) << 100*phi(n, n+1) << "%\n";
std::cout << "special values:\n"
<< "erf(-0) = " << std::erf(-0.0) << '\n'
<< "erf(Inf) = " << std::erf(INFINITY) << '\n';
}
```
Output:
```
normal variate probabilities:
[-4:-3]: 0.13%
[-3:-2]: 2.14%
[-2:-1]: 13.59%
[-1: 0]: 34.13%
[ 0: 1]: 34.13%
[ 1: 2]: 13.59%
[ 2: 3]: 2.14%
[ 3: 4]: 0.13%
special values:
erf(-0) = -0.00
erf(Inf) = 1.00
```
### See also
| | |
| --- | --- |
| [erfcerfcferfcl](erfc "cpp/numeric/math/erfc")
(C++11)(C++11)(C++11) | complementary error function (function) |
| [C documentation](https://en.cppreference.com/w/c/numeric/math/erf "c/numeric/math/erf") for `erf` |
### External links
[Weisstein, Eric W. "Erf."](http://mathworld.wolfram.com/Erf.html) From MathWorld--A Wolfram Web Resource.
cpp MATH_ERRNO, MATH_ERREXCEPT, math_errhandling MATH\_ERRNO, MATH\_ERREXCEPT, math\_errhandling
===============================================
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
|
```
#define MATH_ERRNO 1
```
| | (since C++11) |
|
```
#define MATH_ERREXCEPT 2
```
| | (since C++11) |
|
```
#define math_errhandling /*implementation defined*/
```
| | (since C++11) |
The macro constant `math_errhandling` expands to an expression of type `int` that is either equal to `MATH_ERRNO`, or equal to `MATH_ERREXCEPT`, or equal to their bitwise OR (`MATH_ERRNO | MATH_ERREXCEPT`).
The value of `math_errhandling` indicates the type of error handling that is performed by the floating-point operators and [functions](../math "cpp/numeric/math"):
| Constant | Explanation |
| --- | --- |
| `MATH_ERREXCEPT` | indicates that floating-point exceptions are used: at least `[FE\_DIVBYZERO](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")`, `[FE\_INVALID](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")`, and `[FE\_OVERFLOW](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` are defined in `<cfenv>`. |
| `MATH_ERRNO` | indicates that floating-point operations use the variable `[errno](../../error/errno "cpp/error/errno")` to report errors. |
If the implementation supports IEEE floating-point arithmetic (IEC 60559), `math_errhandling & MATH_ERREXCEPT` is required to be non-zero.
The following floating-point error conditions are recognized:
| Condition | Explanation | errno | floating-point exception | Example |
| --- | --- | --- | --- | --- |
| Domain error | the argument is outside the range in which the operation is mathematically defined (the description of [each function](../math "cpp/numeric/math") lists the required domain errors) | `[EDOM](../../error/errno_macros "cpp/error/errno macros")` | `[FE\_INVALID](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` | `[std::acos](http://en.cppreference.com/w/cpp/numeric/math/acos)(2)` |
| Pole error | the mathematical result of the function is exactly infinite or undefined | `[ERANGE](../../error/errno_macros "cpp/error/errno macros")` | `[FE\_DIVBYZERO](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` | `[std::log](http://en.cppreference.com/w/cpp/numeric/math/log)(0.0)`, `1.0/0.0` |
| Range error due to overflow | the mathematical result is finite, but becomes infinite after rounding, or becomes the largest representable finite value after rounding down | `[ERANGE](../../error/errno_macros "cpp/error/errno macros")` | `[FE\_OVERFLOW](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` | `[std::pow](http://en.cppreference.com/w/cpp/numeric/math/pow)([DBL\_MAX](http://en.cppreference.com/w/cpp/types/climits),2)` |
| Range error due to underflow | the result is non-zero, but becomes zero after rounding, or becomes subnormal with a loss of precision | `[ERANGE](../../error/errno_macros "cpp/error/errno macros")` or unchanged (implementation-defined) | `[FE\_UNDERFLOW](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` or nothing (implementation-defined) | `[DBL\_TRUE\_MIN](http://en.cppreference.com/w/cpp/types/climits)/2` |
| Inexact result | the result has to be rounded to fit in the destination type | unchanged | `[FE\_INEXACT](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` or nothing (unspecified) | `[std::sqrt](http://en.cppreference.com/w/cpp/numeric/math/sqrt)(2)`, `1.0/10.0` |
### Notes
Whether `[FE\_INEXACT](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` is raised by the mathematical library functions is unspecified in general, but may be explicitly specified in the description of the function (e.g. `[std::rint](rint "cpp/numeric/math/rint")` vs `[std::nearbyint](nearbyint "cpp/numeric/math/nearbyint")`).
Before C++11, floating-point exceptions were not specified, `[EDOM](http://en.cppreference.com/w/cpp/error/errno_macros)` was required for any domain error, `[ERANGE](http://en.cppreference.com/w/cpp/error/errno_macros)` was required for overflows and implementation-defined for underflows.
### Example
```
#include <iostream>
#include <cfenv>
#include <cmath>
#include <cerrno>
#include <cstring>
#pragma STDC FENV_ACCESS ON
int main()
{
std::cout << "MATH_ERRNO is "
<< (math_errhandling & MATH_ERRNO ? "set" : "not set") << '\n'
<< "MATH_ERREXCEPT is "
<< (math_errhandling & MATH_ERREXCEPT ? "set" : "not set") << '\n';
std::feclearexcept(FE_ALL_EXCEPT);
errno = 0;
std::cout << "log(0) = " << std::log(0) << '\n';
if(errno == ERANGE)
std::cout << "errno = ERANGE (" << std::strerror(errno) << ")\n";
if(std::fetestexcept(FE_DIVBYZERO))
std::cout << "FE_DIVBYZERO (pole error) reported\n";
}
```
Possible output:
```
MATH_ERRNO is set
MATH_ERREXCEPT is set
log(0) = -inf
errno = ERANGE (Numerical result out of range)
FE_DIVBYZERO (pole error) reported
```
### See also
| | |
| --- | --- |
| [FE\_ALL\_EXCEPTFE\_DIVBYZEROFE\_INEXACTFE\_INVALIDFE\_OVERFLOWFE\_UNDERFLOW](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")
(C++11) | floating-point exceptions (macro constant) |
| [errno](../../error/errno "cpp/error/errno") | macro which expands to POSIX-compatible thread-local error number variable(macro variable) |
| [C documentation](https://en.cppreference.com/w/c/numeric/math/math_errhandling "c/numeric/math/math errhandling") for `math_errhandling` |
cpp std::nearbyint, std::nearbyintf, std::nearbyintl std::nearbyint, std::nearbyintf, std::nearbyintl
================================================
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
|
```
float nearbyint ( float arg );
float nearbyintf( float arg );
```
| (1) | (since C++11) |
|
```
double nearbyint ( double arg );
```
| (2) | (since C++11) |
|
```
long double nearbyint ( long double arg );
long double nearbyintl( long double arg );
```
| (3) | (since C++11) |
|
```
double nearbyint ( IntegralType arg );
```
| (4) | (since C++11) |
1-3) Rounds the floating-point argument `arg` to an integer value in floating-point format, using the [current rounding mode](../fenv/fe_round "cpp/numeric/fenv/FE round").
4) A set of overloads or a function template accepting an argument of any [integral type](../../types/is_integral "cpp/types/is integral"). Equivalent to (2) (the argument is cast to `double`). ### Parameters
| | | |
| --- | --- | --- |
| arg | - | floating point value |
### Return value
The nearest integer value to `arg`, according to the [current rounding mode](../fenv/fe_round "cpp/numeric/fenv/FE round"), is returned.
### Error handling
This function is not subject to any of the errors specified in `[math\_errhandling](math_errhandling "cpp/numeric/math/math errhandling")`.
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* `[FE\_INEXACT](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` is never raised
* If `arg` is ยฑโ, it is returned, unmodified
* If `arg` is ยฑ0, it is returned, unmodified
* If `arg` is NaN, NaN is returned
### Notes
The only difference between `std::nearbyint` and `[std::rint](rint "cpp/numeric/math/rint")` is that `std::nearbyint` never raises `[FE\_INEXACT](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")`.
The largest representable floating-point values are exact integers in all standard floating-point formats, so `std::nearbyint` never overflows on its own; however the result may overflow any integer type (including `[std::intmax\_t](../../types/integer "cpp/types/integer")`), when stored in an integer variable.
If the current rounding mode is `[FE\_TONEAREST](../fenv/fe_round "cpp/numeric/fenv/FE round")`, this function rounds to even in halfway cases (like `rint`, but unlike `round`).
### Example
```
#include <iostream>
#include <cmath>
#include <cfenv>
int main()
{
#pragma STDC FENV_ACCESS ON
std::fesetround(FE_TONEAREST);
std::cout << "rounding to nearest: \n"
<< "nearbyint(+2.3) = " << std::nearbyint(2.3)
<< " nearbyint(+2.5) = " << std::nearbyint(2.5)
<< " nearbyint(+3.5) = " << std::nearbyint(3.5) << '\n'
<< "nearbyint(-2.3) = " << std::nearbyint(-2.3)
<< " nearbyint(-2.5) = " << std::nearbyint(-2.5)
<< " nearbyint(-3.5) = " << std::nearbyint(-3.5) << '\n';
std::fesetround(FE_DOWNWARD);
std::cout << "rounding down:\n"
<< "nearbyint(+2.3) = " << std::nearbyint(2.3)
<< " nearbyint(+2.5) = " << std::nearbyint(2.5)
<< " nearbyint(+3.5) = " << std::nearbyint(3.5) << '\n'
<< "nearbyint(-2.3) = " << std::nearbyint(-2.3)
<< " nearbyint(-2.5) = " << std::nearbyint(-2.5)
<< " nearbyint(-3.5) = " << std::nearbyint(-3.5) << '\n';
std::cout << "nearbyint(-0.0) = " << std::nearbyint(-0.0) << '\n'
<< "nearbyint(-Inf) = " << std::nearbyint(-INFINITY) << '\n';
}
```
Output:
```
rounding to nearest:
nearbyint(+2.3) = 2 nearbyint(+2.5) = 2 nearbyint(+3.5) = 4
nearbyint(-2.3) = -2 nearbyint(-2.5) = -2 nearbyint(-3.5) = -4
rounding down:
nearbyint(+2.3) = 2 nearbyint(+2.5) = 2 nearbyint(+3.5) = 3
nearbyint(-2.3) = -3 nearbyint(-2.5) = -3 nearbyint(-3.5) = -4
nearbyint(-0.0) = -0
nearbyint(-Inf) = -inf
```
### See also
| | |
| --- | --- |
| [rintrintfrintllrintlrintflrintlllrintllrintfllrintl](rint "cpp/numeric/math/rint")
(C++11)(C++11)(C++11)(C++11)(C++11)(C++11)(C++11)(C++11)(C++11) | nearest integer using current rounding mode with exception if the result differs (function) |
| [roundroundfroundllroundlroundflroundlllroundllroundfllroundl](round "cpp/numeric/math/round")
(C++11)(C++11)(C++11)(C++11)(C++11)(C++11)(C++11)(C++11)(C++11) | nearest integer, rounding away from zero in halfway cases (function) |
| [fegetroundfesetround](../fenv/feround "cpp/numeric/fenv/feround")
(C++11)(C++11) | gets or sets rounding direction (function) |
| [C documentation](https://en.cppreference.com/w/c/numeric/math/nearbyint "c/numeric/math/nearbyint") for `nearbyint` |
cpp std::isfinite std::isfinite
=============
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
|
```
bool isfinite( float arg );
```
| (1) | (since C++11) (constexpr since C++23) |
|
```
bool isfinite( double arg );
```
| (2) | (since C++11) (constexpr since C++23) |
|
```
bool isfinite( long double arg );
```
| (3) | (since C++11) (constexpr since C++23) |
|
```
bool isfinite( IntegralType arg );
```
| (4) | (since C++11) (constexpr since C++23) |
1-3) Determines if the given floating point number `arg` has finite value i.e. it is normal, subnormal or zero, but not infinite or NaN.
4) A set of overloads or a function template accepting the `arg` argument of any [integral type](../../types/is_integral "cpp/types/is integral"). Equivalent to (2) (the argument is cast to `double`). ### Parameters
| | | |
| --- | --- | --- |
| arg | - | floating point value |
### Return value
`true` if `arg` has finite value, `false` otherwise.
### Examples
```
#include <iostream>
#include <cmath>
#include <cfloat>
int main()
{
std::cout << std::boolalpha
<< "isfinite(NaN) = " << std::isfinite(NAN) << '\n'
<< "isfinite(Inf) = " << std::isfinite(INFINITY) << '\n'
<< "isfinite(0.0) = " << std::isfinite(0.0) << '\n'
<< "isfinite(exp(800)) = " << std::isfinite(std::exp(800)) << '\n'
<< "isfinite(DBL_MIN/2.0) = " << std::isfinite(DBL_MIN/2.0) << '\n';
}
```
Output:
```
isfinite(NaN) = false
isfinite(Inf) = false
isfinite(0.0) = true
isfinite(exp(800)) = false
isfinite(DBL_MIN/2.0) = true
```
### See also
| | |
| --- | --- |
| [fpclassify](fpclassify "cpp/numeric/math/fpclassify")
(C++11) | categorizes the given floating-point value (function) |
| [isinf](isinf "cpp/numeric/math/isinf")
(C++11) | checks if the given number is infinite (function) |
| [isnan](isnan "cpp/numeric/math/isnan")
(C++11) | checks if the given number is NaN (function) |
| [isnormal](isnormal "cpp/numeric/math/isnormal")
(C++11) | checks if the given number is normal (function) |
| [C documentation](https://en.cppreference.com/w/c/numeric/math/isfinite "c/numeric/math/isfinite") for `isfinite` |
cpp std::sqrt, std::sqrtf, std::sqrtl std::sqrt, std::sqrtf, std::sqrtl
=================================
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
| | (1) | |
|
```
float sqrt ( float arg );
```
| |
|
```
float sqrtf( float arg );
```
| (since C++11) |
|
```
double sqrt ( double arg );
```
| (2) | |
| | (3) | |
|
```
long double sqrt ( long double arg );
```
| |
|
```
long double sqrtl( long double arg );
```
| (since C++11) |
|
```
double sqrt ( IntegralType arg );
```
| (4) | (since C++11) |
1-3) Computes the square root of `arg`.
4) A set of overloads or a function template accepting an argument of any [integral type](../../types/is_integral "cpp/types/is integral"). Equivalent to (2) (the argument is cast to `double`). ### Parameters
| | | |
| --- | --- | --- |
| arg | - | Value of a floating-point or [integral type](../../types/is_integral "cpp/types/is integral") |
### Return value
If no errors occur, square root of `arg` (\({\small \sqrt{arg} }\)โarg), is returned.
If a domain error occurs, an implementation-defined value is returned (NaN where supported).
If a range error occurs due to underflow, the correct result (after rounding) is returned.
### Error handling
Errors are reported as specified in `[math\_errhandling](math_errhandling "cpp/numeric/math/math errhandling")`.
Domain error occurs if `arg` is less than zero.
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* If the argument is less than -0, `[FE\_INVALID](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` is raised and NaN is returned.
* If the argument is +โ or ยฑ0, it is returned, unmodified.
* If the argument is NaN, NaN is returned
### Notes
`std::sqrt` is required by the IEEE standard to be exact. The only other operations required to be exact are the [arithmetic operators](../../language/operator_arithmetic "cpp/language/operator arithmetic") and the function `[std::fma](fma "cpp/numeric/math/fma")`. After rounding to the return type (using default rounding mode), the result of `std::sqrt` is indistinguishable from the infinitely precise result. In other words, the error is less than 0.5 ulp. Other functions, including `[std::pow](pow "cpp/numeric/math/pow")`, are not so constrained.
### Example
```
#include <iostream>
#include <cmath>
#include <cerrno>
#include <cfenv>
#include <cstring>
#pragma STDC FENV_ACCESS ON
int main()
{
// normal use
std::cout << "sqrt(100) = " << std::sqrt(100) << '\n'
<< "sqrt(2) = " << std::sqrt(2) << '\n'
<< "golden ratio = " << (1+std::sqrt(5))/2 << '\n';
// special values
std::cout << "sqrt(-0) = " << std::sqrt(-0.0) << '\n';
// error handling
errno = 0;
std::feclearexcept(FE_ALL_EXCEPT);
std::cout << "sqrt(-1.0) = " << std::sqrt(-1) << '\n';
if(errno == EDOM)
std::cout << " errno = EDOM " << std::strerror(errno) << '\n';
if(std::fetestexcept(FE_INVALID))
std::cout << " FE_INVALID raised\n";
}
```
Possible output:
```
sqrt(100) = 10
sqrt(2) = 1.41421
golden ratio = 1.61803
sqrt(-0) = -0
sqrt(-1.0) = -nan
errno = EDOM Numerical argument out of domain
FE_INVALID raised
```
### See also
| | |
| --- | --- |
| [powpowfpowl](pow "cpp/numeric/math/pow")
(C++11)(C++11) | raises a number to the given power (\(\small{x^y}\)xy) (function) |
| [cbrtcbrtfcbrtl](cbrt "cpp/numeric/math/cbrt")
(C++11)(C++11)(C++11) | computes cubic root (\(\small{\sqrt[3]{x} }\)3โx) (function) |
| [hypothypotfhypotl](hypot "cpp/numeric/math/hypot")
(C++11)(C++11)(C++11) | computes square root of the sum of the squares of two or three (C++17) given numbers (\(\scriptsize{\sqrt{x^2+y^2} }\)โx2+y2), (\(\scriptsize{\sqrt{x^2+y^2+z^2} }\)โx2+y2+z2) (function) |
| [sqrt(std::complex)](../complex/sqrt "cpp/numeric/complex/sqrt") | complex square root in the range of the right half-plane (function template) |
| [sqrt(std::valarray)](../valarray/sqrt "cpp/numeric/valarray/sqrt") | applies the function `std::sqrt` to each element of valarray (function template) |
| [C documentation](https://en.cppreference.com/w/c/numeric/math/sqrt "c/numeric/math/sqrt") for `sqrt` |
| programming_docs |
cpp std::logb, std::logbf, std::logbl std::logb, std::logbf, std::logbl
=================================
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
|
```
float logb ( float arg );
```
| (1) | (since C++11) (constexpr since C++23) |
|
```
float logbf( float arg );
```
| (2) | (since C++11) (constexpr since C++23) |
|
```
double logb ( double arg );
```
| (3) | (since C++11) (constexpr since C++23) |
|
```
long double logb ( long double arg );
```
| (4) | (since C++11) (constexpr since C++23) |
|
```
long double logbl( long double arg );
```
| (5) | (since C++11) (constexpr since C++23) |
|
```
double logb ( IntegralType arg );
```
| (6) | (since C++11) (constexpr since C++23) |
1-5) Extracts the value of the unbiased radix-independent exponent from the floating-point argument `arg`, and returns it as a floating-point value.
6) A set of overloads or a function template accepting an argument of any [integral type](../../types/is_integral "cpp/types/is integral"). Equivalent to (3) (the argument is cast to `double`). Formally, the unbiased exponent is the signed integral part of log
r|arg| (returned by this function as a floating-point value), for non-zero arg, where `r` is `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::radix` and `T` is the floating-point type of `arg`. If `arg` is subnormal, it is treated as though it was normalized.
### Parameters
| | | |
| --- | --- | --- |
| arg | - | floating point value |
### Return value
If no errors occur, the unbiased exponent of `arg` is returned as a signed floating-point value.
If a domain error occurs, an implementation-defined value is returned.
If a pole error occurs, `[-HUGE\_VAL](huge_val "cpp/numeric/math/HUGE VAL")`, `-HUGE_VALF`, or `-HUGE_VALL` is returned.
### Error handling
Errors are reported as specified in `[math\_errhandling](math_errhandling "cpp/numeric/math/math errhandling")`.
Domain or range error may occur if `arg` is zero.
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* If `arg` is ยฑ0, -โ is returned and `[FE\_DIVBYZERO](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` is raised.
* If `arg` is ยฑโ, +โ is returned
* If `arg` is NaN, NaN is returned.
* In all other cases, the result is exact (`[FE\_INEXACT](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` is never raised) and [the current rounding mode](../fenv/fe_round "cpp/numeric/fenv/FE round") is ignored
### Notes
[POSIX requires](http://pubs.opengroup.org/onlinepubs/9699919799/functions/logb.html) that a pole error occurs if `arg` is ยฑ0.
The value of the exponent returned by `std::logb` is always 1 less than the exponent returned by `[std::frexp](frexp "cpp/numeric/math/frexp")` because of the different normalization requirements: for the exponent `e` returned by `std::logb`, |arg\*r-e
| is between 1 and `r` (typically between `1` and `2`), but for the exponent `e` returned by `[std::frexp](frexp "cpp/numeric/math/frexp")`, |arg\*2-e
| is between `0.5` and `1`.
### Example
Compares different floating-point decomposition functions.
```
#include <iostream>
#include <cmath>
#include <limits>
#include <cfenv>
#pragma STDC FENV_ACCESS ON
int main()
{
double f = 123.45;
std::cout << "Given the number " << f << " or " << std::hexfloat
<< f << std::defaultfloat << " in hex,\n";
double f3;
double f2 = std::modf(f, &f3);
std::cout << "modf() makes " << f3 << " + " << f2 << '\n';
int i;
f2 = std::frexp(f, &i);
std::cout << "frexp() makes " << f2 << " * 2^" << i << '\n';
i = std::ilogb(f);
std::cout << "logb()/ilogb() make " << f/std::scalbn(1.0, i) << " * "
<< std::numeric_limits<double>::radix
<< "^" << std::ilogb(f) << '\n';
// error handling
std::feclearexcept(FE_ALL_EXCEPT);
std::cout << "logb(0) = " << std::logb(0) << '\n';
if (std::fetestexcept(FE_DIVBYZERO))
std::cout << " FE_DIVBYZERO raised\n";
}
```
Possible output:
```
Given the number 123.45 or 0x1.edccccccccccdp+6 in hex,
modf() makes 123 + 0.45
frexp() makes 0.964453 * 2^7
logb()/ilogb() make 1.92891 * 2^6
logb(0) = -Inf
FE_DIVBYZERO raised
```
### See also
| | |
| --- | --- |
| [frexpfrexpffrexpl](frexp "cpp/numeric/math/frexp")
(C++11)(C++11) | decomposes a number into significand and a power of `2` (function) |
| [ilogbilogbfilogbl](ilogb "cpp/numeric/math/ilogb")
(C++11)(C++11)(C++11) | extracts exponent of the number (function) |
| [scalbnscalbnfscalbnlscalblnscalblnfscalblnl](scalbn "cpp/numeric/math/scalbn")
(C++11)(C++11)(C++11)(C++11)(C++11)(C++11) | multiplies a number by `[FLT\_RADIX](../../types/climits "cpp/types/climits")` raised to a power (function) |
| [C documentation](https://en.cppreference.com/w/c/numeric/math/logb "c/numeric/math/logb") for `logb` |
cpp std::tanh, std::tanhf, std::tanhl std::tanh, std::tanhf, std::tanhl
=================================
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
| | (1) | |
|
```
float tanh ( float arg );
```
| |
|
```
float tanhf( float arg );
```
| (since C++11) |
|
```
double tanh ( double arg );
```
| (2) | |
| | (3) | |
|
```
long double tanh ( long double arg );
```
| |
|
```
long double tanhl( long double arg );
```
| (since C++11) |
|
```
double tanh ( IntegralType arg );
```
| (4) | (since C++11) |
1-3) Computes the hyperbolic tangent of `arg`
4) A set of overloads or a function template accepting an argument of any [integral type](../../types/is_integral "cpp/types/is integral"). Equivalent to 2) (the argument is cast to `double`). ### Parameters
| | | |
| --- | --- | --- |
| arg | - | value of a floating-point or [Integral type](../../types/is_integral "cpp/types/is integral") |
### Return value
If no errors occur, the hyperbolic tangent of `arg` (tanh(arg), or earg-e-arg/earg+e-arg) is returned. If a range error occurs due to underflow, the correct result (after rounding) is returned.
### Error handling
Errors are reported as specified in `[math\_errhandling](math_errhandling "cpp/numeric/math/math errhandling")`.
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* if the argument is ยฑ0, ยฑ0 is returned
* If the argument is ยฑโ, ยฑ1 is returned
* if the argument is NaN, NaN is returned
### Notes
[POSIX specifies](http://pubs.opengroup.org/onlinepubs/9699919799/functions/tanh.html) that in case of underflow, `arg` is returned unmodified, and if that is not supported, and implementation-defined value no greater than DBL\_MIN, FLT\_MIN, and LDBL\_MIN is returned.
### Examples
```
#include <iostream>
#include <cmath>
int main()
{
std::cout << std::showpos
<< "tanh(+1) = " << std::tanh(+1) << '\n'
<< "tanh(-1) = " << std::tanh(-1) << '\n'
<< "tanh(0.1)*sinh(0.2)-cosh(0.2) = "
<< std::tanh(0.1) * std::sinh(0.2) - std::cosh(0.2) << '\n'
// special values:
<< "tanh(+0) = " << std::tanh(+0.0) << '\n'
<< "tanh(-0) = " << std::tanh(-0.0) << '\n';
}
```
Output:
```
tanh(+1) = +0.761594
tanh(-1) = -0.761594
tanh(0.1)*sinh(0.2)-cosh(0.2) = -1
tanh(+0) = +0
tanh(-0) = -0
```
### See also
| | |
| --- | --- |
| [sinhsinhfsinhl](sinh "cpp/numeric/math/sinh")
(C++11)(C++11) | computes hyperbolic sine (\({\small\sinh{x} }\)sinh(x)) (function) |
| [coshcoshfcoshl](cosh "cpp/numeric/math/cosh")
(C++11)(C++11) | computes hyperbolic cosine (\({\small\cosh{x} }\)cosh(x)) (function) |
| [atanhatanhfatanhl](atanh "cpp/numeric/math/atanh")
(C++11)(C++11)(C++11) | computes the inverse hyperbolic tangent (\({\small\operatorname{artanh}{x} }\)artanh(x)) (function) |
| [tanh(std::complex)](../complex/tanh "cpp/numeric/complex/tanh") | computes hyperbolic tangent of a complex number (\({\small\tanh{z} }\)tanh(z)) (function template) |
| [tanh(std::valarray)](../valarray/tanh "cpp/numeric/valarray/tanh") | applies the function `std::tanh` to each element of valarray (function template) |
| [C documentation](https://en.cppreference.com/w/c/numeric/math/tanh "c/numeric/math/tanh") for `tanh` |
cpp std::cbrt, std::cbrtf, std::cbrtl std::cbrt, std::cbrtf, std::cbrtl
=================================
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
|
```
float cbrt ( float arg );
float cbrtf( float arg );
```
| (1) | (since C++11) |
|
```
double cbrt ( double arg );
```
| (2) | (since C++11) |
|
```
long double cbrt ( long double arg );
long double cbrtl( long double arg );
```
| (3) | (since C++11) |
|
```
double cbrt ( IntegralType arg );
```
| (4) | (since C++11) |
1-3) Computes the cube root of `arg`.
4) A set of overloads or a function template accepting an argument of any [integral type](../../types/is_integral "cpp/types/is integral"). Equivalent to 2) (the argument is cast to `double`). ### Parameters
| | | |
| --- | --- | --- |
| arg | - | value of a floating-point or [Integral type](../../types/is_integral "cpp/types/is integral") |
### Return value
If no errors occur, the cube root of `arg` (\(\small{\sqrt[3]{arg} }\)3โarg), is returned.
If a range error occurs due to underflow, the correct result (after rounding) is returned.
### Error handling
Errors are reported as specified in `[math\_errhandling](math_errhandling "cpp/numeric/math/math errhandling")`.
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* if the argument is ยฑ0 or ยฑโ, it is returned, unchanged
* if the argument is NaN, NaN is returned.
### Notes
`std::cbrt(arg)` is not equivalent to `[std::pow](http://en.cppreference.com/w/cpp/numeric/math/pow)(arg, 1.0/3)` because the rational number \(\small{\frac1{3} }\)1/3 is typically not equal to `1.0/3` and `[std::pow](pow "cpp/numeric/math/pow")` cannot raise a negative base to a fractional exponent. Moreover, `std::cbrt(arg)` usually gives more accurate results than `[std::pow](http://en.cppreference.com/w/cpp/numeric/math/pow)(arg, 1.0/3)` (see example). ### Example
```
#include <iostream>
#include <iomanip>
#include <cmath>
#include <limits>
int main()
{
std::cout
<< "Normal use:\n"
<< "cbrt(729) = " << std::cbrt(729) << '\n'
<< "cbrt(-0.125) = " << std::cbrt(-0.125) << '\n'
<< "Special values:\n"
<< "cbrt(-0) = " << std::cbrt(-0.0) << '\n'
<< "cbrt(+inf) = " << std::cbrt(INFINITY) << '\n'
<< "Accuracy and comparison with `pow`:\n"
<< std::setprecision(std::numeric_limits<double>::max_digits10)
<< "cbrt(343) = " << std::cbrt(343) << '\n'
<< "pow(343,1.0/3) = " << std::pow(343, 1.0/3) << '\n'
<< "cbrt(-343) = " << std::cbrt(-343) << '\n'
<< "pow(-343,1.0/3) = " << std::pow(-343, 1.0/3) << '\n';
}
```
Possible output:
```
Normal use:
cbrt(729) = 9
cbrt(-0.125) = -0.5
Special values:
cbrt(-0) = -0
cbrt(+inf) = inf
Accuracy and comparison with `pow`:
cbrt(343) = 7
pow(343,1.0/3) = 6.9999999999999991
cbrt(-343) = -7
pow(-343,1.0/3) = -nan
```
### See also
| | |
| --- | --- |
| [powpowfpowl](pow "cpp/numeric/math/pow")
(C++11)(C++11) | raises a number to the given power (\(\small{x^y}\)xy) (function) |
| [sqrtsqrtfsqrtl](sqrt "cpp/numeric/math/sqrt")
(C++11)(C++11) | computes square root (\(\small{\sqrt{x} }\)โx) (function) |
| [hypothypotfhypotl](hypot "cpp/numeric/math/hypot")
(C++11)(C++11)(C++11) | computes square root of the sum of the squares of two or three (C++17) given numbers (\(\scriptsize{\sqrt{x^2+y^2} }\)โx2+y2), (\(\scriptsize{\sqrt{x^2+y^2+z^2} }\)โx2+y2+z2) (function) |
| [C documentation](https://en.cppreference.com/w/c/numeric/math/cbrt "c/numeric/math/cbrt") for `cbrt` |
cpp std::isinf std::isinf
==========
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
|
```
bool isinf( float arg );
```
| (1) | (since C++11) (constexpr since C++23) |
|
```
bool isinf( double arg );
```
| (2) | (since C++11) (constexpr since C++23) |
|
```
bool isinf( long double arg );
```
| (3) | (since C++11) (constexpr since C++23) |
|
```
bool isinf( IntegralType arg );
```
| (4) | (since C++11) (constexpr since C++23) |
1-3) Determines if the given floating-point number `arg` is a positive or negative infinity.
4) A set of overloads or a function template accepting the `arg` argument of any [integral type](../../types/is_integral "cpp/types/is integral"). Equivalent to (2) (the argument is cast to `double`). ### Parameters
| | | |
| --- | --- | --- |
| arg | - | floating point value |
### Return value
`true` if `arg` is infinite, `false` otherwise.
### Example
```
#include <iostream>
#include <cmath>
#include <cfloat>
int main()
{
std::cout << std::boolalpha
<< "isinf(NaN) = " << std::isinf(NAN) << '\n'
<< "isinf(Inf) = " << std::isinf(INFINITY) << '\n'
<< "isinf(0.0) = " << std::isinf(0.0) << '\n'
<< "isinf(exp(800)) = " << std::isinf(std::exp(800)) << '\n'
<< "isinf(DBL_MIN/2.0) = " << std::isinf(DBL_MIN/2.0) << '\n';
}
```
Output:
```
isinf(NaN) = false
isinf(Inf) = true
isinf(0.0) = false
isinf(exp(800)) = true
isinf(DBL_MIN/2.0) = false
```
### See also
| | |
| --- | --- |
| [fpclassify](fpclassify "cpp/numeric/math/fpclassify")
(C++11) | categorizes the given floating-point value (function) |
| [isfinite](isfinite "cpp/numeric/math/isfinite")
(C++11) | checks if the given number has finite value (function) |
| [isnan](isnan "cpp/numeric/math/isnan")
(C++11) | checks if the given number is NaN (function) |
| [isnormal](isnormal "cpp/numeric/math/isnormal")
(C++11) | checks if the given number is normal (function) |
| [C documentation](https://en.cppreference.com/w/c/numeric/math/isinf "c/numeric/math/isinf") for `isinf` |
cpp std::isunordered std::isunordered
================
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
|
```
bool isunordered( float x, float y );
```
| (1) | (since C++11) (constexpr since C++23) |
|
```
bool isunordered( double x, double y );
```
| (2) | (since C++11) (constexpr since C++23) |
|
```
bool isunordered( long double x, long double y );
```
| (3) | (since C++11) (constexpr since C++23) |
|
```
bool isunordered( Arithmetic x, Arithmetic y );
```
| (4) | (since C++11) (constexpr since C++23) |
1-3) Determines if the floating point numbers `x` and `y` are unordered, that is, one or both are NaN and thus cannot be meaningfully compared with each other.
4) A set of overloads or a function template for all combinations of arguments of arithmetic type not covered by (1-3). If any argument has [integral type](../../types/is_integral "cpp/types/is integral"), it is cast to `double`. ### Parameters
| | | |
| --- | --- | --- |
| x | - | floating point value |
| y | - | floating point value |
### Return value
`true` if either `x` or `y` is NaN, `false` otherwise.
### See also
| | |
| --- | --- |
| [fpclassify](fpclassify "cpp/numeric/math/fpclassify")
(C++11) | categorizes the given floating-point value (function) |
| [isnan](isnan "cpp/numeric/math/isnan")
(C++11) | checks if the given number is NaN (function) |
| [C documentation](https://en.cppreference.com/w/c/numeric/math/isunordered "c/numeric/math/isunordered") for `isunordered` |
cpp std::pow, std::powf, std::powl std::pow, std::powf, std::powl
==============================
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
| | (1) | |
|
```
float pow ( float base, float exp );
```
| |
|
```
float powf( float base, float exp );
```
| (since C++11) |
|
```
double pow ( double base, double exp );
```
| (2) | |
| | (3) | |
|
```
long double pow ( long double base, long double exp );
```
| |
|
```
long double powl( long double base, long double exp );
```
| (since C++11) |
|
```
float pow ( float base, int iexp );
```
| (4) | (until C++11) |
|
```
double pow ( double base, int iexp );
```
| (5) | (until C++11) |
|
```
long double pow ( long double base, int iexp );
```
| (6) | (until C++11) |
|
```
Promoted pow ( Arithmetic1 base, Arithmetic2 exp );
```
| (7) | (since C++11) |
1-6) Computes the value of `base` raised to the power `exp` or `iexp`.
7) A set of overloads or a function template for all combinations of arguments of arithmetic type not covered by 1-3). If any argument has [integral type](../../types/is_integral "cpp/types/is integral"), it is cast to `double`. If any argument is `long double`, then the return type `Promoted` is also `long double`, otherwise the return type is always `double`. ### Parameters
| | | |
| --- | --- | --- |
| base | - | base as a value of floating-point or [integral type](../../types/is_integral "cpp/types/is integral") |
| exp | - | exponent as a value of floating-point or [integral type](../../types/is_integral "cpp/types/is integral") |
| iexp | - | exponent as integer value |
### Return value
If no errors occur, `base` raised to the power of `exp` (or `iexp`) (baseexp
), is returned.
If a domain error occurs, an implementation-defined value is returned (NaN where supported).
If a pole error or a range error due to overflow occurs, `[ยฑHUGE\_VAL](huge_val "cpp/numeric/math/HUGE VAL")`, `ยฑHUGE_VALF`, or `ยฑHUGE_VALL` is returned.
If a range error occurs due to underflow, the correct result (after rounding) is returned.
### Error handling
Errors are reported as specified in `[math\_errhandling](math_errhandling "cpp/numeric/math/math errhandling")`.
If `base` is finite and negative and `exp` is finite and non-integer, a domain error occurs and a range error may occur.
If `base` is zero and `exp` is zero, a domain error may occur.
If `base` is zero and `exp` is negative, a domain error or a pole error may occur.
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* `pow(+0, exp)`, where `exp` is a negative odd integer, returns +โ and raises `[FE\_DIVBYZERO](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")`
* `pow(-0, exp)`, where `exp` is a negative odd integer, returns -โ and raises `[FE\_DIVBYZERO](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")`
* `pow(ยฑ0, exp)`, where `exp` is negative, finite, and is an even integer or a non-integer, returns +โ and raises `[FE\_DIVBYZERO](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")`
* `pow(ยฑ0, -โ)` returns +โ and may raise `[FE\_DIVBYZERO](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")`
* `pow(+0, exp)`, where `exp` is a positive odd integer, returns +0
* `pow(-0, exp)`, where `exp` is a positive odd integer, returns -0
* `pow(ยฑ0, exp)`, where `exp` is positive non-integer or a positive even integer, returns +0
* `pow(-1, ยฑโ)` returns `1`
* `pow(+1, exp)` returns `1` for any `exp`, even when `exp` is `NaN`
* `pow(base, ยฑ0)` returns `1` for any `base`, even when `base` is `NaN`
* `pow(base, exp)` returns `NaN` and raises `[FE\_INVALID](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` if `base` is finite and negative and `exp` is finite and non-integer.
* `pow(base, -โ)` returns +โ for any `|base|<1`
* `pow(base, -โ)` returns +0 for any `|base|>1`
* `pow(base, +โ)` returns +0 for any `|base|<1`
* `pow(base, +โ)` returns +โ for any `|base|>1`
* `pow(-โ, exp)` returns -0 if `exp` is a negative odd integer
* `pow(-โ, exp)` returns +0 if `exp` is a negative non-integer or negative even integer
* `pow(-โ, exp)` returns -โ if `exp` is a positive odd integer
* `pow(-โ, exp)` returns +โ if `exp` is a positive non-integer or positive even integer
* `pow(+โ, exp)` returns +0 for any negative `exp`
* `pow(+โ, exp)` returns +โ for any positive `exp`
* except where specified above, if any argument is NaN, NaN is returned
### Notes
`pow(float, int)` returns `float` until C++11 (per overload 4) but returns `double` since C++11 (per overload 7).
Although `std::pow` cannot be used to obtain a root of a negative number, `[std::cbrt](cbrt "cpp/numeric/math/cbrt")` is provided for the common case where `exp` is 1/3.
### Example
```
#include <iostream>
#include <cmath>
#include <cerrno>
#include <cfenv>
#include <cstring>
#pragma STDC FENV_ACCESS ON
int main()
{
// typical usage
std::cout << "pow(2, 10) = " << std::pow(2,10) << '\n'
<< "pow(2, 0.5) = " << std::pow(2,0.5) << '\n'
<< "pow(-2, -3) = " << std::pow(-2,-3) << '\n';
// special values
std::cout << "pow(-1, NAN) = " << std::pow(-1,NAN) << '\n'
<< "pow(+1, NAN) = " << std::pow(+1,NAN) << '\n'
<< "pow(INFINITY, 2) = " << std::pow(INFINITY, 2) << '\n'
<< "pow(INFINITY, -1) = " << std::pow(INFINITY, -1) << '\n';
// error handling
errno = 0;
std::feclearexcept(FE_ALL_EXCEPT);
std::cout << "pow(-1, 1/3) = " << std::pow(-1, 1.0/3) << '\n';
if (errno == EDOM)
std::cout << " errno == EDOM " << std::strerror(errno) << '\n';
if (std::fetestexcept(FE_INVALID))
std::cout << " FE_INVALID raised\n";
std::feclearexcept(FE_ALL_EXCEPT);
std::cout << "pow(-0, -3) = " << std::pow(-0.0, -3) << '\n';
if (std::fetestexcept(FE_DIVBYZERO))
std::cout << " FE_DIVBYZERO raised\n";
}
```
Possible output:
```
pow(2, 10) = 1024
pow(2, 0.5) = 1.41421
pow(-2, -3) = -0.125
pow(-1, NAN) = nan
pow(+1, NAN) = 1
pow(INFINITY, 2) = inf
pow(INFINITY, -1) = 0
pow(-1, 1/3) = -nan
errno == EDOM Numerical argument out of domain
FE_INVALID raised
pow(-0, -3) = -inf
FE_DIVBYZERO raised
```
### See also
| | |
| --- | --- |
| [sqrtsqrtfsqrtl](sqrt "cpp/numeric/math/sqrt")
(C++11)(C++11) | computes square root (\(\small{\sqrt{x} }\)โx) (function) |
| [cbrtcbrtfcbrtl](cbrt "cpp/numeric/math/cbrt")
(C++11)(C++11)(C++11) | computes cubic root (\(\small{\sqrt[3]{x} }\)3โx) (function) |
| [hypothypotfhypotl](hypot "cpp/numeric/math/hypot")
(C++11)(C++11)(C++11) | computes square root of the sum of the squares of two or three (C++17) given numbers (\(\scriptsize{\sqrt{x^2+y^2} }\)โx2+y2), (\(\scriptsize{\sqrt{x^2+y^2+z^2} }\)โx2+y2+z2) (function) |
| [pow(std::complex)](../complex/pow "cpp/numeric/complex/pow") | complex power, one or both arguments may be a complex number (function template) |
| [pow(std::valarray)](../valarray/pow "cpp/numeric/valarray/pow") | applies the function `std::pow` to two valarrays or a valarray and a value (function template) |
| [C documentation](https://en.cppreference.com/w/c/numeric/math/pow "c/numeric/math/pow") for `pow` |
| programming_docs |
cpp std::exp, std::expf, std::expl std::exp, std::expf, std::expl
==============================
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
| | (1) | |
|
```
float exp ( float arg );
```
| |
|
```
float expf( float arg );
```
| (since C++11) |
|
```
double exp ( double arg );
```
| (2) | |
| | (3) | |
|
```
long double exp ( long double arg );
```
| |
|
```
long double expl( long double arg );
```
| (since C++11) |
|
```
double exp ( IntegralType arg );
```
| (4) | (since C++11) |
1-3) Computes *e* (Euler's number, `2.7182818...`) raised to the given power `arg`
4) A set of overloads or a function template accepting an argument of any [integral type](../../types/is_integral "cpp/types/is integral"). Equivalent to (2) (the argument is cast to `double`). ### Parameters
| | | |
| --- | --- | --- |
| arg | - | value of floating-point or [Integral type](../../types/is_integral "cpp/types/is integral") |
### Return value
If no errors occur, the base-*e* exponential of `arg` (earg
) is returned.
If a range error due to overflow occurs, `[+HUGE\_VAL](huge_val "cpp/numeric/math/HUGE VAL")`, `+HUGE_VALF`, or `+HUGE_VALL` is returned.
If a range error occurs due to underflow, the correct result (after rounding) is returned.
### Error handling
Errors are reported as specified in `[math\_errhandling](math_errhandling "cpp/numeric/math/math errhandling")`.
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* If the argument is ยฑ0, 1 is returned
* If the argument is -โ, +0 is returned
* If the argument is +โ, +โ is returned
* If the argument is NaN, NaN is returned
### Notes
For IEEE-compatible type `double`, overflow is guaranteed if 709.8 < arg, and underflow is guaranteed if arg < -708.4.
### Example
```
#include <iostream>
#include <iomanip>
#include <cmath>
#include <cerrno>
#include <cstring>
#include <cfenv>
// #pragma STDC FENV_ACCESS ON
int main()
{
std::cout << "exp(1) = eยน = " << std::setprecision(16) << std::exp(1) << '\n'
<< "FV of $100, continuously compounded at 3% for 1 year = "
<< std::setprecision(6) << 100*std::exp(0.03) << '\n';
// special values
std::cout << "exp(-0) = " << std::exp(-0.0) << '\n'
<< "exp(-Inf) = " << std::exp(-INFINITY) << '\n';
// error handling
errno = 0;
std::feclearexcept(FE_ALL_EXCEPT);
std::cout << "exp(710) = " << std::exp(710) << '\n';
if (errno == ERANGE)
std::cout << " errno == ERANGE: " << std::strerror(errno) << '\n';
if (std::fetestexcept(FE_OVERFLOW))
std::cout << " FE_OVERFLOW raised\n";
}
```
Possible output:
```
exp(1) = eยน = 2.718281828459045
FV of $100, continuously compounded at 3% for 1 year = 103.045
exp(-0) = 1
exp(-Inf) = 0
exp(710) = inf
errno == ERANGE: Numerical result out of range
FE_OVERFLOW raised
```
### See also
| | |
| --- | --- |
| [exp2exp2fexp2l](exp2 "cpp/numeric/math/exp2")
(C++11)(C++11)(C++11) | returns *2* raised to the given power (\({\small 2^x}\)2x) (function) |
| [expm1expm1fexpm1l](expm1 "cpp/numeric/math/expm1")
(C++11)(C++11)(C++11) | returns *e* raised to the given power, minus one (\({\small e^x-1}\)ex-1) (function) |
| [loglogflogl](log "cpp/numeric/math/log")
(C++11)(C++11) | computes natural (base *e*) logarithm (\({\small \ln{x} }\)ln(x)) (function) |
| [exp(std::complex)](../complex/exp "cpp/numeric/complex/exp") | complex base *e* exponential (function template) |
| [exp(std::valarray)](../valarray/exp "cpp/numeric/valarray/exp") | applies the function `std::exp` to each element of valarray (function template) |
| [C documentation](https://en.cppreference.com/w/c/numeric/math/exp "c/numeric/math/exp") for `exp` |
cpp std::exp2, std::exp2f, std::exp2l std::exp2, std::exp2f, std::exp2l
=================================
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
|
```
float exp2 ( float n );
float exp2f( float n );
```
| (1) | (since C++11) |
|
```
double exp2 ( double n );
```
| (2) | (since C++11) |
|
```
long double exp2 ( long double n );
long double exp2l( long double n );
```
| (3) | (since C++11) |
|
```
double exp2 ( IntegralType n );
```
| (4) | (since C++11) |
1-3) Computes 2 raised to the given power `n`
4) A set of overloads or a function template accepting an argument of any [integral type](../../types/is_integral "cpp/types/is integral"). Equivalent to (2) (the argument is cast to `double`). ### Parameters
| | | |
| --- | --- | --- |
| n | - | value of floating-point or [Integral type](../../types/is_integral "cpp/types/is integral") |
### Return value
If no errors occur, the base-*2* exponential of `n` (2n
) is returned.
If a range error due to overflow occurs, `[+HUGE\_VAL](huge_val "cpp/numeric/math/HUGE VAL")`, `+HUGE_VALF`, or `+HUGE_VALL` is returned.
If a range error occurs due to underflow, the correct result (after rounding) is returned.
### Error handling
Errors are reported as specified in `[math\_errhandling](math_errhandling "cpp/numeric/math/math errhandling")`.
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* If the argument is ยฑ0, 1 is returned
* If the argument is -โ, +0 is returned
* If the argument is +โ, +โ is returned
* If the argument is NaN, NaN is returned
### Example
```
#include <iostream>
#include <cmath>
#include <cerrno>
#include <cstring>
#include <cfenv>
// #pragma STDC FENV_ACCESS ON
int main()
{
std::cout << "exp2(4) = " << std::exp2(4) << '\n'
<< "exp2(0.5) = " << std::exp2(0.5) << '\n'
<< "exp2(-4) = " << std::exp2(-4) << '\n';
// special values
std::cout << "exp2(-0) = " << std::exp2(-0.0) << '\n'
<< "exp2(-Inf) = " << std::exp2(-INFINITY) << '\n';
// error handling
errno = 0;
std::feclearexcept(FE_ALL_EXCEPT);
std::cout << "exp2(1024) = " << std::exp2(1024) << '\n';
if (errno == ERANGE)
std::cout << " errno == ERANGE: " << std::strerror(errno) << '\n';
if (std::fetestexcept(FE_OVERFLOW))
std::cout << " FE_OVERFLOW raised\n";
}
```
Possible output:
```
exp2(4) = 16
exp2(0.5) = 1.41421
exp2(-4) = 0.0625
exp2(-0) = 1
exp2(-Inf) = 0
exp2(1024) = inf
errno == ERANGE: Numerical result out of range
FE_OVERFLOW raised
```
### See also
| | |
| --- | --- |
| [expexpfexpl](exp "cpp/numeric/math/exp")
(C++11)(C++11) | returns *e* raised to the given power (\({\small e^x}\)ex) (function) |
| [expm1expm1fexpm1l](expm1 "cpp/numeric/math/expm1")
(C++11)(C++11)(C++11) | returns *e* raised to the given power, minus one (\({\small e^x-1}\)ex-1) (function) |
| [log2log2flog2l](log2 "cpp/numeric/math/log2")
(C++11)(C++11)(C++11) | base 2 logarithm of the given number (\({\small \log\_{2}{x} }\)log2(x)) (function) |
| [C documentation](https://en.cppreference.com/w/c/numeric/math/exp2 "c/numeric/math/exp2") for `exp2` |
cpp std::log1p, std::log1pf, std::log1pl std::log1p, std::log1pf, std::log1pl
====================================
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
|
```
float log1p ( float arg );
float log1pf( float arg );
```
| (1) | (since C++11) |
|
```
double log1p ( double arg );
```
| (2) | (since C++11) |
|
```
long double log1p ( long double arg );
long double log1pl( long double arg );
```
| (3) | (since C++11) |
|
```
double log1p ( IntegralType arg );
```
| (4) | (since C++11) |
1-3) Computes the natural (base `e`) logarithm of `1+arg`. This function is more precise than the expression `[std::log](http://en.cppreference.com/w/cpp/numeric/math/log)(1+arg)` if `arg` is close to zero.
4) A set of overloads or a function template accepting an argument of any [integral type](../../types/is_integral "cpp/types/is integral"). Equivalent to (2) (the argument is cast to `double`). ### Parameters
| | | |
| --- | --- | --- |
| arg | - | value of floating-point or [Integral type](../../types/is_integral "cpp/types/is integral") |
### Return value
If no errors occur ln(1+arg) is returned.
If a domain error occurs, an implementation-defined value is returned (NaN where supported).
If a pole error occurs, `[-HUGE\_VAL](huge_val "cpp/numeric/math/HUGE VAL")`, `-HUGE_VALF`, or `-HUGE_VALL` is returned.
If a range error occurs due to underflow, the correct result (after rounding) is returned.
### Error handling
Errors are reported as specified in `[math\_errhandling](math_errhandling "cpp/numeric/math/math errhandling")`.
Domain error occurs if `arg` is less than -1.
Pole error may occur if `arg` is -1.
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* If the argument is ยฑ0, it is returned unmodified
* If the argument is -1, -โ is returned and `[FE\_DIVBYZERO](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` is raised.
* If the argument is less than -1, NaN is returned and `[FE\_INVALID](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` is raised.
* If the argument is +โ, +โ is returned
* If the argument is NaN, NaN is returned
### Notes
The functions `[std::expm1](expm1 "cpp/numeric/math/expm1")` and `std::log1p` are useful for financial calculations, for example, when calculating small daily interest rates: (1+x)n
-1 can be expressed as `[std::expm1](http://en.cppreference.com/w/cpp/numeric/math/expm1)(n \* std::log1p(x))`. These functions also simplify writing accurate inverse hyperbolic functions.
### Example
```
#include <iostream>
#include <cfenv>
#include <cmath>
#include <cerrno>
#include <cstring>
// #pragma STDC FENV_ACCESS ON
int main()
{
std::cout << "log1p(0) = " << log1p(0) << '\n'
<< "Interest earned in 2 days on on $100, compounded daily at 1%\n"
<< " on a 30/360 calendar = "
<< 100*expm1(2*log1p(0.01/360)) << '\n'
<< "log(1+1e-16) = " << std::log(1+1e-16)
<< " log1p(1e-16) = " << std::log1p(1e-16) << '\n';
// special values
std::cout << "log1p(-0) = " << std::log1p(-0.0) << '\n'
<< "log1p(+Inf) = " << std::log1p(INFINITY) << '\n';
// error handling
errno = 0;
std::feclearexcept(FE_ALL_EXCEPT);
std::cout << "log1p(-1) = " << std::log1p(-1) << '\n';
if (errno == ERANGE)
std::cout << " errno == ERANGE: " << std::strerror(errno) << '\n';
if (std::fetestexcept(FE_DIVBYZERO))
std::cout << " FE_DIVBYZERO raised\n";
}
```
Possible output:
```
log1p(0) = 0
Interest earned in 2 days on on $100, compounded daily at 1%
on a 30/360 calendar = 0.00555563
log(1+1e-16) = 0 log1p(1e-16) = 1e-16
log1p(-0) = -0
log1p(+Inf) = inf
log1p(-1) = -inf
errno == ERANGE: Result too large
FE_DIVBYZERO raised
```
### See also
| | |
| --- | --- |
| [loglogflogl](log "cpp/numeric/math/log")
(C++11)(C++11) | computes natural (base *e*) logarithm (\({\small \ln{x} }\)ln(x)) (function) |
| [log10log10flog10l](log10 "cpp/numeric/math/log10")
(C++11)(C++11) | computes common (base *10*) logarithm (\({\small \log\_{10}{x} }\)log10(x)) (function) |
| [log2log2flog2l](log2 "cpp/numeric/math/log2")
(C++11)(C++11)(C++11) | base 2 logarithm of the given number (\({\small \log\_{2}{x} }\)log2(x)) (function) |
| [expm1expm1fexpm1l](expm1 "cpp/numeric/math/expm1")
(C++11)(C++11)(C++11) | returns *e* raised to the given power, minus one (\({\small e^x-1}\)ex-1) (function) |
| [C documentation](https://en.cppreference.com/w/c/numeric/math/log1p "c/numeric/math/log1p") for `log1p` |
cpp std::div, std::ldiv, std::lldiv std::div, std::ldiv, std::lldiv
===============================
| Defined in header `[<cstdlib>](../../header/cstdlib "cpp/header/cstdlib")` | | |
| --- | --- | --- |
|
```
std::div_t div( int x, int y );
```
| (1) | (constexpr since C++23) |
|
```
std::ldiv_t div( long x, long y );
```
| (2) | (constexpr since C++23) |
|
```
std::lldiv_t div( long long x, long long y );
```
| (3) | (since C++11) (constexpr since C++23) |
|
```
std::ldiv_t ldiv( long x, long y );
```
| (4) | (constexpr since C++23) |
|
```
std::lldiv_t lldiv( long long x, long long y );
```
| (5) | (since C++11) (constexpr since C++23) |
| Defined in header `[<cinttypes>](../../header/cinttypes "cpp/header/cinttypes")` | | |
|
```
std::imaxdiv_t div( std::intmax_t x, std::intmax_t y );
```
| (6) | (since C++11) |
|
```
std::imaxdiv_t imaxdiv( std::intmax_t x, std::intmax_t y );
```
| (7) | (since C++11) |
Computes both the quotient and the remainder of the division of the numerator `x` by the denominator `y`.
| | |
| --- | --- |
| Overload of `std::div` for `[std::intmax\_t](../../types/integer "cpp/types/integer")` is provided in [`<cinttypes>`](../../header/cinttypes "cpp/header/cinttypes") if and only if `[std::intmax\_t](../../types/integer "cpp/types/integer")` is an extended integer type. | (since C++11) |
| | |
| --- | --- |
| The quotient is the algebraic quotient with any fractional part discarded (truncated towards zero). The remainder is such that `quot * y + rem == x`. | (until C++11) |
| The quotient is the result of the expression `x/y`. The remainder is the result of the expression `x%y`. | (since C++11) |
### Parameters
| | | |
| --- | --- | --- |
| x, y | - | integer values |
### Return value
If both the remainder and the quotient can be represented as objects of the corresponding type (`int`, `long`, `long long`, `std::imaxdiv_t`, respectively), returns both as an object of type `std::div_t`, `std::ldiv_t`, `std::lldiv_t`, `std::imaxdiv_t` defined as follows:
std::div\_t
------------
```
struct div_t { int quot; int rem; };
```
or.
```
struct div_t { int rem; int quot; };
```
std::ldiv\_t
-------------
```
struct ldiv_t { long quot; long rem; };
```
or.
```
struct ldiv_t { long rem; long quot; };
```
std::lldiv\_t
--------------
```
struct lldiv_t { long long quot; long long rem; };
```
or.
```
struct lldiv_t { long long rem; long long quot; };
```
std::imaxdiv\_t
----------------
```
struct imaxdiv_t { std::intmax_t quot; std::intmax_t rem; };
```
or.
```
struct imaxdiv_t { std::intmax_t rem; std::intmax_t quot; };
```
If either the remainder or the quotient cannot be represented, the behavior is undefined.
### Notes
Until C++11, the rounding direction of the quotient and the sign of the remainder in the [built-in division and remainder operators](../../language/operator_arithmetic "cpp/language/operator arithmetic") was implementation-defined if either of the operands was negative, but it was well-defined in `std::div`.
On many platforms, a single CPU instruction obtains both the quotient and the remainder, and this function may leverage that, although compilers are generally able to merge nearby `/` and `%` where suitable.
### Example
```
#include <string>
#include <cmath>
#include <cstdlib>
#include <iostream>
#include <sstream>
#include <cassert>
std::string euclidean_division_string(int dividend, int divisor)
{
auto dv = std::div(dividend, divisor);
assert(dividend == divisor * dv.quot + dv.rem);
assert(dv.quot == dividend / divisor);
assert(dv.rem == dividend % divisor);
return (std::ostringstream() << std::showpos << dividend << " = "
<< divisor << " * (" << dv.quot << ") "
<< std::showpos << dv.rem).str();
}
std::string itoa(int n, int radix /*[2..16]*/)
{
std::string buf;
std::div_t dv{}; dv.quot = n;
do {
dv = std::div(dv.quot, radix);
buf += "0123456789abcdef"[std::abs(dv.rem)]; // string literals are arrays
} while(dv.quot);
if (n < 0)
buf += '-';
return {buf.rbegin(), buf.rend()};
}
int main()
{
std::cout << euclidean_division_string(369, 10) << '\n'
<< euclidean_division_string(369, -10) << '\n'
<< euclidean_division_string(-369, 10) << '\n'
<< euclidean_division_string(-369, -10) << "\n\n";
std::cout << itoa(12345, 10) << '\n'
<< itoa(-12345, 10) << '\n'
<< itoa(42, 2) << '\n'
<< itoa(65535, 16) << '\n';
}
```
Output:
```
+369 = +10 * (+36) +9
+369 = -10 * (-36) +9
-369 = +10 * (-36) -9
-369 = -10 * (+36) -9
12345
-12345
101010
ffff
```
### See also
| | |
| --- | --- |
| [fmodfmodffmodl](fmod "cpp/numeric/math/fmod")
(C++11)(C++11) | remainder of the floating point division operation (function) |
| [remainderremainderfremainderl](remainder "cpp/numeric/math/remainder")
(C++11)(C++11)(C++11) | signed remainder of the division operation (function) |
| [remquoremquofremquol](remquo "cpp/numeric/math/remquo")
(C++11)(C++11)(C++11) | signed remainder as well as the three last bits of the division operation (function) |
| [C documentation](https://en.cppreference.com/w/c/numeric/math/div "c/numeric/math/div") for `div` |
### External links
* [Euclidean division](https://en.wikipedia.org/wiki/Euclidean_division "enwiki:Euclidean division")
cpp std::ilogb, std::ilogbf, std::ilogbl std::ilogb, std::ilogbf, std::ilogbl
====================================
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
|
```
int ilogb ( float arg );
int ilogbf( float arg );
```
| (1) | (since C++11) (constexpr since C++23) |
|
```
int ilogb ( double arg );
```
| (2) | (since C++11) (constexpr since C++23) |
|
```
int ilogb ( long double arg );
int ilogbl( long double arg );
```
| (3) | (since C++11) (constexpr since C++23) |
|
```
int ilogb ( IntegralType arg );
```
| (4) | (since C++11) (constexpr since C++23) |
|
```
#define FP_ILOGB0 /*implementation-defined*/
```
| (5) | (since C++11) |
|
```
#define FP_ILOGBNAN /*implementation-defined*/
```
| (6) | (since C++11) |
1-3) Extracts the value of the unbiased exponent from the floating-point argument `arg`, and returns it as a signed integer value.
4) A set of overloads or a function template accepting an argument of any [integral type](../../types/is_integral "cpp/types/is integral"). Equivalent to (2) (the argument is cast to `double`).
5) Expands to integer constant expression whose value is either `[INT\_MIN](../../types/climits "cpp/types/climits")` or `-[INT\_MAX](http://en.cppreference.com/w/cpp/types/climits)`.
6) Expands to integer constant expression whose value is either `[INT\_MIN](../../types/climits "cpp/types/climits")` or `+[INT\_MAX](http://en.cppreference.com/w/cpp/types/climits)`. Formally, the unbiased exponent is the integral part of log
r|arg| as a signed integral value, for non-zero `arg`, where `r` is `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<T>::radix` and `T` is the floating-point type of `arg`.
### Parameters
| | | |
| --- | --- | --- |
| arg | - | floating point value |
### Return value
If no errors occur, the unbiased exponent of `arg` is returned as a signed int value.
If `arg` is zero, `FP_ILOGB0` is returned.
If `arg` is infinite, `[INT\_MAX](../../types/climits "cpp/types/climits")` is returned.
If `arg` is a NaN, `FP_ILOGBNAN` is returned.
If the correct result is greater than `[INT\_MAX](../../types/climits "cpp/types/climits")` or smaller than `[INT\_MIN](../../types/climits "cpp/types/climits")`, the return value is unspecified.
### Error handling
Errors are reported as specified in `[math\_errhandling](math_errhandling "cpp/numeric/math/math errhandling")`.
A domain error or range error may occur if `arg` is zero, infinite, or NaN.
If the correct result is greater than `[INT\_MAX](../../types/climits "cpp/types/climits")` or smaller than `[INT\_MIN](../../types/climits "cpp/types/climits")`, a domain error or a range error may occur.
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* If the correct result is greater than `[INT\_MAX](../../types/climits "cpp/types/climits")` or smaller than `[INT\_MIN](../../types/climits "cpp/types/climits")`, `[FE\_INVALID](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` is raised.
* If `arg` is ยฑ0, ยฑโ, or NaN, `[FE\_INVALID](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` is raised.
* In all other cases, the result is exact (`[FE\_INEXACT](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` is never raised) and [the current rounding mode](../fenv/fe_round "cpp/numeric/fenv/FE round") is ignored
### Notes
If `arg` is not zero, infinite, or NaN, the value returned is exactly equivalent to `static\_cast<int>([std::logb](http://en.cppreference.com/w/cpp/numeric/math/logb)(arg))`.
[POSIX requires](http://pubs.opengroup.org/onlinepubs/9699919799/functions/ilogb.html) that a domain error occurs if `arg` is zero, infinite, NaN, or if the correct result is outside of the range of `int`.
POSIX also requires that, on XSI-conformant systems, the value returned when the correct result is greater than `[INT\_MAX](../../types/climits "cpp/types/climits")` is `[INT\_MAX](../../types/climits "cpp/types/climits")` and the value returned when the correct result is less than `[INT\_MIN](../../types/climits "cpp/types/climits")` is `[INT\_MIN](../../types/climits "cpp/types/climits")`.
The correct result can be represented as `int` on all known implementations. For overflow to occur, `[INT\_MAX](../../types/climits "cpp/types/climits")` must be less than `[LDBL\_MAX\_EXP](http://en.cppreference.com/w/cpp/types/climits)\*log2([FLT\_RADIX](http://en.cppreference.com/w/cpp/types/climits))` or `[INT\_MIN](../../types/climits "cpp/types/climits")` must be greater than `LDBL_MIN_EXP-[LDBL\_MANT\_DIG](http://en.cppreference.com/w/cpp/types/climits))\*log2([FLT\_RADIX](http://en.cppreference.com/w/cpp/types/climits))`.
The value of the exponent returned by `std::ilogb` is always 1 less than the exponent retuned by `[std::frexp](frexp "cpp/numeric/math/frexp")` because of the different normalization requirements: for the exponent `e` returned by `std::ilogb`, |arg\*r-e
| is between 1 and `r` (typically between `1` and `2`), but for the exponent `e` returned by `[std::frexp](frexp "cpp/numeric/math/frexp")`, |arg\*2-e
| is between `0.5` and `1`.
### Example
Compares different floating-point decomposition functions.
```
#include <iostream>
#include <cmath>
#include <limits>
#include <cfenv>
// #pragma STDC FENV_ACCESS ON
int main()
{
double f = 123.45;
std::cout << "Given the number " << f << " or " << std::hexfloat
<< f << std::defaultfloat << " in hex,\n";
double f3;
double f2 = std::modf(f, &f3);
std::cout << "modf() makes " << f3 << " + " << f2 << '\n';
int i;
f2 = std::frexp(f, &i);
std::cout << "frexp() makes " << f2 << " * 2^" << i << '\n';
i = std::ilogb(f);
std::cout << "logb()/ilogb() make " << f/std::scalbn(1.0, i) << " * "
<< std::numeric_limits<double>::radix
<< "^" << std::ilogb(f) << '\n';
// error handling
std::feclearexcept(FE_ALL_EXCEPT);
std::cout << "ilogb(0) = " << std::ilogb(0) << '\n';
if (std::fetestexcept(FE_INVALID))
std::cout << " FE_INVALID raised\n";
}
```
Possible output:
```
Given the number 123.45 or 0x1.edccccccccccdp+6 in hex,
modf() makes 123 + 0.45
frexp() makes 0.964453 * 2^7
logb()/ilogb() make 1.92891 * 2^6
ilogb(0) = -2147483648
FE_INVALID raised
```
### See also
| | |
| --- | --- |
| [frexpfrexpffrexpl](frexp "cpp/numeric/math/frexp")
(C++11)(C++11) | decomposes a number into significand and a power of `2` (function) |
| [logblogbflogbl](logb "cpp/numeric/math/logb")
(C++11)(C++11)(C++11) | extracts exponent of the number (function) |
| [scalbnscalbnfscalbnlscalblnscalblnfscalblnl](scalbn "cpp/numeric/math/scalbn")
(C++11)(C++11)(C++11)(C++11)(C++11)(C++11) | multiplies a number by `[FLT\_RADIX](../../types/climits "cpp/types/climits")` raised to a power (function) |
| [C documentation](https://en.cppreference.com/w/c/numeric/math/ilogb "c/numeric/math/ilogb") for `ilogb` |
| programming_docs |
cpp std::tgamma, std::tgammaf, std::tgammal std::tgamma, std::tgammaf, std::tgammal
=======================================
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
|
```
float tgamma ( float arg );
float tgammaf( float arg );
```
| (1) | (since C++11) |
|
```
double tgamma ( double arg );
```
| (2) | (since C++11) |
|
```
long double tgamma ( long double arg );
long double tgammal( long double arg );
```
| (3) | (since C++11) |
|
```
double tgamma ( IntegralType arg );
```
| (4) | (since C++11) |
1-3) Computes the [gamma function](https://en.wikipedia.org/wiki/Gamma_function "enwiki:Gamma function") of `arg`.
4) A set of overloads or a function template accepting an argument of any [integral type](../../types/is_integral "cpp/types/is integral"). Equivalent to 2) (the argument is cast to `double`). ### Parameters
| | | |
| --- | --- | --- |
| arg | - | value of a floating-point or [Integral type](../../types/is_integral "cpp/types/is integral") |
### Return value
If no errors occur, the value of the gamma function of `arg`, that is \(\Gamma(\mathtt{arg}) = \displaystyle\int\_0^\infty\!\! t^{\mathtt{arg}-1} e^{-t}\, dt\)โซโ
0*t*arg-1
*e*-t d*t*, is returned.
If a domain error occurs, an implementation-defined value (NaN where supported) is returned.
If a pole error occurs, `[ยฑHUGE\_VAL](huge_val "cpp/numeric/math/HUGE VAL")`, `ยฑHUGE_VALF`, or `ยฑHUGE_VALL` is returned.
If a range error due to overflow occurs, `[ยฑHUGE\_VAL](huge_val "cpp/numeric/math/HUGE VAL")`, `ยฑHUGE_VALF`, or `ยฑHUGE_VALL` is returned.
If a range error due to underflow occurs, the correct value (after rounding) is returned.
### Error handling
Errors are reported as specified in `[math\_errhandling](math_errhandling "cpp/numeric/math/math errhandling")`.
If `arg` is zero or is an integer less than zero, a pole error or a domain error may occur.
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* If the argument is ยฑ0, ยฑโ is returned and `[FE\_DIVBYZERO](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` is raised
* If the argument is a negative integer, NaN is returned and `[FE\_INVALID](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` is raised
* If the argument is -โ, NaN is returned and `[FE\_INVALID](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` is raised
* If the argument is +โ, +โ is returned.
* If the argument is NaN, NaN is returned
### Notes
If `arg` is a natural number, `std::tgamma(arg)` is the factorial of `arg-1`. Many implementations calculate the exact integer-domain factorial if the argument is a sufficiently small integer.
For IEEE-compatible type `double`, overflow happens if `0 < x < 1/DBL_MAX` or if `x > 171.7`.
[POSIX requires](http://pubs.opengroup.org/onlinepubs/9699919799/functions/tgamma.html) that a pole error occurs if the argument is zero, but a domain error occurs when the argument is a negative integer. It also specifies that in future, domain errors may be replaced by pole errors for negative integer arguments (in which case the return value in those cases would change from NaN to ยฑโ).
There is a non-standard function named `gamma` in various implementations, but its definition is inconsistent. For example, glibc and 4.2BSD version of `gamma` executes `lgamma`, but 4.4BSD version of `gamma` executes `tgamma`.
### Example
```
#include <iostream>
#include <cmath>
#include <cerrno>
#include <cstring>
#include <cfenv>
#pragma STDC FENV_ACCESS ON
int main()
{
std::cout << "tgamma(10) = " << std::tgamma(10)
<< ", 9! = " << 2*3*4*5*6*7*8*9 << '\n'
<< "tgamma(0.5) = " << std::tgamma(0.5)
<< ", sqrt(pi) = " << std::sqrt(std::acos(-1)) << '\n';
// special values
std::cout << "tgamma(1) = " << std::tgamma(1) << '\n'
<< "tgamma(+Inf) = " << std::tgamma(INFINITY) << '\n';
// error handling
errno=0;
std::feclearexcept(FE_ALL_EXCEPT);
std::cout << "tgamma(-1) = " << std::tgamma(-1) << '\n';
if (errno == EDOM)
std::cout << " errno == EDOM: " << std::strerror(errno) << '\n';
if (std::fetestexcept(FE_INVALID))
std::cout << " FE_INVALID raised\n";
}
```
Possible output:
```
tgamma(10) = 362880, 9! = 362880
tgamma(0.5) = 1.77245, sqrt(pi) = 1.77245
tgamma(1) = 1
tgamma(+Inf) = inf
tgamma(-1) = nan
errno == EDOM: Numerical argument out of domain
FE_INVALID raised
```
### See also
| | |
| --- | --- |
| [lgammalgammaflgammal](lgamma "cpp/numeric/math/lgamma")
(C++11)(C++11)(C++11) | natural logarithm of the gamma function (function) |
| [betabetafbetal](../special_functions/beta "cpp/numeric/special functions/beta")
(C++17)(C++17)(C++17) | beta function (function) |
| [C documentation](https://en.cppreference.com/w/c/numeric/math/tgamma "c/numeric/math/tgamma") for `tgamma` |
### External links
[Weisstein, Eric W. "Gamma Function."](http://mathworld.wolfram.com/GammaFunction.html) From MathWorld--A Wolfram Web Resource.
cpp std::ceil, std::ceilf, std::ceill std::ceil, std::ceilf, std::ceill
=================================
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
|
```
float ceil ( float arg );
```
| (1) | (constexpr since C++23) |
|
```
float ceilf( float arg );
```
| (2) | (since C++11) (constexpr since C++23) |
|
```
double ceil ( double arg );
```
| (3) | (constexpr since C++23) |
|
```
long double ceil ( long double arg );
```
| (4) | (constexpr since C++23) |
|
```
long double ceill( long double arg );
```
| (5) | (since C++11) (constexpr since C++23) |
|
```
double ceil ( IntegralType arg );
```
| (6) | (since C++11) (constexpr since C++23) |
1-5) Computes the smallest integer value not less than `arg`.
6) A set of overloads or a function template accepting an argument of any [integral type](../../types/is_integral "cpp/types/is integral"). Equivalent to (3) (the argument is cast to `double`). ### Parameters
| | | |
| --- | --- | --- |
| arg | - | floating point value |
### Return value
If no errors occur, the smallest integer value not less than `arg`, that is โargโ, is returned.
Return value ![math-ceil.svg]() Argument ### Error handling
Errors are reported as specified in `[math\_errhandling](math_errhandling "cpp/numeric/math/math errhandling")`.
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* The current [rounding mode](../fenv/fe_round "cpp/numeric/fenv/FE round") has no effect.
* If `arg` is ยฑโ, it is returned unmodified
* If `arg` is ยฑ0, it is returned, unmodified
* If arg is NaN, NaN is returned
### Notes
`[FE\_INEXACT](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` may be (but isn't required to be) raised when rounding a non-integer finite value.
The largest representable floating-point values are exact integers in all standard floating-point formats, so this function never overflows on its own; however the result may overflow any integer type (including `[std::intmax\_t](../../types/integer "cpp/types/integer")`), when stored in an integer variable.
This function (for double argument) behaves as if (except for the freedom to not raise `[FE\_INEXACT](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")`) implemented by the following code:
```
#include <cmath>
#include <cfenv>
#pragma STDC FENV_ACCESS ON
double ceil(double x)
{
double result;
int save_round = std::fegetround();
std::fesetround(FE_UPWARD);
result = std::rint(x); // or std::nearbyint
std::fesetround(save_round);
return result;
}
```
### Example
```
#include <cmath>
#include <iostream>
int main()
{
std::cout << std::fixed
<< "ceil(+2.4) = " << std::ceil(+2.4) << '\n'
<< "ceil(-2.4) = " << std::ceil(-2.4) << '\n'
<< "ceil(-0.0) = " << std::ceil(-0.0) << '\n'
<< "ceil(-Inf) = " << std::ceil(-INFINITY) << '\n';
}
```
Output:
```
ceil(+2.4) = 3.000000
ceil(-2.4) = -2.000000
ceil(-0.0) = -0.000000
ceil(-Inf) = -inf
```
### See also
| | |
| --- | --- |
| [floorfloorffloorl](floor "cpp/numeric/math/floor")
(C++11)(C++11) | nearest integer not greater than the given value (function) |
| [trunctruncftruncl](trunc "cpp/numeric/math/trunc")
(C++11)(C++11)(C++11) | nearest integer not greater in magnitude than the given value (function) |
| [roundroundfroundllroundlroundflroundlllroundllroundfllroundl](round "cpp/numeric/math/round")
(C++11)(C++11)(C++11)(C++11)(C++11)(C++11)(C++11)(C++11)(C++11) | nearest integer, rounding away from zero in halfway cases (function) |
| [nearbyintnearbyintfnearbyintl](nearbyint "cpp/numeric/math/nearbyint")
(C++11)(C++11)(C++11) | nearest integer using current rounding mode (function) |
| [rintrintfrintllrintlrintflrintlllrintllrintfllrintl](rint "cpp/numeric/math/rint")
(C++11)(C++11)(C++11)(C++11)(C++11)(C++11)(C++11)(C++11)(C++11) | nearest integer using current rounding mode with exception if the result differs (function) |
| [C documentation](https://en.cppreference.com/w/c/numeric/math/ceil "c/numeric/math/ceil") for `ceil` |
cpp std::hypot, std::hypotf, std::hypotl std::hypot, std::hypotf, std::hypotl
====================================
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
|
```
float hypot ( float x, float y );
float hypotf( float x, float y );
```
| (1) | (since C++11) |
|
```
double hypot ( double x, double y );
```
| (2) | (since C++11) |
|
```
long double hypot ( long double x, long double y );
long double hypotl( long double x, long double y );
```
| (3) | (since C++11) |
|
```
Promoted hypot ( Arithmetic1 x, Arithmetic2 y );
```
| (4) | (since C++11) |
|
```
float hypot ( float x, float y, float z );
```
| (5) | (since C++17) |
|
```
double hypot ( double x, double y, double z );
```
| (6) | (since C++17) |
|
```
long double hypot ( long double x, long double y, long double z );
```
| (7) | (since C++17) |
|
```
Promoted hypot ( Arithmetic1 x, Arithmetic2 y, Arithmetic3 z );
```
| (8) | (since C++17) |
1-3) Computes the square root of the sum of the squares of `x` and `y`, without undue overflow or underflow at intermediate stages of the computation.
4) A set of overloads or a function template for all combinations of arguments of arithmetic type not covered by (1-3). If any argument has [integral type](../../types/is_integral "cpp/types/is integral"), it is cast to `double`. If any other argument is `long double`, then the return type is `long double`, otherwise it is `double`.
5-7) Computes the square root of the sum of the squares of `x`, `y`, and `z`, without undue overflow or underflow at intermediate stages of the computation.
8) A set of overloads or a function template for all combinations of arguments of arithmetic type not covered by (5-7). If any argument has [integral type](../../types/is_integral "cpp/types/is integral"), it is cast to `double`. If any other argument is `long double`, then the return type is `long double`, otherwise it is `double`. The value computed by the two-argument version of this function is the length of the hypotenuse of a right-angled triangle with sides of length `x` and `y`, or the distance of the point `(x,y)` from the origin `(0,0)`, or the magnitude of a complex number `x+*i*y`.
The value computed by the three-argument version of this function is the distance of the point `(x,y,z)` from the origin `(0,0,0)`.
### Parameters
| | | |
| --- | --- | --- |
| x, y, z | - | values of floating-point or [integral types](../../types/is_integral "cpp/types/is integral") |
### Return value
1-4) If no errors occur, the hypotenuse of a right-angled triangle, \(\scriptsize{\sqrt{x^2+y^2} }\)โx2
+y2
, is returned.
5-8) If no errors occur, the distance from origin in 3D space, \(\scriptsize{\sqrt{x^2+y^2+z^2} }\)โx2
+y2
+z2
, is returned. If a range error due to overflow occurs, `[+HUGE\_VAL](huge_val "cpp/numeric/math/HUGE VAL")`, `+HUGE_VALF`, or `+HUGE_VALL` is returned.
If a range error due to underflow occurs, the correct result (after rounding) is returned.
### Error handling
Errors are reported as specified in `[math\_errhandling](math_errhandling "cpp/numeric/math/math errhandling")`.
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* `hypot(x, y)`, `hypot(y, x)`, and `hypot(x, -y)` are equivalent
* if one of the arguments is ยฑ0, `hypot(x,y)` is equivalent to `fabs` called with the non-zero argument
* if one of the arguments is ยฑโ, `hypot(x,y)` returns +โ even if the other argument is NaN
* otherwise, if any of the arguments is NaN, NaN is returned
### Notes
Implementations usually guarantee precision of less than 1 ulp ([units in the last place](https://en.wikipedia.org/wiki/Unit_in_the_last_place "enwiki:Unit in the last place")): [GNU](http://sourceware.org/git/?p=glibc.git;a=blob_plain;f=sysdeps/ieee754/dbl-64/e_hypot.c), [BSD](http://www.freebsd.org/cgi/cvsweb.cgi/src/lib/msun/src/e_hypot.c).
`std::hypot(x, y)` is equivalent to `std::abs([std::complex](http://en.cppreference.com/w/cpp/numeric/complex)<double>(x,y))`.
[POSIX specifies](http://pubs.opengroup.org/onlinepubs/9699919799/functions/hypot.html) that underflow may only occur when both arguments are subnormal and the correct result is also subnormal (this forbids naive implementations).
| | | | |
| --- | --- | --- | --- |
| Distance between two points `(x1,y1,z1)` and `(x2,y2,z2)` on 3D space can be calculated using 3-argument overload of `std::hypot` as `std::hypot(x2-x1, y2-y1, z2-z1)`.
| [Feature-test](../../utility/feature_test "cpp/utility/feature test") macro |
| --- |
| [`__cpp_lib_hypot`](../../feature_test#Library_features "cpp/feature test") |
| (since C++17) |
### Example
```
#include <iostream>
#include <cmath>
#include <cerrno>
#include <cfenv>
#include <cfloat>
#include <cstring>
// #pragma STDC FENV_ACCESS ON
int main()
{
// typical usage
std::cout << "(1,1) cartesian is (" << std::hypot(1,1)
<< ',' << std::atan2(1,1) << ") polar\n";
struct Point3D { float x, y, z; } a{3.14,2.71,9.87}, b{1.14,5.71,3.87};
// C++17 has 3-argumnet hypot overload:
std::cout << "distance(a,b) = " << std::hypot(a.x-b.x,a.y-b.y,a.z-b.z) << '\n';
// special values
std::cout << "hypot(NAN,INFINITY) = " << std::hypot(NAN,INFINITY) << '\n';
// error handling
errno = 0;
std::feclearexcept(FE_ALL_EXCEPT);
std::cout << "hypot(DBL_MAX,DBL_MAX) = " << std::hypot(DBL_MAX,DBL_MAX) << '\n';
if (errno == ERANGE)
std::cout << " errno = ERANGE " << std::strerror(errno) << '\n';
if (std::fetestexcept(FE_OVERFLOW))
std::cout << " FE_OVERFLOW raised\n";
}
```
Output:
```
(1,1) cartesian is (1.41421,0.785398) polar
distance(a,b) = 7
hypot(NAN,INFINITY) = inf
hypot(DBL_MAX,DBL_MAX) = inf
errno = ERANGE Numerical result out of range
FE_OVERFLOW raised
```
### See also
| | |
| --- | --- |
| [powpowfpowl](pow "cpp/numeric/math/pow")
(C++11)(C++11) | raises a number to the given power (\(\small{x^y}\)xy) (function) |
| [sqrtsqrtfsqrtl](sqrt "cpp/numeric/math/sqrt")
(C++11)(C++11) | computes square root (\(\small{\sqrt{x} }\)โx) (function) |
| [cbrtcbrtfcbrtl](cbrt "cpp/numeric/math/cbrt")
(C++11)(C++11)(C++11) | computes cubic root (\(\small{\sqrt[3]{x} }\)3โx) (function) |
| [abs(std::complex)](../complex/abs "cpp/numeric/complex/abs") | returns the magnitude of a complex number (function template) |
| [C documentation](https://en.cppreference.com/w/c/numeric/math/hypot "c/numeric/math/hypot") for `hypot` |
cpp std::ldexp, std::ldexpf, std::ldexpl std::ldexp, std::ldexpf, std::ldexpl
====================================
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
|
```
float ldexp ( float x, int exp );
```
| (1) | (constexpr since C++23) |
|
```
float ldexpf( float x, int exp );
```
| (2) | (since C++11) (constexpr since C++23) |
|
```
double ldexp ( double x, int exp );
```
| (3) | (constexpr since C++23) |
|
```
long double ldexp ( long double x, int exp );
```
| (4) | (constexpr since C++23) |
|
```
long double ldexpl( long double x, int exp );
```
| (5) | (since C++11) (constexpr since C++23) |
|
```
double ldexp ( IntegralType x, int exp );
```
| (6) | (since C++11) (constexpr since C++23) |
1-5) Multiplies a floating point value `x` by the number `2` raised to the `exp` power.
6) A set of overloads or a function template accepting an argument of any [integral type](../../types/is_integral "cpp/types/is integral"). Equivalent to (3) (the argument is cast to `double`). ### Parameters
| | | |
| --- | --- | --- |
| x | - | floating point value |
| exp | - | integer value |
### Return value
If no errors occur, `x` multiplied by 2 to the power of `exp` (xร2exp
) is returned.
If a range error due to overflow occurs, `[ยฑHUGE\_VAL](huge_val "cpp/numeric/math/HUGE VAL")`, `ยฑHUGE_VALF`, or `ยฑHUGE_VALL` is returned.
If a range error due to underflow occurs, the correct result (after rounding) is returned.
### Error handling
Errors are reported as specified in `[math\_errhandling](math_errhandling "cpp/numeric/math/math errhandling")`.
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* Unless a range error occurs, `[FE\_INEXACT](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` is never raised (the result is exact)
* Unless a range error occurs, [the current rounding mode](../fenv/fe_round "cpp/numeric/fenv/FE round") is ignored
* If `x` is ยฑ0, it is returned, unmodified
* If `x` is ยฑโ, it is returned, unmodified
* If `exp` is 0, then `x` is returned, unmodified
* If `x` is NaN, NaN is returned
### Notes
On binary systems (where `[FLT\_RADIX](../../types/climits "cpp/types/climits")` is `2`), `std::ldexp` is equivalent to `[std::scalbn](scalbn "cpp/numeric/math/scalbn")`.
The function `std::ldexp` ("load exponent"), together with its dual, `[std::frexp](frexp "cpp/numeric/math/frexp")`, can be used to manipulate the representation of a floating-point number without direct bit manipulations.
On many implementations, `std::ldexp` is less efficient than multiplication or division by a power of two using arithmetic operators.
### Example
```
#include <iostream>
#include <cmath>
#include <cerrno>
#include <cstring>
#include <cfenv>
// #pragma STDC FENV_ACCESS ON
int main()
{
std::cout << "ldexp(7, -4) = " << std::ldexp(7, -4) << '\n'
<< "ldexp(1, -1074) = " << std::ldexp(1, -1074)
<< " (minimum positive subnormal double)\n"
<< "ldexp(nextafter(1,0), 1024) = "
<< std::ldexp(std::nextafter(1,0), 1024)
<< " (largest finite double)\n";
// special values
std::cout << "ldexp(-0, 10) = " << std::ldexp(-0.0, 10) << '\n'
<< "ldexp(-Inf, -1) = " << std::ldexp(-INFINITY, -1) << '\n';
// error handling
errno = 0;
std::feclearexcept(FE_ALL_EXCEPT);
std::cout << "ldexp(1, 1024) = " << std::ldexp(1, 1024) << '\n';
if (errno == ERANGE)
std::cout << " errno == ERANGE: " << std::strerror(errno) << '\n';
if (std::fetestexcept(FE_OVERFLOW))
std::cout << " FE_OVERFLOW raised\n";
}
```
Output:
```
ldexp(7, -4) = 0.4375
ldexp(1, -1074) = 4.94066e-324 (minimum positive subnormal double)
ldexp(nextafter(1,0), 1024) = 1.79769e+308 (largest finite double)
ldexp(-0, 10) = -0
ldexp(-Inf, -1) = -inf
ldexp(1, 1024) = inf
errno == ERANGE: Numerical result out of range
FE_OVERFLOW raised
```
### See also
| | |
| --- | --- |
| [frexpfrexpffrexpl](frexp "cpp/numeric/math/frexp")
(C++11)(C++11) | decomposes a number into significand and a power of `2` (function) |
| [scalbnscalbnfscalbnlscalblnscalblnfscalblnl](scalbn "cpp/numeric/math/scalbn")
(C++11)(C++11)(C++11)(C++11)(C++11)(C++11) | multiplies a number by `[FLT\_RADIX](../../types/climits "cpp/types/climits")` raised to a power (function) |
| [C documentation](https://en.cppreference.com/w/c/numeric/math/ldexp "c/numeric/math/ldexp") for `ldexp` |
| programming_docs |
cpp std::signbit std::signbit
============
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
|
```
bool signbit( float arg );
```
| (1) | (since C++11) (constexpr since C++23) |
|
```
bool signbit( double arg );
```
| (2) | (since C++11) (constexpr since C++23) |
|
```
bool signbit( long double arg );
```
| (3) | (since C++11) (constexpr since C++23) |
|
```
bool signbit( IntegralType arg );
```
| (4) | (since C++11) (constexpr since C++23) |
1-3) Determines if the given floating point number `arg` is negative.
4) A set of overloads or a function template accepting the `arg` argument of any [integral type](../../types/is_integral "cpp/types/is integral"). Equivalent to (2) (the argument is cast to `double`). ### Parameters
| | | |
| --- | --- | --- |
| arg | - | floating point value |
### Return value
`true` if `arg` is negative, `false` otherwise.
### Notes
This function detects the sign bit of zeroes, infinities, and NaNs. Along with `[std::copysign](copysign "cpp/numeric/math/copysign")`, std::signbit is one of the only two portable ways to examine the sign of a NaN.
### Example
```
#include <iostream>
#include <cmath>
int main()
{
std::cout << std::boolalpha
<< "signbit(+0.0) = " << std::signbit(+0.0) << '\n'
<< "signbit(-0.0) = " << std::signbit(-0.0) << '\n';
}
```
Output:
```
signbit(+0.0) = false
signbit(-0.0) = true
```
### See also
| | |
| --- | --- |
| [abs(float)fabsfabsffabsl](fabs "cpp/numeric/math/fabs")
(C++11)(C++11) | absolute value of a floating point value (\(\small{|x|}\)|x|) (function) |
| [copysigncopysignfcopysignl](copysign "cpp/numeric/math/copysign")
(C++11)(C++11)(C++11) | copies the sign of a floating point value (function) |
| [C documentation](https://en.cppreference.com/w/c/numeric/math/signbit "c/numeric/math/signbit") for `signbit` |
cpp std::isgreaterequal std::isgreaterequal
===================
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
|
```
bool isgreaterequal( float x, float y );
```
| (1) | (since C++11) (constexpr since C++23) |
|
```
bool isgreaterequal( double x, double y );
```
| (2) | (since C++11) (constexpr since C++23) |
|
```
bool isgreaterequal( long double x, long double y );
```
| (3) | (since C++11) (constexpr since C++23) |
|
```
bool isgreaterequal( Arithmetic x, Arithmetic y );
```
| (4) | (since C++11) (constexpr since C++23) |
1-3) Determines if the floating point number `x` is greater than or equal to the floating-point number `y`, without setting floating-point exceptions.
4) A set of overloads or a function template for all combinations of arguments of arithmetic type not covered by (1-3). If any argument has [integral type](../../types/is_integral "cpp/types/is integral"), it is cast to `double`. ### Parameters
| | | |
| --- | --- | --- |
| x | - | floating point value |
| y | - | floating point value |
### Return value
`true` if `x >= y`, `false` otherwise.
### Notes
The built-in `operator>=` for floating-point numbers may raise `[FE\_INVALID](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` if one or both of the arguments is NaN. This function is a "quiet" version of `operator>=`.
### See also
| | |
| --- | --- |
| [greater\_equal](../../utility/functional/greater_equal "cpp/utility/functional/greater equal") | function object implementing `x >= y` (class template) |
| [islessequal](islessequal "cpp/numeric/math/islessequal")
(C++11) | checks if the first floating-point argument is less or equal than the second (function) |
| [C documentation](https://en.cppreference.com/w/c/numeric/math/isgreaterequal "c/numeric/math/isgreaterequal") for `isgreaterequal` |
cpp std::sinh, std::sinhf, std::sinhl std::sinh, std::sinhf, std::sinhl
=================================
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
| | (1) | |
|
```
float sinh ( float arg );
```
| |
|
```
float sinhf( float arg );
```
| (since C++11) |
|
```
double sinh ( double arg );
```
| (2) | |
| | (3) | |
|
```
long double sinh ( long double arg );
```
| |
|
```
long double sinhl( long double arg );
```
| (since C++11) |
|
```
double sinh ( IntegralType arg );
```
| (4) | (since C++11) |
1-3) Computes the hyperbolic sine of `arg`
4) A set of overloads or a function template accepting an argument of any [integral type](../../types/is_integral "cpp/types/is integral"). Equivalent to 2) (the argument is cast to `double`). ### Parameters
| | | |
| --- | --- | --- |
| arg | - | value of a floating-point or [Integral type](../../types/is_integral "cpp/types/is integral") |
### Return value
If no errors occur, the hyperbolic sine of `arg` (sinh(arg), or earg-e-arg/2) is returned. If a range error due to overflow occurs, `[ยฑHUGE\_VAL](huge_val "cpp/numeric/math/HUGE VAL")`, `ยฑHUGE_VALF`, or `ยฑHUGE_VALL` is returned.
If a range error occurs due to underflow, the correct result (after rounding) is returned.
### Error handling
Errors are reported as specified in `[math\_errhandling](math_errhandling "cpp/numeric/math/math errhandling")`.
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* if the argument is ยฑ0 or ยฑโ, it is returned unmodified
* if the argument is NaN, NaN is returned
### Notes
[POSIX specifies](http://pubs.opengroup.org/onlinepubs/9699919799/functions/sinh.html) that in case of underflow, `arg` is returned unmodified, and if that is not supported, and implementation-defined value no greater than DBL\_MIN, FLT\_MIN, and LDBL\_MIN is returned.
### Example
```
#include <iostream>
#include <cmath>
#include <cerrno>
#include <cstring>
#include <cfenv>
#pragma STDC FENV_ACCESS ON
int main()
{
std::cout << "sinh(1) = " << std::sinh(1) << '\n'
<< "sinh(-1) = " << std::sinh(-1) << '\n'
<< "log(sinh(1)+cosh(1)) = "
<< std::log(std::sinh(1)+std::cosh(1)) << '\n';
// special values
std::cout << "sinh(+0) = " << std::sinh(0.0) << '\n'
<< "sinh(-0) = " << std::sinh(-0.0) << '\n';
// error handling
errno = 0;
std::feclearexcept(FE_ALL_EXCEPT);
std::cout << "sinh(710.5) = " << std::sinh(710.5) << '\n';
if (errno == ERANGE)
std::cout << " errno == ERANGE: " << std::strerror(errno) << '\n';
if (std::fetestexcept(FE_OVERFLOW))
std::cout << " FE_OVERFLOW raised\n";
}
```
Output:
```
sinh(1) = 1.1752
sinh(-1) = -1.1752
log(sinh(1)+cosh(1)) = 1
sinh(+0) = 0
sinh(-0) = -0
sinh(710.5) = inf
errno == ERANGE: Numerical result out of range
FE_OVERFLOW raised
```
### See also
| | |
| --- | --- |
| [coshcoshfcoshl](cosh "cpp/numeric/math/cosh")
(C++11)(C++11) | computes hyperbolic cosine (\({\small\cosh{x} }\)cosh(x)) (function) |
| [tanhtanhftanhl](tanh "cpp/numeric/math/tanh")
(C++11)(C++11) | computes hyperbolic tangent (\({\small\tanh{x} }\)tanh(x)) (function) |
| [asinhasinhfasinhl](asinh "cpp/numeric/math/asinh")
(C++11)(C++11)(C++11) | computes the inverse hyperbolic sine (\({\small\operatorname{arsinh}{x} }\)arsinh(x)) (function) |
| [sinh(std::complex)](../complex/sinh "cpp/numeric/complex/sinh") | computes hyperbolic sine of a complex number (\({\small\sinh{z} }\)sinh(z)) (function template) |
| [sinh(std::valarray)](../valarray/sinh "cpp/numeric/valarray/sinh") | applies the function `std::sinh` to each element of valarray (function template) |
| [C documentation](https://en.cppreference.com/w/c/numeric/math/sinh "c/numeric/math/sinh") for `sinh` |
cpp std::lgamma, std::lgammaf, std::lgammal std::lgamma, std::lgammaf, std::lgammal
=======================================
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
|
```
float lgamma ( float arg );
float lgammaf( float arg );
```
| (1) | (since C++11) |
|
```
double lgamma ( double arg );
```
| (2) | (since C++11) |
|
```
long double lgamma ( long double arg );
long double lgammal( long double arg );
```
| (3) | (since C++11) |
|
```
double lgamma ( IntegralType arg );
```
| (4) | (since C++11) |
1-3) Computes the natural logarithm of the absolute value of the [gamma function](https://en.wikipedia.org/wiki/Gamma_function "enwiki:Gamma function") of `arg`.
4) A set of overloads or a function template accepting an argument of any [integral type](../../types/is_integral "cpp/types/is integral"). Equivalent to (2) (the argument is cast to `double`). ### Parameters
| | | |
| --- | --- | --- |
| arg | - | value of a floating-point or [Integral type](../../types/is_integral "cpp/types/is integral") |
### Return value
If no errors occur, the value of the logarithm of the gamma function of `arg`, that is \(\log\_{e}|{\int\_0^\infty t^{arg-1} e^{-t} \mathsf{d}t}|\)log
e|โซโ
0*t*arg-1
*e*-t d*t*|, is returned.
If a pole error occurs, `[+HUGE\_VAL](huge_val "cpp/numeric/math/HUGE VAL")`, `+HUGE_VALF`, or `+HUGE_VALL` is returned.
If a range error due to overflow occurs, `[ยฑHUGE\_VAL](huge_val "cpp/numeric/math/HUGE VAL")`, `ยฑHUGE_VALF`, or `ยฑHUGE_VALL` is returned.
### Error handling
Errors are reported as specified in `[math\_errhandling](math_errhandling "cpp/numeric/math/math errhandling")`.
If `arg` is zero or is an integer less than zero, a pole error may occur.
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* If the argument is 1, +0 is returned
* If the argument is 2, +0 is returned
* If the argument is ยฑ0, +โ is returned and `[FE\_DIVBYZERO](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` is raised
* If the argument is a negative integer, +โ is returned and `[FE\_DIVBYZERO](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` is raised
* If the argument is ยฑโ, +โ is returned.
* If the argument is NaN, NaN is returned
### Notes
If `arg` is a natural number, `std::lgamma(arg)` is the logarithm of the factorial of `arg-1`.
The [POSIX version of lgamma](http://pubs.opengroup.org/onlinepubs/9699919799/functions/lgamma.html) is not thread-safe: each execution of the function stores the sign of the gamma function of `arg` in the static external variable `signgam`. Some implementations provide `lgamma_r`, which takes a pointer to user-provided storage for singgam as the second parameter, and is thread-safe.
There is a non-standard function named `gamma` in various implementations, but its definition is inconsistent. For example, glibc and 4.2BSD version of `gamma` executes `lgamma`, but 4.4BSD version of `gamma` executes `tgamma`.
### Example
```
#include <iostream>
#include <cmath>
#include <cerrno>
#include <cstring>
#include <cfenv>
// #pragma STDC FENV_ACCESS ON
const double pi = std::acos(-1); // or std::numbers::pi since C++20
int main()
{
std::cout << "lgamma(10) = " << std::lgamma(10)
<< ", log(9!) = " << std::log(2*3*4*5*6*7*8*9) << '\n'
<< "lgamma(0.5) = " << std::lgamma(0.5)
<< " , log(sqrt(pi)) = " << std::log(std::sqrt(pi)) << '\n';
// special values
std::cout << "lgamma(1) = " << std::lgamma(1) << '\n'
<< "lgamma(+Inf) = " << std::lgamma(INFINITY) << '\n';
// error handling
errno = 0;
std::feclearexcept(FE_ALL_EXCEPT);
std::cout << "lgamma(0) = " << std::lgamma(0) << '\n';
if (errno == ERANGE)
std::cout << " errno == ERANGE: " << std::strerror(errno) << '\n';
if (std::fetestexcept(FE_DIVBYZERO))
std::cout << " FE_DIVBYZERO raised\n";
}
```
Output:
```
lgamma(10) = 12.8018, log(9!) = 12.8018
lgamma(0.5) = 0.572365 , log(sqrt(pi)) = 0.572365
lgamma(1) = 0
lgamma(+Inf) = inf
lgamma(0) = inf
errno == ERANGE: Numerical result out of range
FE_DIVBYZERO raised
```
### See also
| | |
| --- | --- |
| [tgammatgammaftgammal](tgamma "cpp/numeric/math/tgamma")
(C++11)(C++11)(C++11) | gamma function (function) |
| [C documentation](https://en.cppreference.com/w/c/numeric/math/lgamma "c/numeric/math/lgamma") for `lgamma` |
### External links
[Weisstein, Eric W. "Log Gamma Function."](http://mathworld.wolfram.com/LogGammaFunction.html) From MathWorld--A Wolfram Web Resource.
cpp std::isnan std::isnan
==========
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
|
```
bool isnan( float arg );
```
| (1) | (since C++11) (constexpr since C++23) |
|
```
bool isnan( double arg );
```
| (2) | (since C++11) (constexpr since C++23) |
|
```
bool isnan( long double arg );
```
| (3) | (since C++11) (constexpr since C++23) |
|
```
bool isnan( IntegralType arg );
```
| (4) | (since C++11) (constexpr since C++23) |
1-3) Determines if the given floating point number `arg` is a not-a-number (NaN) value.
4) A set of overloads or a function template accepting the `arg` argument of any [integral type](../../types/is_integral "cpp/types/is integral"). Equivalent to (2) (the argument is cast to `double`). ### Parameters
| | | |
| --- | --- | --- |
| arg | - | floating point value |
### Return value
`true` if `arg` is a NaN, `false` otherwise.
### Notes
There are many different NaN values with different sign bits and payloads, see `[std::nan](nan "cpp/numeric/math/nan")` and `[std::numeric\_limits::quiet\_NaN](../../types/numeric_limits/quiet_nan "cpp/types/numeric limits/quiet NaN")`.
NaN values never compare equal to themselves or to other NaN values. Copying a NaN is not required, by IEEE-754, to preserve its bit representation (sign and [payload](nan "cpp/numeric/math/nan")), though most implementation do.
Another way to test if a floating-point value is NaN is to compare it with itself: `bool is_nan(double x) { return x != x; }`
### Example
```
#include <iostream>
#include <cmath>
#include <cfloat>
int main()
{
std::cout << std::boolalpha
<< "isnan(NaN) = " << std::isnan(NAN) << '\n'
<< "isnan(Inf) = " << std::isnan(INFINITY) << '\n'
<< "isnan(0.0) = " << std::isnan(0.0) << '\n'
<< "isnan(DBL_MIN/2.0) = " << std::isnan(DBL_MIN/2.0) << '\n'
<< "isnan(0.0 / 0.0) = " << std::isnan(0.0/0.0) << '\n'
<< "isnan(Inf - Inf) = " << std::isnan(INFINITY - INFINITY) << '\n';
}
```
Output:
```
isnan(NaN) = true
isnan(Inf) = false
isnan(0.0) = false
isnan(DBL_MIN/2.0) = false
isnan(0.0 / 0.0) = true
isnan(Inf - Inf) = true
```
### See also
| | |
| --- | --- |
| [nannanfnanl](nan "cpp/numeric/math/nan")
(C++11)(C++11)(C++11) | not-a-number (NaN) (function) |
| [fpclassify](fpclassify "cpp/numeric/math/fpclassify")
(C++11) | categorizes the given floating-point value (function) |
| [isfinite](isfinite "cpp/numeric/math/isfinite")
(C++11) | checks if the given number has finite value (function) |
| [isinf](isinf "cpp/numeric/math/isinf")
(C++11) | checks if the given number is infinite (function) |
| [isnormal](isnormal "cpp/numeric/math/isnormal")
(C++11) | checks if the given number is normal (function) |
| [isunordered](isunordered "cpp/numeric/math/isunordered")
(C++11) | checks if two floating-point values are unordered (function) |
| [C documentation](https://en.cppreference.com/w/c/numeric/math/isnan "c/numeric/math/isnan") for `isnan` |
cpp FP_NORMAL, FP_SUBNORMAL, FP_ZERO, FP_INFINITE, FP_NAN FP\_NORMAL, FP\_SUBNORMAL, FP\_ZERO, FP\_INFINITE, FP\_NAN
==========================================================
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
|
```
#define FP_NORMAL /*implementation defined*/
```
| | (since C++11) |
|
```
#define FP_SUBNORMAL /*implementation defined*/
```
| | (since C++11) |
|
```
#define FP_ZERO /*implementation defined*/
```
| | (since C++11) |
|
```
#define FP_INFINITE /*implementation defined*/
```
| | (since C++11) |
|
```
#define FP_NAN /*implementation defined*/
```
| | (since C++11) |
The `FP_NORMAL`, `FP_SUBNORMAL`, `FP_ZERO`, `FP_INFINITE`, `FP_NAN` macros each represent a distinct category of floating-point numbers. They all expand to an integer constant expression.
| Constant | Explanation |
| --- | --- |
| `FP_NORMAL` | indicates that the value is *normal*, i.e. not an infinity, subnormal, not-a-number or zero |
| `FP_SUBNORMAL` | indicates that the value is *subnormal* |
| `FP_ZERO` | indicates that the value is positive or negative zero |
| `FP_INFINITE` | indicates that the value is not representable by the underlying type (positive or negative infinity) |
| `FP_NAN` | indicates that the value is not-a-number (NaN) |
### Example
```
#include <iostream>
#include <cmath>
#include <cfloat>
const char* show_classification(double x) {
switch(std::fpclassify(x)) {
case FP_INFINITE: return "Inf";
case FP_NAN: return "NaN";
case FP_NORMAL: return "normal";
case FP_SUBNORMAL: return "subnormal";
case FP_ZERO: return "zero";
default: return "unknown";
}
}
int main()
{
std::cout << "1.0/0.0 is " << show_classification(1/0.0) << '\n'
<< "0.0/0.0 is " << show_classification(0.0/0.0) << '\n'
<< "DBL_MIN/2 is " << show_classification(DBL_MIN/2) << '\n'
<< "-0.0 is " << show_classification(-0.0) << '\n'
<< "1.0 is " << show_classification(1.0) << '\n';
}
```
Output:
```
1.0/0.0 is Inf
0.0/0.0 is NaN
DBL_MIN/2 is subnormal
-0.0 is zero
1.0 is normal
```
### See also
| | |
| --- | --- |
| [fpclassify](fpclassify "cpp/numeric/math/fpclassify")
(C++11) | categorizes the given floating-point value (function) |
| [C documentation](https://en.cppreference.com/w/c/numeric/math/FP_categories "c/numeric/math/FP categories") for `FP_categories` |
cpp std::acosh, std::acoshf, std::acoshl std::acosh, std::acoshf, std::acoshl
====================================
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
|
```
float acosh ( float arg );
float acoshf( float arg );
```
| (1) | (since C++11) |
|
```
double acosh ( double arg );
```
| (2) | (since C++11) |
|
```
long double acosh ( long double arg );
long double acoshl( long double arg );
```
| (3) | (since C++11) |
|
```
double acosh ( IntegralType arg );
```
| (4) | (since C++11) |
1-3) Computes the inverse hyperbolic cosine of `arg`.
4) A set of overloads or a function template accepting an argument of any [integral type](../../types/is_integral "cpp/types/is integral"). Equivalent to 2) (the argument is cast to `double`). ### Parameters
| | | |
| --- | --- | --- |
| arg | - | value of a floating-point or [Integral type](../../types/is_integral "cpp/types/is integral") |
### Return value
If no errors occur, the inverse hyperbolic cosine of `arg` (cosh-1
(arg), or arcosh(arg)) on the interval [0, +โ], is returned.
If a domain error occurs, an implementation-defined value is returned (NaN where supported).
### Error handling
Errors are reported as specified in `[math\_errhandling](math_errhandling "cpp/numeric/math/math errhandling")`.
If the argument is less than 1, a domain error occurs.
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* if the argument is less than 1, `[FE\_INVALID](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` is raised an NaN is returned
* if the argument is 1, +0 is returned
* if the argument is +โ, +โ is returned
* if the argument is NaN, NaN is returned
### Notes
Although the C standard (to which C++ refers for this function) names this function "arc hyperbolic cosine", the inverse functions of the hyperbolic functions are the area functions. Their argument is the area of a hyperbolic sector, not an arc. The correct name is "inverse hyperbolic cosine" (used by POSIX) or "area hyperbolic cosine".
### Examples
```
#include <iostream>
#include <cmath>
#include <cfloat>
#include <cerrno>
#include <cfenv>
#include <cstring>
#pragma STDC FENV_ACCESS ON
int main()
{
std::cout << "acosh(1) = " << std::acosh(1) << '\n'
<< "acosh(10) = " << std::acosh(10) << '\n'
<< "acosh(DBL_MAX) = " << std::acosh(DBL_MAX) << '\n'
<< "acosh(Inf) = " << std::acosh(INFINITY) << '\n';
// error handling
errno = 0;
std::feclearexcept(FE_ALL_EXCEPT);
std::cout << "acosh(0.5) = " << std::acosh(0.5) << '\n';
if (errno == EDOM)
std::cout << " errno == EDOM: " << std::strerror(errno) << '\n';
if (std::fetestexcept(FE_INVALID))
std::cout << " FE_INVALID raised\n";
}
```
Possible output:
```
acosh(1) = 0
acosh(10) = 2.99322
acosh(DBL_MAX) = 710.476
acosh(Inf) = inf
acosh(0.5) = -nan
errno == EDOM: Numerical argument out of domain
FE_INVALID raised
```
### See also
| | |
| --- | --- |
| [asinhasinhfasinhl](asinh "cpp/numeric/math/asinh")
(C++11)(C++11)(C++11) | computes the inverse hyperbolic sine (\({\small\operatorname{arsinh}{x} }\)arsinh(x)) (function) |
| [atanhatanhfatanhl](atanh "cpp/numeric/math/atanh")
(C++11)(C++11)(C++11) | computes the inverse hyperbolic tangent (\({\small\operatorname{artanh}{x} }\)artanh(x)) (function) |
| [coshcoshfcoshl](cosh "cpp/numeric/math/cosh")
(C++11)(C++11) | computes hyperbolic cosine (\({\small\cosh{x} }\)cosh(x)) (function) |
| [acosh(std::complex)](../complex/acosh "cpp/numeric/complex/acosh")
(C++11) | computes area hyperbolic cosine of a complex number (\({\small\operatorname{arcosh}{z} }\)arcosh(z)) (function template) |
| [C documentation](https://en.cppreference.com/w/c/numeric/math/acosh "c/numeric/math/acosh") for `acosh` |
### External links
[Weisstein, Eric W. "Inverse Hyperbolic Cosine."](http://mathworld.wolfram.com/InverseHyperbolicCosine.html) From MathWorld--A Wolfram Web Resource.
| programming_docs |
cpp std::log, std::logf, std::logl std::log, std::logf, std::logl
==============================
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
| | (1) | |
|
```
float log ( float arg );
```
| |
|
```
float logf( float arg );
```
| (since C++11) |
|
```
double log ( double arg );
```
| (2) | |
| | (3) | |
|
```
long double log ( long double arg );
```
| |
|
```
long double logl( long double arg );
```
| (since C++11) |
|
```
double log ( IntegralType arg );
```
| (4) | (since C++11) |
1-3) Computes the natural (base *e*) logarithm of `arg`.
4) A set of overloads or a function template accepting an argument of any [integral type](../../types/is_integral "cpp/types/is integral"). Equivalent to (2) (the argument is cast to `double`). ### Parameters
| | | |
| --- | --- | --- |
| arg | - | value of floating-point or [Integral type](../../types/is_integral "cpp/types/is integral") |
### Return value
If no errors occur, the natural (base-*e*) logarithm of `arg` (ln(arg) or log
e(arg)) is returned.
If a domain error occurs, an implementation-defined value is returned (NaN where supported).
If a pole error occurs, `[-HUGE\_VAL](huge_val "cpp/numeric/math/HUGE VAL")`, `-HUGE_VALF`, or `-HUGE_VALL` is returned.
### Error handling
Errors are reported as specified in `[math\_errhandling](math_errhandling "cpp/numeric/math/math errhandling")`.
Domain error occurs if `arg` is less than zero.
Pole error may occur if `arg` is zero.
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* If the argument is ยฑ0, -โ is returned and `[FE\_DIVBYZERO](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` is raised.
* If the argument is 1, +0 is returned
* If the argument is negative, NaN is returned and `[FE\_INVALID](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` is raised.
* If the argument is +โ, +โ is returned
* If the argument is NaN, NaN is returned
### Example
```
#include <iostream>
#include <cmath>
#include <cerrno>
#include <cstring>
#include <cfenv>
// #pragma STDC FENV_ACCESS ON
int main()
{
std::cout << "log(1) = " << std::log(1) << '\n'
<< "base-5 logarithm of 125 = " << std::log(125)/std::log(5) << '\n';
// special values
std::cout << "log(1) = " << std::log(1) << '\n'
<< "log(+Inf) = " << std::log(INFINITY) << '\n';
// error handling
errno = 0;
std::feclearexcept(FE_ALL_EXCEPT);
std::cout << "log(0) = " << std::log(0) << '\n';
if (errno == ERANGE)
std::cout << " errno == ERANGE: " << std::strerror(errno) << '\n';
if (std::fetestexcept(FE_DIVBYZERO))
std::cout << " FE_DIVBYZERO raised\n";
}
```
Possible output:
```
log(1) = 0
base-5 logarithm of 125 = 3
log(1) = 0
log(+Inf) = inf
log(0) = -inf
errno == ERANGE: Numerical result out of range
FE_DIVBYZERO raised
```
### See also
| | |
| --- | --- |
| [log10log10flog10l](log10 "cpp/numeric/math/log10")
(C++11)(C++11) | computes common (base *10*) logarithm (\({\small \log\_{10}{x} }\)log10(x)) (function) |
| [log2log2flog2l](log2 "cpp/numeric/math/log2")
(C++11)(C++11)(C++11) | base 2 logarithm of the given number (\({\small \log\_{2}{x} }\)log2(x)) (function) |
| [log1plog1pflog1pl](log1p "cpp/numeric/math/log1p")
(C++11)(C++11)(C++11) | natural logarithm (to base *e*) of 1 plus the given number (\({\small \ln{(1+x)} }\)ln(1+x)) (function) |
| [expexpfexpl](exp "cpp/numeric/math/exp")
(C++11)(C++11) | returns *e* raised to the given power (\({\small e^x}\)ex) (function) |
| [log(std::complex)](../complex/log "cpp/numeric/complex/log") | complex natural logarithm with the branch cuts along the negative real axis (function template) |
| [log(std::valarray)](../valarray/log "cpp/numeric/valarray/log") | applies the function `std::log` to each element of valarray (function template) |
| [C documentation](https://en.cppreference.com/w/c/numeric/math/log "c/numeric/math/log") for `log` |
cpp std::expm1, std::expm1f, std::expm1l std::expm1, std::expm1f, std::expm1l
====================================
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
|
```
float expm1 ( float arg );
float expm1f( float arg );
```
| (1) | (since C++11) |
|
```
double expm1 ( double arg );
```
| (2) | (since C++11) |
|
```
long double expm1 ( long double arg );
long double expm1l( long double arg );
```
| (3) | (since C++11) |
|
```
double expm1 ( IntegralType arg );
```
| (4) | (since C++11) |
1-3) Computes the *e* (Euler's number, `2.7182818`) raised to the given power `arg`, minus `1.0`. This function is more accurate than the expression `[std::exp](http://en.cppreference.com/w/cpp/numeric/math/exp)(arg)-1.0` if `arg` is close to zero.
4) A set of overloads or a function template accepting an argument of any [integral type](../../types/is_integral "cpp/types/is integral"). Equivalent to (2) (the argument is cast to `double`). ### Parameters
| | | |
| --- | --- | --- |
| arg | - | value of floating-point or [Integral type](../../types/is_integral "cpp/types/is integral") |
### Return value
If no errors occur earg
-1 is returned.
If a range error due to overflow occurs, `[+HUGE\_VAL](huge_val "cpp/numeric/math/HUGE VAL")`, `+HUGE_VALF`, or `+HUGE_VALL` is returned.
If a range error occurs due to underflow, the correct result (after rounding) is returned.
### Error handling
Errors are reported as specified in `[math\_errhandling](math_errhandling "cpp/numeric/math/math errhandling")`.
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* If the argument is ยฑ0, it is returned, unmodified
* If the argument is -โ, -1 is returned
* If the argument is +โ, +โ is returned
* If the argument is NaN, NaN is returned
### Notes
The functions `std::expm1` and `[std::log1p](log1p "cpp/numeric/math/log1p")` are useful for financial calculations, for example, when calculating small daily interest rates: (1+x)n
-1 can be expressed as `std::expm1(n \* [std::log1p](http://en.cppreference.com/w/cpp/numeric/math/log1p)(x))`. These functions also simplify writing accurate inverse hyperbolic functions.
For IEEE-compatible type `double`, overflow is guaranteed if 709.8 < arg.
### Example
```
#include <iostream>
#include <cmath>
#include <cerrno>
#include <cstring>
#include <cfenv>
// #pragma STDC FENV_ACCESS ON
int main()
{
std::cout << "expm1(1) = " << std::expm1(1) << '\n'
<< "Interest earned in 2 days on on $100, compounded daily at 1%\n"
<< " on a 30/360 calendar = "
<< 100*std::expm1(2*std::log1p(0.01/360)) << '\n'
<< "exp(1e-16)-1 = " << std::exp(1e-16)-1
<< ", but expm1(1e-16) = " << std::expm1(1e-16) << '\n';
// special values
std::cout << "expm1(-0) = " << std::expm1(-0.0) << '\n'
<< "expm1(-Inf) = " << std::expm1(-INFINITY) << '\n';
// error handling
errno = 0;
std::feclearexcept(FE_ALL_EXCEPT);
std::cout << "expm1(710) = " << std::expm1(710) << '\n';
if (errno == ERANGE)
std::cout << " errno == ERANGE: " << std::strerror(errno) << '\n';
if (std::fetestexcept(FE_OVERFLOW))
std::cout << " FE_OVERFLOW raised\n";
}
```
Possible output:
```
expm1(1) = 1.71828
Interest earned in 2 days on on $100, compounded daily at 1%
on a 30/360 calendar = 0.00555563
exp(1e-16)-1 = 0 expm1(1e-16) = 1e-16
expm1(-0) = -0
expm1(-Inf) = -1
expm1(710) = inf
errno == ERANGE: Result too large
FE_OVERFLOW raised
```
### See also
| | |
| --- | --- |
| [expexpfexpl](exp "cpp/numeric/math/exp")
(C++11)(C++11) | returns *e* raised to the given power (\({\small e^x}\)ex) (function) |
| [exp2exp2fexp2l](exp2 "cpp/numeric/math/exp2")
(C++11)(C++11)(C++11) | returns *2* raised to the given power (\({\small 2^x}\)2x) (function) |
| [log1plog1pflog1pl](log1p "cpp/numeric/math/log1p")
(C++11)(C++11)(C++11) | natural logarithm (to base *e*) of 1 plus the given number (\({\small \ln{(1+x)} }\)ln(1+x)) (function) |
| [C documentation](https://en.cppreference.com/w/c/numeric/math/expm1 "c/numeric/math/expm1") for `expm1` |
cpp std::abs, std::labs, std::llabs, std::imaxabs std::abs, std::labs, std::llabs, std::imaxabs
=============================================
| Defined in header `[<cstdlib>](../../header/cstdlib "cpp/header/cstdlib")` | | |
| --- | --- | --- |
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
|
```
int abs( int n );
```
| (1) | (constexpr since C++23) |
|
```
long abs( long n );
```
| (2) | (constexpr since C++23) |
|
```
long long abs( long long n );
```
| (3) | (since C++11) (constexpr since C++23) |
| Defined in header `[<cstdlib>](../../header/cstdlib "cpp/header/cstdlib")` | | |
|
```
long labs( long n );
```
| (4) | (constexpr since C++23) |
|
```
long long llabs( long long n );
```
| (5) | (since C++11) (constexpr since C++23) |
| Defined in header `[<cinttypes>](../../header/cinttypes "cpp/header/cinttypes")` | | |
|
```
std::intmax_t abs( std::intmax_t n );
```
| (6) | (since C++11) |
|
```
std::intmax_t imaxabs( std::intmax_t n );
```
| (7) | (since C++11) |
Computes the absolute value of an integer number. The behavior is undefined if the result cannot be represented by the return type.
If `std::abs` is called with an unsigned integral argument that cannot be converted to `int` by [integral promotion](../../language/implicit_conversion#Integral_promotion "cpp/language/implicit conversion"), the program is ill-formed.
| | |
| --- | --- |
| Overload (6) of `std::abs` for `[std::intmax\_t](../../types/integer "cpp/types/integer")` is provided in [`<cinttypes>`](../../header/cinttypes "cpp/header/cinttypes") if and only if `[std::intmax\_t](../../types/integer "cpp/types/integer")` is an extended integer type. | (since C++11) |
### Parameters
| | | |
| --- | --- | --- |
| n | - | integer value |
### Return value
The absolute value of `n` (i.e. `|n|`), if it is representable.
### Notes
In 2's complement systems, the absolute value of the most-negative value is out of range, e.g. for 32-bit 2's complement type `int`, `[INT\_MIN](../../types/climits "cpp/types/climits")` is `-2147483648`, but the would-be result `2147483648` is greater than `[INT\_MAX](../../types/climits "cpp/types/climits")`, which is `2147483647`.
### Example
```
#include <iostream>
#include <cstdlib>
#include <climits>
int main()
{
std::cout << std::showpos
<< "abs(+3) = " << std::abs(3) << '\n'
<< "abs(-3) = " << std::abs(-3) << '\n';
// std::cout << std::abs(INT_MIN); // undefined behavior on 2's complement systems
}
```
Output:
```
abs(+3) = +3
abs(-3) = +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 2192](https://cplusplus.github.io/LWG/issue2192) | C++98 | overloads of `std::abs` were inconsistentlydeclared in two headers | declared these overloads in both headers |
### See also
| | |
| --- | --- |
| [abs(float)fabsfabsffabsl](fabs "cpp/numeric/math/fabs")
(C++11)(C++11) | absolute value of a floating point value (\(\small{|x|}\)|x|) (function) |
| [abs(std::complex)](../complex/abs "cpp/numeric/complex/abs") | returns the magnitude of a complex number (function template) |
| [abs(std::valarray)](../valarray/abs "cpp/numeric/valarray/abs") | applies the function `abs` to each element of valarray (function template) |
| [C documentation](https://en.cppreference.com/w/c/numeric/math/abs "c/numeric/math/abs") for `abs, labs, llabs` |
cpp HUGE_VALF, HUGE_VAL, HUGE_VALL HUGE\_VALF, HUGE\_VAL, HUGE\_VALL
=================================
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
|
```
#define HUGE_VALF /*implementation defined*/
```
| | (since C++11) |
|
```
#define HUGE_VAL /*implementation defined*/
```
| | |
|
```
#define HUGE_VALL /*implementation defined*/
```
| | (since C++11) |
The `HUGE_VALF`, `HUGE_VAL` and `HUGE_VALL` macros expand to positive floating point constant expressions which compare equal to the values returned by floating-point functions and operators in case of overflow (see `[math\_errhandling](math_errhandling "cpp/numeric/math/math errhandling")`).
| Constant | Explanation |
| --- | --- |
| `HUGE_VALF` | Expands to positive `float` expression that indicates overflow |
| `HUGE_VAL` | Expands to positive `double` expression that indicates overflow, not necessarily representable as a `float` |
| `HUGE_VALL` | Expands to positive `long double` expression that indicates overflow, not necessarily representable as a `float` or `double` |
On implementations that support floating-point infinities, these macros always expand to the positive infinities of `float`, `double`, and `long double`, respectively.
### See also
| | |
| --- | --- |
| [INFINITY](infinity "cpp/numeric/math/INFINITY")
(C++11) | evaluates to positive infinity or the value guaranteed to overflow a `float` (macro constant) |
| [C documentation](https://en.cppreference.com/w/c/numeric/math/HUGE_VAL "c/numeric/math/HUGE VAL") for `HUGE_VAL` |
cpp std::fmod, std::fmodf, std::fmodl std::fmod, std::fmodf, std::fmodl
=================================
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
|
```
float fmod ( float x, float y );
```
| (1) | (constexpr since C++23) |
|
```
float fmodf( float x, float y );
```
| (2) | (since C++11) (constexpr since C++23) |
|
```
double fmod ( double x, double y );
```
| (3) | (constexpr since C++23) |
|
```
long double fmod ( long double x, long double y );
```
| (4) | (constexpr since C++23) |
|
```
long double fmodl( long double x, long double y );
```
| (5) | (since C++11) (constexpr since C++23) |
|
```
Promoted fmod ( Arithmetic1 x, Arithmetic2 y );
```
| (6) | (since C++11) (constexpr since C++23) |
1-5) Computes the floating-point remainder of the division operation `x/y`.
6) A set of overloads or a function template for all combinations of arguments of [arithmetic type](../../types/is_arithmetic "cpp/types/is arithmetic") not covered by (1-5). If any argument has [integral type](../../types/is_integral "cpp/types/is integral"), it is cast to `double`. If any other argument is `long double`, then the return type is `long double`, otherwise it is `double`. The floating-point remainder of the division operation `x/y` calculated by this function is exactly the value `x - n*y`, where `n` is `x/y` with its fractional part truncated.
The returned value has the same sign as `x` and is less than `y` in magnitude.
### Parameters
| | | |
| --- | --- | --- |
| x, y | - | floating point values |
### Return value
If successful, returns the floating-point remainder of the division `x/y` as defined above.
If a domain error occurs, an implementation-defined value is returned (NaN where supported).
If a range error occurs due to underflow, the correct result (after rounding) is returned.
### Error handling
Errors are reported as specified in `[math\_errhandling](math_errhandling "cpp/numeric/math/math errhandling")`.
Domain error may occur if `y` is zero.
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* If `x` is ยฑ0 and `y` is not zero, ยฑ0 is returned
* If `x` is ยฑโ and `y` is not NaN, NaN is returned and `[FE\_INVALID](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` is raised
* If `y` is ยฑ0 and `x` is not NaN, NaN is returned and `[FE\_INVALID](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` is raised
* If `y` is ยฑโ and `x` is finite, `x` is returned.
* If either argument is NaN, NaN is returned
### Notes
[POSIX requires](http://pubs.opengroup.org/onlinepubs/9699919799/functions/fmod.html) that a domain error occurs if `x` is infinite or `y` is zero.
`std::fmod`, but not `[std::remainder](remainder "cpp/numeric/math/remainder")` is useful for doing silent wrapping of floating-point types to unsigned integer types: `(0.0 <= (y = std::fmod( [std::rint](http://en.cppreference.com/w/cpp/numeric/math/rint)(x), 65536.0 )) ? y : 65536.0 + y)` is in the range `[-0.0 .. 65535.0]`, which corresponds to `unsigned short`, but `[std::remainder](http://en.cppreference.com/w/cpp/numeric/math/remainder)([std::rint](http://en.cppreference.com/w/cpp/numeric/math/rint)(x), 65536.0` is in the range `[-32767.0, +32768.0]`, which is outside of the range of `signed short`.
The `double` version of `std::fmod` behaves as if implemented as follows:
```
double fmod(double x, double y)
{
#pragma STDC FENV_ACCESS ON
double result = std::remainder(std::fabs(x), (y = std::fabs(y)));
if (std::signbit(result)) result += y;
return std::copysign(result, x);
}
```
The expression `x - trunc(x/y)*y` may not equal `fmod(x,y)`, when the rounding of `x/y` to initialize the argument of `trunc` loses too much precision (example: `x = 30.508474576271183309`, `y = 6.1016949152542370172`).
### Example
```
#include <iostream>
#include <cmath>
#include <cfenv>
// #pragma STDC FENV_ACCESS ON
int main()
{
std::cout << "fmod(+5.1, +3.0) = " << std::fmod(5.1,3) << '\n'
<< "fmod(-5.1, +3.0) = " << std::fmod(-5.1,3) << '\n'
<< "fmod(+5.1, -3.0) = " << std::fmod(5.1,-3) << '\n'
<< "fmod(-5.1, -3.0) = " << std::fmod(-5.1,-3) << '\n';
// special values
std::cout << "fmod(+0.0, 1.0) = " << std::fmod(0, 1) << '\n'
<< "fmod(-0.0, 1.0) = " << std::fmod(-0.0, 1) << '\n'
<< "fmod(5.1, Inf) = " << std::fmod(5.1, INFINITY) << '\n';
// error handling
std::feclearexcept(FE_ALL_EXCEPT);
std::cout << "fmod(+5.1, 0) = " << std::fmod(5.1, 0) << '\n';
if(std::fetestexcept(FE_INVALID))
std::cout << " FE_INVALID raised\n";
}
```
Possible output:
```
fmod(+5.1, +3.0) = 2.1
fmod(-5.1, +3.0) = -2.1
fmod(+5.1, -3.0) = 2.1
fmod(-5.1, -3.0) = -2.1
fmod(+0.0, 1.0) = 0
fmod(-0.0, 1.0) = -0
fmod(5.1, Inf) = 5.1
fmod(+5.1, 0) = -nan
FE_INVALID raised
```
### See also
| | |
| --- | --- |
| [div(int)ldivlldiv](div "cpp/numeric/math/div")
(C++11) | computes quotient and remainder of integer division (function) |
| [remainderremainderfremainderl](remainder "cpp/numeric/math/remainder")
(C++11)(C++11)(C++11) | signed remainder of the division operation (function) |
| [remquoremquofremquol](remquo "cpp/numeric/math/remquo")
(C++11)(C++11)(C++11) | signed remainder as well as the three last bits of the division operation (function) |
| [C documentation](https://en.cppreference.com/w/c/numeric/math/fmod "c/numeric/math/fmod") for `fmod` |
cpp std::fma, std::fmaf, std::fmal std::fma, std::fmaf, std::fmal
==============================
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
|
```
float fma ( float x, float y, float z );
```
| (1) | (since C++11) (constexpr since C++23) |
|
```
float fmaf( float x, float y, float z );
```
| (2) | (since C++11) (constexpr since C++23) |
|
```
double fma ( double x, double y, double z );
```
| (3) | (since C++11) (constexpr since C++23) |
|
```
long double fma ( long double x, long double y, long double z );
```
| (4) | (since C++11) (constexpr since C++23) |
|
```
long double fmal( long double x, long double y, long double z );
```
| (5) | (since C++11) (constexpr since C++23) |
|
```
Promoted fma ( Arithmetic1 x, Arithmetic2 y, Arithmetic3 z );
```
| (6) | (since C++11) (constexpr since C++23) |
|
```
#define FP_FAST_FMA /* implementation-defined */
```
| (7) | (since C++11) |
|
```
#define FP_FAST_FMAF /* implementation-defined */
```
| (8) | (since C++11) |
|
```
#define FP_FAST_FMAL /* implementation-defined */
```
| (9) | (since C++11) |
1-5) Computes `(x*y) + z` as if to infinite precision and rounded only once to fit the result type.
6) A set of overloads or a function template for all combinations of arguments of [arithmetic type](../../types/is_arithmetic "cpp/types/is arithmetic") not covered by (1-5). If any argument has [integral type](../../types/is_integral "cpp/types/is integral"), it is cast to `double`. If any other argument is `long double`, then the return type is `long double`, otherwise it is `double`.
7-9) If the macro constants `FP_FAST_FMA`, `FP_FAST_FMAF`, or `FP_FAST_FMAL` are defined, the function `std::fma` evaluates faster (in addition to being more precise) than the expression `x*y+z` for `float`, `double`, and `long double` arguments, respectively. If defined, these macros evaluate to integer `1`. ### Parameters
| | | |
| --- | --- | --- |
| x, y, z | - | values of floating-point or [integral types](../../types/is_integral "cpp/types/is integral") |
### Return value
If successful, returns the value of `(x*y) + z` as if calculated to infinite precision and rounded once to fit the result type (or, alternatively, calculated as a single ternary floating-point operation).
If a range error due to overflow occurs, `[ยฑHUGE\_VAL](huge_val "cpp/numeric/math/HUGE VAL")`, `ยฑHUGE_VALF`, or `ยฑHUGE_VALL` is returned.
If a range error due to underflow occurs, the correct value (after rounding) is returned.
### Error handling
Errors are reported as specified in `[math\_errhandling](math_errhandling "cpp/numeric/math/math errhandling")`.
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* If x is zero and y is infinite or if x is infinite and y is zero, and z is not a NaN, then NaN is returned and `[FE\_INVALID](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` is raised
* If x is zero and y is infinite or if x is infinite and y is zero, and z is a NaN, then NaN is returned and `[FE\_INVALID](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` may be raised
* If `x*y` is an exact infinity and z is an infinity with the opposite sign, NaN is returned and `[FE\_INVALID](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` is raised
* If x or y are NaN, NaN is returned
* If z is NaN, and `x*y` aren't 0\*Inf or Inf\*0, then NaN is returned (without `[FE\_INVALID](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")`).
### Notes
This operation is commonly implemented in hardware as [fused multiply-add](https://en.wikipedia.org/wiki/Multiply%E2%80%93accumulate_operation "enwiki:Multiplyโaccumulate operation") CPU instruction. If supported by hardware, the appropriate `FP_FAST_FMA?` macros are expected to be defined, but many implementations make use of the CPU instruction even when the macros are not defined.
[POSIX additionally specifies](http://pubs.opengroup.org/onlinepubs/9699919799/functions/fma.html) that the situations specified to return `[FE\_INVALID](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` are domain errors.
Due to its infinite intermediate precision, `std::fma` is a common building block of other correctly-rounded mathematical operations, such as `[std::sqrt](sqrt "cpp/numeric/math/sqrt")` or even the division (where not provided by the CPU, e.g. [Itanium](https://en.wikipedia.org/wiki/Itanium "enwiki:Itanium")).
As with all floating-point expressions, the expression `(x*y) + z` may be compiled as a fused multiply-add unless the [`#pragma`](../../preprocessor/impl "cpp/preprocessor/impl") `STDC FP_CONTRACT` is off.
### Example
```
#include <iostream>
#include <iomanip>
#include <cmath>
#include <cfenv>
#ifndef __GNUC__
#pragma STDC FENV_ACCESS ON
#endif
int main()
{
// demo the difference between fma and built-in operators
const double in = 0.1;
std::cout << "0.1 double is " << std::setprecision(23) << in
<< " (" << std::hexfloat << in << std::defaultfloat << ")\n"
<< "0.1*10 is 1.0000000000000000555112 (0x8.0000000000002p-3), "
<< "or 1.0 if rounded to double\n";
const double expr_result = 0.1 * 10 - 1;
const double fma_result = std::fma(0.1, 10, -1);
std::cout << "0.1 * 10 - 1 = " << expr_result
<< " : 1 subtracted after intermediate rounding\n"
<< "fma(0.1, 10, -1) = " << std::setprecision(6) << fma_result << " ("
<< std::hexfloat << fma_result << std::defaultfloat << ")\n\n";
// fma is used in double-double arithmetic
const double high = 0.1 * 10;
const double low = std::fma(0.1, 10, -high);
std::cout << "in double-double arithmetic, 0.1 * 10 is representable as "
<< high << " + " << low << "\n\n";
// error handling
std::feclearexcept(FE_ALL_EXCEPT);
std::cout << "fma(+Inf, 10, -Inf) = " << std::fma(INFINITY, 10, -INFINITY) << '\n';
if(std::fetestexcept(FE_INVALID))
std::cout << " FE_INVALID raised\n";
}
```
Possible output:
```
0.1 double is 0.10000000000000000555112 (0x1.999999999999ap-4)
0.1*10 is 1.0000000000000000555112 (0x8.0000000000002p-3), or 1.0 if rounded to double
0.1 * 10 - 1 = 0 : 1 subtracted after intermediate rounding
fma(0.1, 10, -1) = 5.55112e-17 (0x1p-54)
in double-double arithmetic, 0.1 * 10 is representable as 1 + 5.55112e-17
fma(+Inf, 10, -Inf) = -nan
FE_INVALID raised
```
### See also
| | |
| --- | --- |
| [remainderremainderfremainderl](remainder "cpp/numeric/math/remainder")
(C++11)(C++11)(C++11) | signed remainder of the division operation (function) |
| [remquoremquofremquol](remquo "cpp/numeric/math/remquo")
(C++11)(C++11)(C++11) | signed remainder as well as the three last bits of the division operation (function) |
| [C documentation](https://en.cppreference.com/w/c/numeric/math/fma "c/numeric/math/fma") for `fma` |
| programming_docs |
cpp std::modf, std::modff, std::modfl std::modf, std::modff, std::modfl
=================================
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
|
```
float modf ( float x, float* iptr );
```
| (1) | (constexpr since C++23) |
|
```
float modff( float x, float* iptr );
```
| (2) | (since C++11) (constexpr since C++23) |
|
```
double modf ( double x, double* iptr );
```
| (3) | (constexpr since C++23) |
|
```
long double modf ( long double x, long double* iptr );
```
| (4) | (constexpr since C++23) |
|
```
long double modfl( long double x, long double* iptr );
```
| (5) | (since C++11) (constexpr since C++23) |
1-5) Decomposes given floating point value `x` into integral and fractional parts, each having the same type and sign as `x`. The integral part (in floating-point format) is stored in the object pointed to by `iptr`. ### Parameters
| | | |
| --- | --- | --- |
| x | - | floating point value |
| iptr | - | pointer to floating point value to store the integral part to |
### Return value
If no errors occur, returns the fractional part of `x` with the same sign as `x`. The integral part is put into the value pointed to by `iptr`.
The sum of the returned value and the value stored in `*iptr` gives `x` (allowing for rounding).
### Error handling
This function is not subject to any errors specified in `[math\_errhandling](math_errhandling "cpp/numeric/math/math errhandling")`.
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* If `x` is ยฑ0, ยฑ0 is returned, and ยฑ0 is stored in `*iptr`.
* If `x` is ยฑโ, ยฑ0 is returned, and ยฑโ is stored in `*iptr`.
* If `x` is NaN, NaN is returned, and NaN is stored in `*iptr`.
* The returned value is exact, [the current rounding mode](../fenv/fe_round "cpp/numeric/fenv/FE round") is ignored
### Notes
This function behaves as if implemented as follows:
```
double modf(double x, double* iptr)
{
#pragma STDC FENV_ACCESS ON
int save_round = std::fegetround();
std::fesetround(FE_TOWARDZERO);
*iptr = std::nearbyint(x);
std::fesetround(save_round);
return std::copysign(std::isinf(x) ? 0.0 : x - (*iptr), x);
}
```
### Example
Compares different floating-point decomposition functions.
```
#include <iostream>
#include <cmath>
#include <limits>
int main()
{
double f = 123.45;
std::cout << "Given the number " << f << " or " << std::hexfloat
<< f << std::defaultfloat << " in hex,\n";
double f3;
double f2 = std::modf(f, &f3);
std::cout << "modf() makes " << f3 << " + " << f2 << '\n';
int i;
f2 = std::frexp(f, &i);
std::cout << "frexp() makes " << f2 << " * 2^" << i << '\n';
i = std::ilogb(f);
std::cout << "logb()/ilogb() make " << f/std::scalbn(1.0, i) << " * "
<< std::numeric_limits<double>::radix
<< "^" << std::ilogb(f) << '\n';
// special values
f2 = std::modf(-0.0, &f3);
std::cout << "modf(-0) makes " << f3 << " + " << f2 << '\n';
f2 = std::modf(-INFINITY, &f3);
std::cout << "modf(-Inf) makes " << f3 << " + " << f2 << '\n';
}
```
Possible output:
```
Given the number 123.45 or 0x1.edccccccccccdp+6 in hex,
modf() makes 123 + 0.45
frexp() makes 0.964453 * 2^7
logb()/ilogb() make 1.92891 * 2^6
modf(-0) makes -0 + -0
modf(-Inf) makes -INF + -0
```
### See also
| | |
| --- | --- |
| [trunctruncftruncl](trunc "cpp/numeric/math/trunc")
(C++11)(C++11)(C++11) | nearest integer not greater in magnitude than the given value (function) |
| [C documentation](https://en.cppreference.com/w/c/numeric/math/modf "c/numeric/math/modf") for `modf` |
cpp std::log10, std::log10f, std::log10l std::log10, std::log10f, std::log10l
====================================
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
| | (1) | |
|
```
float log10 ( float arg );
```
| |
|
```
float log10f( float arg );
```
| (since C++11) |
|
```
double log10 ( double arg );
```
| (2) | |
| | (3) | |
|
```
long double log10 ( long double arg );
```
| |
|
```
long double log10l( long double arg );
```
| (since C++11) |
|
```
double log10 ( IntegralType arg );
```
| (4) | (since C++11) |
1-3) Computes the common (base-*10*) logarithm of `arg`.
4) A set of overloads or a function template accepting an argument of any [integral type](../../types/is_integral "cpp/types/is integral"). Equivalent to 2) (the argument is cast to `double`). ### Parameters
| | | |
| --- | --- | --- |
| arg | - | value of floating-point or [Integral type](../../types/is_integral "cpp/types/is integral") |
### Return value
If no errors occur, the common (base-*10*) logarithm of `arg` (log
10(arg) or lg(arg)) is returned.
If a domain error occurs, an implementation-defined value is returned (NaN where supported).
If a pole error occurs, `[-HUGE\_VAL](huge_val "cpp/numeric/math/HUGE VAL")`, `-HUGE_VALF`, or `-HUGE_VALL` is returned.
### Error handling
Errors are reported as specified in `[math\_errhandling](math_errhandling "cpp/numeric/math/math errhandling")`.
Domain error occurs if `arg` is less than zero.
Pole error may occur if `arg` is zero.
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* If the argument is ยฑ0, -โ is returned and `[FE\_DIVBYZERO](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` is raised.
* If the argument is 1, +0 is returned
* If the argument is negative, NaN is returned and `[FE\_INVALID](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` is raised.
* If the argument is +โ, +โ is returned
* If the argument is NaN, NaN is returned
### Example
```
#include <iostream>
#include <cmath>
#include <cerrno>
#include <cstring>
#include <cfenv>
// #pragma STDC FENV_ACCESS ON
int main()
{
std::cout << "log10(1000) = " << std::log10(1000) << '\n'
<< "log10(0.001) = " << std::log10(0.001) << '\n'
<< "base-5 logarithm of 125 = " << std::log10(125)/std::log10(5) << '\n';
// special values
std::cout << "log10(1) = " << std::log10(1) << '\n'
<< "log10(+Inf) = " << std::log10(INFINITY) << '\n';
// error handling
errno = 0;
std::feclearexcept(FE_ALL_EXCEPT);
std::cout << "log10(0) = " << std::log10(0) << '\n';
if (errno == ERANGE)
std::cout << " errno == ERANGE: " << std::strerror(errno) << '\n';
if (std::fetestexcept(FE_DIVBYZERO))
std::cout << " FE_DIVBYZERO raised\n";
}
```
Possible output:
```
log10(1000) = 3
log10(0.001) = -3
base-5 logarithm of 125 = 3
log10(1) = 0
log10(+Inf) = inf
log10(0) = -inf
errno == ERANGE: Numerical result out of range
FE_DIVBYZERO raised
```
### See also
| | |
| --- | --- |
| [loglogflogl](log "cpp/numeric/math/log")
(C++11)(C++11) | computes natural (base *e*) logarithm (\({\small \ln{x} }\)ln(x)) (function) |
| [log2log2flog2l](log2 "cpp/numeric/math/log2")
(C++11)(C++11)(C++11) | base 2 logarithm of the given number (\({\small \log\_{2}{x} }\)log2(x)) (function) |
| [log1plog1pflog1pl](log1p "cpp/numeric/math/log1p")
(C++11)(C++11)(C++11) | natural logarithm (to base *e*) of 1 plus the given number (\({\small \ln{(1+x)} }\)ln(1+x)) (function) |
| [log10(std::complex)](../complex/log10 "cpp/numeric/complex/log10") | complex common logarithm with the branch cuts along the negative real axis (function template) |
| [log10(std::valarray)](../valarray/log10 "cpp/numeric/valarray/log10") | applies the function `std::log10` to each element of valarray (function template) |
| [C documentation](https://en.cppreference.com/w/c/numeric/math/log10 "c/numeric/math/log10") for `log10` |
cpp std::frexp, std::frexpf, std::frexpl std::frexp, std::frexpf, std::frexpl
====================================
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
|
```
float frexp ( float arg, int* exp );
```
| (1) | (constexpr since C++23) |
|
```
float frexpf( float arg, int* exp );
```
| (2) | (since C++11) (constexpr since C++23) |
|
```
double frexp ( double arg, int* exp );
```
| (3) | (constexpr since C++23) |
|
```
long double frexp ( long double arg, int* exp );
```
| (4) | (constexpr since C++23) |
|
```
long double frexpl( long double arg, int* exp );
```
| (5) | (since C++11) (constexpr since C++23) |
|
```
double frexp ( IntegralType arg, int* exp );
```
| (6) | (since C++11) (constexpr since C++23) |
1-5) Decomposes given floating point value `arg` into a normalized fraction and an integral power of two.
6) A set of overloads or a function template accepting an argument of any [integral type](../../types/is_integral "cpp/types/is integral"). Equivalent to (3) (the argument is cast to `double`). ### Parameters
| | | |
| --- | --- | --- |
| arg | - | floating point value |
| exp | - | pointer to integer value to store the exponent to |
### Return value
If `arg` is zero, returns zero and stores zero in `*exp`.
Otherwise (if `arg` is not zero), if no errors occur, returns the value `x` in the range `(-1;-0.5], [0.5; 1)` and stores an integer value in `*exp` such that xร2(\*exp)
== arg.
If the value to be stored in `*exp` is outside the range of `int`, the behavior is unspecified.
If `arg` is not a floating-point number, the behavior is unspecified.
### Error handling
This function is not subject to any errors specified in `[math\_errhandling](math_errhandling "cpp/numeric/math/math errhandling")`.
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* If `arg` is ยฑ0, it is returned, unmodified, and `0` is stored in `*exp`.
* If `arg` is ยฑโ, it is returned, and an unspecified value is stored in `*exp`.
* If `arg` is NaN, NaN is returned, and an unspecified value is stored in `*exp`.
* No floating-point exceptions are raised.
* If `[FLT\_RADIX](../../types/climits "cpp/types/climits")` is 2 (or a power of 2), the returned value is exact, [the current rounding mode](../fenv/fe_round "cpp/numeric/fenv/FE round") is ignored
### Notes
On a binary system (where `[FLT\_RADIX](../../types/climits "cpp/types/climits")` is `2`), `frexp` may be implemented as.
```
{
*exp = (value == 0) ? 0 : (int)(1 + std::logb(value));
return std::scalbn(value, -(*exp));
}
```
The function `std::frexp`, together with its dual, `[std::ldexp](ldexp "cpp/numeric/math/ldexp")`, can be used to manipulate the representation of a floating-point number without direct bit manipulations.
### Example
Compares different floating-point decomposition functions.
```
#include <iostream>
#include <cmath>
#include <limits>
int main()
{
double f = 123.45;
std::cout << "Given the number " << f << " or " << std::hexfloat
<< f << std::defaultfloat << " in hex,\n";
double f3;
double f2 = std::modf(f, &f3);
std::cout << "modf() makes " << f3 << " + " << f2 << '\n';
int i;
f2 = std::frexp(f, &i);
std::cout << "frexp() makes " << f2 << " * 2^" << i << '\n';
i = std::ilogb(f);
std::cout << "logb()/ilogb() make " << f/std::scalbn(1.0, i) << " * "
<< std::numeric_limits<double>::radix
<< "^" << std::ilogb(f) << '\n';
}
```
Possible output:
```
Given the number 123.45 or 0x1.edccccccccccdp+6 in hex,
modf() makes 123 + 0.45
frexp() makes 0.964453 * 2^7
logb()/ilogb() make 1.92891 * 2^6
```
### See also
| | |
| --- | --- |
| [ldexpldexpfldexpl](ldexp "cpp/numeric/math/ldexp")
(C++11)(C++11) | multiplies a number by `2` raised to a power (function) |
| [logblogbflogbl](logb "cpp/numeric/math/logb")
(C++11)(C++11)(C++11) | extracts exponent of the number (function) |
| [ilogbilogbfilogbl](ilogb "cpp/numeric/math/ilogb")
(C++11)(C++11)(C++11) | extracts exponent of the number (function) |
| [modfmodffmodfl](modf "cpp/numeric/math/modf")
(C++11)(C++11) | decomposes a number into integer and fractional parts (function) |
| [C documentation](https://en.cppreference.com/w/c/numeric/math/frexp "c/numeric/math/frexp") for `frexp` |
cpp std::nextafter, std::nextafterf, std::nextafterl, std::nexttoward, std::nexttowardf, std::nexttowardl std::nextafter, std::nextafterf, std::nextafterl, std::nexttoward, std::nexttowardf, std::nexttowardl
=====================================================================================================
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
|
```
float nextafter ( float from, float to );
```
| (1) | (since C++11) (constexpr since C++23) |
|
```
float nextafterf( float from, float to );
```
| (2) | (since C++11) (constexpr since C++23) |
|
```
double nextafter ( double from, double to );
```
| (3) | (since C++11) (constexpr since C++23) |
|
```
long double nextafter ( long double from, long double to );
```
| (4) | (since C++11) (constexpr since C++23) |
|
```
long double nextafterl( long double from, long double to );
```
| (5) | (since C++11) (constexpr since C++23) |
|
```
Promoted nextafter ( Arithmetic1 from, Arithmetic2 to );
```
| (6) | (since C++11) (constexpr since C++23) |
|
```
float nexttoward ( float from, long double to );
```
| (7) | (since C++11) (constexpr since C++23) |
|
```
float nexttowardf( float from, long double to );
```
| (8) | (since C++11) (constexpr since C++23) |
|
```
double nexttoward ( double from, long double to );
```
| (9) | (since C++11) (constexpr since C++23) |
|
```
long double nexttoward ( long double from, long double to );
```
| (10) | (since C++11) (constexpr since C++23) |
|
```
long double nexttowardl( long double from, long double to );
```
| (11) | (since C++11) (constexpr since C++23) |
|
```
double nexttoward ( IntegralType from, long double to );
```
| (12) | (since C++11) (constexpr since C++23) |
Returns the next representable value of `from` in the direction of `to`.
1-5) If `from` equals `to`, `to` is returned.
7-11) If `from` equals `to`, `to` is returned, converted from `long double` to the return type of the function without loss of range or precision.
6) A set of overloads or a function template for all combinations of arguments of arithmetic type not covered by (1-5). If any argument has [integral type](../../types/is_integral "cpp/types/is integral"), it is cast to `double`. If any argument is `long double`, then the return type `Promoted` is also `long double`, otherwise the return type is always `double`.
12) A set of overloads or a function template accepting the `from` argument of any [integral type](../../types/is_integral "cpp/types/is integral"). Equivalent to (9) (the argument is cast to `double`). ### Parameters
| | | |
| --- | --- | --- |
| from, to | - | floating point values |
### Return value
If no errors occur, the next representable value of `from` in the direction of `to`. is returned. If `from` equals `to`, then `to` is returned.
If a range error due to overflow occurs, `[ยฑHUGE\_VAL](huge_val "cpp/numeric/math/HUGE VAL")`, `ยฑHUGE_VALF`, or `ยฑHUGE_VALL` is returned (with the same sign as `from`).
If a range error occurs due to underflow, the correct result is returned.
### Error handling
Errors are reported as specified in `[math\_errhandling](math_errhandling "cpp/numeric/math/math errhandling")`.
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* if `from` is finite, but the expected result is an infinity, raises `[FE\_INEXACT](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` and `[FE\_OVERFLOW](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")`
* if `from` does not equal `to` and the result is subnormal or zero, raises `[FE\_INEXACT](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` and `[FE\_UNDERFLOW](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")`
* in any case, the returned value is independent of the current rounding mode
* if either `from` or `to` is NaN, NaN is returned
### Notes
[POSIX specifies](http://pubs.opengroup.org/onlinepubs/9699919799/functions/nextafter.html) that the overflow and the underflow conditions are range errors (`[errno](../../error/errno "cpp/error/errno")` may be set).
IEC 60559 recommends that `from` is returned whenever `from == to`. These functions return `to` instead, which makes the behavior around zero consistent: `std::nextafter(-0.0, +0.0)` returns `+0.0` and `std::nextafter(+0.0, -0.0)` returns `-0.0`.
`nextafter` is typically implemented by manipulation of IEEE representation ([glibc](https://github.com/bminor/glibc/blob/master/math/s_nextafter.c), [musl](https://github.com/ifduyue/musl/blob/master/src/math/nextafter.c)).
### Example
```
#include <cfenv>
#include <cfloat>
#include <cmath>
#include <concepts>
#include <iomanip>
#include <iostream>
int main()
{
float from1 = 0, to1 = std::nextafter(from1, 1.f);
std::cout << "The next representable float after " << std::setprecision(20) << from1
<< " is " << to1
<< std::hexfloat << " (" << to1 << ")\n" << std::defaultfloat;
float from2 = 1, to2 = std::nextafter(from2, 2.f);
std::cout << "The next representable float after " << from2 << " is " << to2
<< std::hexfloat << " (" << to2 << ")\n" << std::defaultfloat;
double from3 = std::nextafter(0.1, 0), to3 = 0.1;
std::cout << "The number 0.1 lies between two valid doubles:\n"
<< std::setprecision(56) << " " << from3
<< std::hexfloat << " (" << from3 << ')' << std::defaultfloat
<< "\nand " << to3 << std::hexfloat << " (" << to3 << ")\n"
<< std::defaultfloat << std::setprecision(20);
std::cout << "\nDifference between nextafter and nexttoward:\n";
long double dir = std::nextafter(from1, 1.0L); // first subnormal long double
float x = std::nextafter(from1, dir); // first converts dir to float, giving 0
std::cout << "With nextafter, next float after " << from1 << " is " << x << '\n';
x = std::nexttoward(from1, dir);
std::cout << "With nexttoward, next float after " << from1 << " is " << x << '\n';
std::cout << "\nSpecial values:\n";
{
// #pragma STDC FENV_ACCESS ON
std::feclearexcept(FE_ALL_EXCEPT);
double from4 = DBL_MAX, to4 = std::nextafter(from4, INFINITY);
std::cout << "The next representable double after " << std::setprecision(6)
<< from4 << std::hexfloat << " (" << from4 << ')'
<< std::defaultfloat << " is " << to4
<< std::hexfloat << " (" << to4 << ")\n" << std::defaultfloat;
if(std::fetestexcept(FE_OVERFLOW)) std::cout << " raised FE_OVERFLOW\n";
if(std::fetestexcept(FE_INEXACT)) std::cout << " raised FE_INEXACT\n";
} // end FENV_ACCESS block
float from5 = 0.0, to5 = std::nextafter(from5, -0.0);
std::cout << "std::nextafter(+0.0, -0.0) gives " << std::fixed << to5 << '\n';
auto precision_loss_demo = []<std::floating_point Fp>(const auto rem, const Fp start) {
std::cout << rem;
for (Fp from = start, to, ฮ;
(ฮ = (to = std::nextafter(from, +INFINITY)) - from) < Fp(10.0);
from *= Fp(10.0))
std::cout << "nextafter(" << std::scientific << std::setprecision(0) << from
<< ", INF) gives " << std::fixed << std::setprecision(6) << to
<< "; ฮ = " << ฮ << '\n';
};
precision_loss_demo("\nPrecision loss demo for float:\n", 10.0f);
precision_loss_demo("\nPrecision loss demo for double:\n", 10.0e9);
precision_loss_demo("\nPrecision loss demo for long double:\n", 10.0e17L);
}
```
Output:
```
The next representable float after 0 is 1.4012984643248170709e-45 (0x1p-149)
The next representable float after 1 is 1.0000001192092895508 (0x1.000002p+0)
The number 0.1 lies between two valid doubles:
0.09999999999999999167332731531132594682276248931884765625 (0x1.9999999999999p-4)
and 0.1000000000000000055511151231257827021181583404541015625 (0x1.999999999999ap-4)
Difference between nextafter and nexttoward:
With nextafter, next float after 0 is 0
With nexttoward, next float after 0 is 1.4012984643248170709e-45
Special values:
The next representable double after 1.79769e+308 (0x1.fffffffffffffp+1023) is inf (inf)
raised FE_OVERFLOW
raised FE_INEXACT
std::nextafter(+0.0, -0.0) gives -0.000000
Precision loss demo for float:
nextafter(1e+01, INF) gives 10.000001; ฮ = 0.000001
nextafter(1e+02, INF) gives 100.000008; ฮ = 0.000008
nextafter(1e+03, INF) gives 1000.000061; ฮ = 0.000061
nextafter(1e+04, INF) gives 10000.000977; ฮ = 0.000977
nextafter(1e+05, INF) gives 100000.007812; ฮ = 0.007812
nextafter(1e+06, INF) gives 1000000.062500; ฮ = 0.062500
nextafter(1e+07, INF) gives 10000001.000000; ฮ = 1.000000
nextafter(1e+08, INF) gives 100000008.000000; ฮ = 8.000000
Precision loss demo for double:
nextafter(1e+10, INF) gives 10000000000.000002; ฮ = 0.000002
nextafter(1e+11, INF) gives 100000000000.000015; ฮ = 0.000015
nextafter(1e+12, INF) gives 1000000000000.000122; ฮ = 0.000122
nextafter(1e+13, INF) gives 10000000000000.001953; ฮ = 0.001953
nextafter(1e+14, INF) gives 100000000000000.015625; ฮ = 0.015625
nextafter(1e+15, INF) gives 1000000000000000.125000; ฮ = 0.125000
nextafter(1e+16, INF) gives 10000000000000002.000000; ฮ = 2.000000
Precision loss demo for long double:
nextafter(1e+18, INF) gives 1000000000000000000.062500; ฮ = 0.062500
nextafter(1e+19, INF) gives 10000000000000000001.000000; ฮ = 1.000000
nextafter(1e+20, INF) gives 100000000000000000008.000000; ฮ = 8.000000
```
### See also
| |
| --- |
| [C documentation](https://en.cppreference.com/w/c/numeric/math/nextafter "c/numeric/math/nextafter") for `nextafter` |
| programming_docs |
cpp std::copysign, std::copysignf, std::copysignl std::copysign, std::copysignf, std::copysignl
=============================================
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
|
```
float copysign ( float mag, float sgn );
```
| (1) | (since C++11) (constexpr since C++23) |
|
```
float copysignf( float mag, float sgn );
```
| (2) | (since C++11) (constexpr since C++23) |
|
```
double copysign ( double mag, double sgn );
```
| (3) | (since C++11) (constexpr since C++23) |
|
```
long double copysign ( long double mag, long double sgn );
```
| (4) | (since C++11) (constexpr since C++23) |
|
```
long double copysignl( long double mag, long double sgn );
```
| (5) | (since C++11) (constexpr since C++23) |
|
```
Promoted copysign ( Arithmetic1 mag, Arithmetic2 sgn );
```
| (6) | (since C++11) (constexpr since C++23) |
1-5) Composes a floating point value with the magnitude of `mag` and the sign of `sgn`.
6) A set of overloads or a function template for all combinations of arguments of arithmetic type not covered by (1-5). If any argument has [integral type](../../types/is_integral "cpp/types/is integral"), it is cast to `double`. If any argument is `long double`, then the return type `Promoted` is also `long double`, otherwise the return type is always `double`. ### Parameters
| | | |
| --- | --- | --- |
| mag, sgn | - | floating point values |
### Return value
If no errors occur, the floating point value with the magnitude of `mag` and the sign of `sgn` is returned.
If `mag` is NaN, then NaN with the sign of `sgn` is returned.
If `sgn` is -0, the result is only negative if the implementation supports the signed zero consistently in arithmetic operations.
### Error handling
This function is not subject to any errors specified in `[math\_errhandling](math_errhandling "cpp/numeric/math/math errhandling")`.
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* The returned value is exact (`[FE\_INEXACT](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` is never raised) and independent of the current [rounding mode](../fenv/fe_round "cpp/numeric/fenv/FE round").
### Notes
`std::copysign` is the only portable way to manipulate the sign of a NaN value (to examine the sign of a NaN, `signbit` may also be used).
### Example
```
#include <iostream>
#include <cmath>
int main(void)
{
std::cout << std::showpos
<< "copysign(1.0,+2.0) = " << std::copysign(1.0,+2.0) << '\n'
<< "copysign(1.0,-2.0) = " << std::copysign(1.0,-2.0) << '\n'
<< "copysign(inf,-2.0) = " << std::copysign(INFINITY,-2.0) << '\n'
<< "copysign(NaN,-2.0) = " << std::copysign(NAN,-2.0) << '\n';
}
```
Output:
```
copysign(1.0,+2.0) = +1
copysign(1.0,-2.0) = -1
copysign(inf,-2.0) = -inf
copysign(NaN,-2.0) = -nan
```
### See also
| | |
| --- | --- |
| [abs(float)fabsfabsffabsl](fabs "cpp/numeric/math/fabs")
(C++11)(C++11) | absolute value of a floating point value (\(\small{|x|}\)|x|) (function) |
| [signbit](signbit "cpp/numeric/math/signbit")
(C++11) | checks if the given number is negative (function) |
| [C documentation](https://en.cppreference.com/w/c/numeric/math/copysign "c/numeric/math/copysign") for `copysign` |
cpp std::nan, std::nanf, std::nanl std::nan, std::nanf, std::nanl
==============================
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
|
```
float nanf( const char* arg );
```
| (1) | (since C++11) |
|
```
double nan( const char* arg );
```
| (2) | (since C++11) |
|
```
long double nanl( const char* arg );
```
| (3) | (since C++11) |
Converts the character string `arg` into the corresponding quiet NaN value, as if by calling `[std::strtof](../../string/byte/strtof "cpp/string/byte/strtof")`, `[std::strtod](../../string/byte/strtof "cpp/string/byte/strtof")`, or `[std::strtold](../../string/byte/strtof "cpp/string/byte/strtof")`, respectively.
1) The call `std::nanf("n-char-sequence")`, where n-char-sequence is a sequence of digits, ASCII letters, and underscores, is equivalent to the call `[std::strtof](http://en.cppreference.com/w/cpp/string/byte/strtof)("NAN(n-char-sequence)", (char\*\*)nullptr);`.
The call `std::nanf("")` is equivalent to the call `[std::strtof](http://en.cppreference.com/w/cpp/string/byte/strtof)("NAN()", (char\*\*)nullptr);`.
The call `std::nanf("string")`, where `string` is neither an n-char-sequence nor an empty string, is equivalent to the call `[std::strtof](http://en.cppreference.com/w/cpp/string/byte/strtof)("NAN", (char\*\*)nullptr);`.
2) Same as (1), but calls `[std::strtod](http://en.cppreference.com/w/cpp/string/byte/strtof)` instead of `[std::strtof](http://en.cppreference.com/w/cpp/string/byte/strtof)`.
3) Same as (1), but calls `[std::strtold](http://en.cppreference.com/w/cpp/string/byte/strtof)` instead of `[std::strtof](http://en.cppreference.com/w/cpp/string/byte/strtof)`. ### Parameters
| | | |
| --- | --- | --- |
| arg | - | narrow character string identifying the contents of a NaN |
### Return value
The quiet NaN value that corresponds to the identifying string `arg` or zero if the implementation does not support quiet NaNs.
If the implementation supports IEEE floating-point arithmetic (IEC 60559), it also supports quiet NaNs.
### Error handling
This function is not subject to any of the error conditions specified in [`math_errhandling`](math_errhandling "cpp/numeric/math/math errhandling").
### Example
```
#include <iostream>
#include <cmath>
#include <cstdint>
#include <cstring>
int main()
{
double f1 = std::nan("1");
std::uint64_t f1n; std::memcpy(&f1n, &f1, sizeof f1);
std::cout << "nan(\"1\") = " << f1 << " (" << std::hex << f1n << ")\n";
double f2 = std::nan("2");
std::uint64_t f2n; std::memcpy(&f2n, &f2, sizeof f2);
std::cout << "nan(\"2\") = " << f2 << " (" << std::hex << f2n << ")\n";
}
```
Possible output:
```
nan("1") = nan (7ff0000000000001)
nan("2") = nan (7ff0000000000002)
```
### See also
| | |
| --- | --- |
| [isnan](isnan "cpp/numeric/math/isnan")
(C++11) | checks if the given number is NaN (function) |
| [NAN](nan "cpp/numeric/math/NAN")
(C++11) | evaluates to a quiet NaN of type `float` (macro constant) |
| [has\_quiet\_NaN](../../types/numeric_limits/has_quiet_nan "cpp/types/numeric limits/has quiet NaN")
[static] | identifies floating-point types that can represent the special value "quiet not-a-number" (NaN) (public static member constant of `std::numeric_limits<T>`) |
| [has\_signaling\_NaN](../../types/numeric_limits/has_signaling_nan "cpp/types/numeric limits/has signaling NaN")
[static] | identifies floating-point types that can represent the special value "signaling not-a-number" (NaN) (public static member constant of `std::numeric_limits<T>`) |
| [quiet\_NaN](../../types/numeric_limits/quiet_nan "cpp/types/numeric limits/quiet NaN")
[static] | returns a quiet NaN value of the given floating-point type (public static member function of `std::numeric_limits<T>`) |
| [signaling\_NaN](../../types/numeric_limits/signaling_nan "cpp/types/numeric limits/signaling NaN")
[static] | returns a signaling NaN value of the given floating-point type (public static member function of `std::numeric_limits<T>`) |
| [C documentation](https://en.cppreference.com/w/c/numeric/math/nan "c/numeric/math/nan") for `nanf, nan, nanl` |
cpp std::islessequal std::islessequal
================
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
|
```
bool islessequal( float x, float y );
```
| (1) | (since C++11) (constexpr since C++23) |
|
```
bool islessequal( double x, double y );
```
| (2) | (since C++11) (constexpr since C++23) |
|
```
bool islessequal( long double x, long double y );
```
| (3) | (since C++11) (constexpr since C++23) |
|
```
bool islessequal( Arithmetic x, Arithmetic y );
```
| (4) | (since C++11) (constexpr since C++23) |
1-3) Determines if the floating point number `x` is less than or equal to the floating-point number `y`, without setting floating-point exceptions.
4) A set of overloads or a function template for all combinations of arguments of arithmetic type not covered by (1-3). If any argument has [integral type](../../types/is_integral "cpp/types/is integral"), it is cast to `double`. ### Parameters
| | | |
| --- | --- | --- |
| x | - | floating point value |
| y | - | floating point value |
### Return value
`true` if `x <= y`, `false` otherwise.
### Notes
The built-in `operator<=` for floating-point numbers may raise `[FE\_INVALID](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` if one or both of the arguments is NaN. This function is a "quiet" version of `operator<=`.
### See also
| | |
| --- | --- |
| [less\_equal](../../utility/functional/less_equal "cpp/utility/functional/less equal") | function object implementing `x <= y` (class template) |
| [isgreaterequal](isgreaterequal "cpp/numeric/math/isgreaterequal")
(C++11) | checks if the first floating-point argument is greater or equal than the second (function) |
| [C documentation](https://en.cppreference.com/w/c/numeric/math/islessequal "c/numeric/math/islessequal") for `islessequal` |
cpp std::islessgreater std::islessgreater
==================
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
|
```
bool islessgreater( float x, float y );
```
| (1) | (since C++11) (constexpr since C++23) |
|
```
bool islessgreater( double x, double y );
```
| (2) | (since C++11) (constexpr since C++23) |
|
```
bool islessgreater( long double x, long double y );
```
| (3) | (since C++11) (constexpr since C++23) |
|
```
bool islessgreater( Arithmetic x, Arithmetic y );
```
| (4) | (since C++11) (constexpr since C++23) |
1-3) Determines if the floating point number `x` is less than or greater than the floating-point number `y`, without setting floating-point exceptions.
4) A set of overloads or a function template for all combinations of arguments of arithmetic type not covered by (1-3). If any argument has [integral type](../../types/is_integral "cpp/types/is integral"), it is cast to `double`. ### Parameters
| | | |
| --- | --- | --- |
| x | - | floating point value |
| y | - | floating point value |
### Return value
`true` if `x < y || x > y`, `false` otherwise.
### Notes
The built-in `operator<` and `operator>` for floating-point numbers may raise `[FE\_INVALID](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` if one or both of the arguments is NaN. This function is a "quiet" version of the expression `x < y || x > y`.
### See also
| | |
| --- | --- |
| [isless](isless "cpp/numeric/math/isless")
(C++11) | checks if the first floating-point argument is less than the second (function) |
| [isgreater](isgreater "cpp/numeric/math/isgreater")
(C++11) | checks if the first floating-point argument is greater than the second (function) |
| [C documentation](https://en.cppreference.com/w/c/numeric/math/islessgreater "c/numeric/math/islessgreater") for `islessgreater` |
cpp std::atan2, std::atan2f, std::atan2l std::atan2, std::atan2f, std::atan2l
====================================
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
| | (1) | |
|
```
float atan2 ( float y, float x );
```
| |
|
```
float atan2f( float y, float x );
```
| (since C++11) |
|
```
double atan2 ( double y, double x );
```
| (2) | |
| | (3) | |
|
```
long double atan2 ( long double y, long double x );
```
| |
|
```
long double atan2l( long double y, long double x );
```
| (since C++11) |
|
```
Promoted atan2 ( Arithmetic1 y, Arithmetic2 x );
```
| (4) | (since C++11) |
1-3) Computes the arc tangent of `y/x` using the signs of arguments to determine the correct quadrant.
4) A set of overloads or a function template for all combinations of arguments of arithmetic type not covered by 1-3). If any argument has [integral type](../../types/is_integral "cpp/types/is integral"), it is cast to `double`. If any argument is `long double`, then the return type `Promoted` is also `long double`, otherwise the return type is always `double`. ### Parameters
| | | |
| --- | --- | --- |
| y, x | - | values of floating-point or [integral types](../../types/is_integral "cpp/types/is integral") |
### Return value
If no errors occur, the arc tangent of `y/x` (arctan(y/x)) in the range [-ฯ , +ฯ] radians, is returned. Y argument Return value [![math-atan2.png]()](https://en.cppreference.com/w/File:math-atan2.png) X argument If a domain error occurs, an implementation-defined value is returned (NaN where supported).
If a range error occurs due to underflow, the correct result (after rounding) is returned.
### Error handling
Errors are reported as specified in `[math\_errhandling](math_errhandling "cpp/numeric/math/math errhandling")`.
Domain error may occur if `x` and `y` are both zero.
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* If `x` and `y` are both zero, domain error *does not* occur
* If `x` and `y` are both zero, range error does not occur either
* If `y` is zero, pole error does not occur
* If `y` is `ยฑ0` and `x` is negative or `-0`, `ยฑฯ` is returned
* If `y` is `ยฑ0` and `x` is positive or `+0`, `ยฑ0` is returned
* If `y` is `ยฑโ` and `x` is finite, `ยฑฯ/2` is returned
* If `y` is `ยฑโ` and `x` is `-โ`, `ยฑ3ฯ/4` is returned
* If `y` is `ยฑโ` and `x` is `+โ`, `ยฑฯ/4` is returned
* If `x` is `ยฑ0` and `y` is negative, `-ฯ/2` is returned
* If `x` is `ยฑ0` and `y` is positive, `+ฯ/2` is returned
* If `x` is `-โ` and `y` is finite and positive, `+ฯ` is returned
* If `x` is `-โ` and `y` is finite and negative, `-ฯ` is returned
* If `x` is `+โ` and `y` is finite and positive, `+0` is returned
* If `x` is `+โ` and `y` is finite and negative, `-0` is returned
* If either `x` is NaN or `y` is NaN, NaN is returned
### Notes
`std::atan2(y, x)` is equivalent to `[std::arg](http://en.cppreference.com/w/cpp/numeric/complex/arg)([std::complex](http://en.cppreference.com/w/cpp/numeric/complex)<double>(x,y))`.
[POSIX specifies](http://pubs.opengroup.org/onlinepubs/9699919799/functions/atan2.html) that in case of underflow, `y/x` is the value returned, and if that is not supported, an implementation-defined value no greater than DBL\_MIN, FLT\_MIN, and LDBL\_MIN is returned.
### Example
```
#include <iostream>
#include <cmath>
int main()
{
// normal usage: the signs of the two arguments determine the quadrant
std::cout << "(x:+1,y:+1) cartesian is (r:" << hypot(1,1)
<< ",phi:" << atan2(1,1) << ") polar\n" // atan2(1,1) = +pi/4, Quad I
<< "(x:-1,y:+1) cartesian is (r:" << hypot(1,-1)
<< ",phi:" << atan2(1,-1) << ") polar\n" // atan2(1, -1) = +3pi/4, Quad II
<< "(x:-1,y:-1) cartesian is (r:" << hypot(-1,-1)
<< ",phi:" << atan2(-1,-1) << ") polar\n" // atan2(-1,-1) = -3pi/4, Quad III
<< "(x:+1,y:-1) cartesian is (r:" << hypot(-1,1)
<< ",phi:" << atan2(-1,1) << ") polar\n"; // atan2(-1, 1) = -pi/4, Quad IV
// special values
std::cout << "atan2(0, 0) = " << atan2(0,0)
<< " atan2(0,-0) = " << atan2(0,-0.0) << '\n'
<< "atan2(7, 0) = " << atan2(7,0)
<< " atan2(7,-0) = " << atan2(7,-0.0) << '\n';
}
```
Output:
```
(x:+1,y:+1) cartesian is (r:1.41421,phi:0.785398) polar
(x:-1,y:+1) cartesian is (r:1.41421,phi:2.35619) polar
(x:-1,y:-1) cartesian is (r:1.41421,phi:-2.35619) polar
(x:+1,y:-1) cartesian is (r:1.41421,phi:-0.785398) polar
atan2(0, 0) = 0 atan2(0,-0) = 3.14159
atan2(7, 0) = 1.5708 atan2(7,-0) = 1.5708
```
### See also
| | |
| --- | --- |
| [asinasinfasinl](asin "cpp/numeric/math/asin")
(C++11)(C++11) | computes arc sine (\({\small\arcsin{x} }\)arcsin(x)) (function) |
| [acosacosfacosl](acos "cpp/numeric/math/acos")
(C++11)(C++11) | computes arc cosine (\({\small\arccos{x} }\)arccos(x)) (function) |
| [atanatanfatanl](atan "cpp/numeric/math/atan")
(C++11)(C++11) | computes arc tangent (\({\small\arctan{x} }\)arctan(x)) (function) |
| [arg](../complex/arg "cpp/numeric/complex/arg") | returns the phase angle (function template) |
| [atan2(std::valarray)](../valarray/atan2 "cpp/numeric/valarray/atan2") | applies the function `std::atan2` to a valarray and a value (function template) |
| [C documentation](https://en.cppreference.com/w/c/numeric/math/atan2 "c/numeric/math/atan2") for `atan2` |
cpp std::abs(float), std::fabs, std::fabsf, std::fabsl std::abs(float), std::fabs, std::fabsf, std::fabsl
==================================================
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
| Defined in header `[<cstdlib>](../../header/cstdlib "cpp/header/cstdlib")` | | |
|
```
float abs( float arg );
```
| (1) | (constexpr since C++23) |
|
```
double abs( double arg );
```
| (2) | (constexpr since C++23) |
|
```
long double abs( long double arg );
```
| (3) | (constexpr since C++23) |
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
|
```
float fabs ( float arg );
```
| (4) | (constexpr since C++23) |
|
```
float fabsf( float arg );
```
| (5) | (since C++11) (constexpr since C++23) |
|
```
double fabs ( double arg );
```
| (6) | (constexpr since C++23) |
|
```
long double fabs ( long double arg );
```
| (7) | (constexpr since C++23) |
|
```
long double fabsl( long double arg );
```
| (8) | (since C++11) (constexpr since C++23) |
|
```
double fabs ( IntegralType arg );
```
| (9) | (since C++11) (constexpr since C++23) |
1-8) Computes the absolute value of a floating point value `arg`.
9) A set of overloads or a function template accepting an argument of any [integral type](../../types/is_integral "cpp/types/is integral"). Equivalent to (6) (the argument is cast to `double`). For integral arguments, [the integral overloads of `std::abs`](abs "cpp/numeric/math/abs") are likely better matches. If `std::abs` is called with an unsigned integral argument that cannot be converted to `int` by [integral promotion](../../language/implicit_conversion#Integral_promotion "cpp/language/implicit conversion"), the program is ill-formed.
### Parameters
| | | |
| --- | --- | --- |
| arg | - | Value of a floating-point or [integral type](../../types/is_integral "cpp/types/is integral") |
### Return value
If successful, returns the absolute value of `arg` (`|arg|`). The value returned is exact and does not depend on any rounding modes.
### Error handling
This function is not subject to any of the error conditions specified in `[math\_errhandling](math_errhandling "cpp/numeric/math/math errhandling")`.
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* If the argument is ยฑ0, +0 is returned
* If the argument is ยฑโ, +โ is returned
* If the argument is NaN, NaN is returned
### Example
```
#include <iostream>
#include <cmath>
int main()
{
std::cout << "abs(+3.0) = " << std::abs(+3.0) << '\n'
<< "abs(-3.0) = " << std::abs(-3.0) << '\n';
// special values
std::cout << "abs(-0.0) = " << std::abs(-0.0) << '\n'
<< "abs(-Inf) = " << std::abs(-INFINITY) << '\n'
<< "abs(-NaN) = " << std::abs(-NAN) << '\n';
}
```
Possible output:
```
abs(+3.0) = 3
abs(-3.0) = 3
abs(-0.0) = 0
abs(-Inf) = inf
abs(-NaN) = nan
```
### 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 2192](https://cplusplus.github.io/LWG/issue2192) | C++98 | overloads of `std::abs` were inconsistentlydeclared in two headers | declared these overloads in both headers |
| [LWG 2735](https://cplusplus.github.io/LWG/issue2735) | C++11 | overloads of `std::abs` for integer typesreturning `double` was erroneously required | removed the requirement |
### See also
| | |
| --- | --- |
| [abs(int)labsllabs](abs "cpp/numeric/math/abs")
(C++11) | computes absolute value of an integral value (\(\small{|x|}\)|x|) (function) |
| [copysigncopysignfcopysignl](copysign "cpp/numeric/math/copysign")
(C++11)(C++11)(C++11) | copies the sign of a floating point value (function) |
| [signbit](signbit "cpp/numeric/math/signbit")
(C++11) | checks if the given number is negative (function) |
| [abs(std::complex)](../complex/abs "cpp/numeric/complex/abs") | returns the magnitude of a complex number (function template) |
| [abs(std::valarray)](../valarray/abs "cpp/numeric/valarray/abs") | applies the function `abs` to each element of valarray (function template) |
| [C documentation](https://en.cppreference.com/w/c/numeric/math/fabs "c/numeric/math/fabs") for `fabs` |
| programming_docs |
cpp std::acos, std::acosf, std::acosl std::acos, std::acosf, std::acosl
=================================
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
| | (1) | |
|
```
float acos ( float arg );
```
| |
|
```
float acosf( float arg );
```
| (since C++11) |
|
```
double acos ( double arg );
```
| (2) | |
| | (3) | |
|
```
long double acos ( long double arg );
```
| |
|
```
long double acosl( long double arg );
```
| (since C++11) |
|
```
double acos ( IntegralType arg );
```
| (4) | (since C++11) |
1-3) Computes the principal value of the arc cosine of `arg`.
4) A set of overloads or a function template accepting an argument of any [integral type](../../types/is_integral "cpp/types/is integral"). Equivalent to 2) (the argument is cast to `double`). ### Parameters
| | | |
| --- | --- | --- |
| arg | - | value of a floating-point or [Integral type](../../types/is_integral "cpp/types/is integral") |
### Return value
If no errors occur, the arc cosine of `arg` (arccos(arg)) in the range [0 , ฯ], is returned.
If a domain error occurs, an implementation-defined value is returned (NaN where supported).
If a range error occurs due to underflow, the correct result (after rounding) is returned.
### Error handling
Errors are reported as specified in `[math\_errhandling](math_errhandling "cpp/numeric/math/math errhandling")`.
Domain error occurs if `arg` is outside the range `[-1.0, 1.0]`
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* If the argument is +1, the value `+0` is returned.
* If |arg| > 1, a domain error occurs and NaN is returned.
* if the argument is NaN, NaN is returned
### Example
```
#include <cmath>
#include <iostream>
#include <cerrno>
#include <cfenv>
#include <cstring>
#pragma STDC FENV_ACCESS ON
int main()
{
std::cout << "acos(-1) = " << acos(-1) << '\n'
<< "acos(0.0) = " << acos(0.0) << " 2*acos(0.0) = " << 2*acos(0) << '\n'
<< "acos(0.5) = " << acos(0.5) << " 3*acos(0.5) = " << 3*acos(0.5) << '\n'
<< "acos(1) = " << acos(1) << '\n';
// error handling
errno = 0;
std::feclearexcept(FE_ALL_EXCEPT);
std::cout << "acos(1.1) = " << acos(1.1) << '\n';
if (errno == EDOM)
std::cout << " errno == EDOM: " << std::strerror(errno) << '\n';
if (std::fetestexcept(FE_INVALID))
std::cout << " FE_INVALID raised" << '\n';
}
```
Output:
```
acos(-1) = 3.14159
acos(0.0) = 1.5708 2*acos(0.0) = 3.14159
acos(0.5) = 1.0472 3*acos(0.5) = 3.14159
acos(1) = 0
acos(1.1) = nan
errno == EDOM: Numerical argument out of domain
FE_INVALID raised
```
### See also
| | |
| --- | --- |
| [asinasinfasinl](asin "cpp/numeric/math/asin")
(C++11)(C++11) | computes arc sine (\({\small\arcsin{x} }\)arcsin(x)) (function) |
| [atanatanfatanl](atan "cpp/numeric/math/atan")
(C++11)(C++11) | computes arc tangent (\({\small\arctan{x} }\)arctan(x)) (function) |
| [atan2atan2fatan2l](atan2 "cpp/numeric/math/atan2")
(C++11)(C++11) | arc tangent, using signs to determine quadrants (function) |
| [coscosfcosl](cos "cpp/numeric/math/cos")
(C++11)(C++11) | computes cosine (\({\small\cos{x} }\)cos(x)) (function) |
| [acos(std::complex)](../complex/acos "cpp/numeric/complex/acos")
(C++11) | computes arc cosine of a complex number (\({\small\arccos{z} }\)arccos(z)) (function template) |
| [acos(std::valarray)](../valarray/acos "cpp/numeric/valarray/acos") | applies the function `std::acos` to each element of valarray (function template) |
| [C documentation](https://en.cppreference.com/w/c/numeric/math/acos "c/numeric/math/acos") for `acos` |
cpp std::floor, std::floorf, std::floorl std::floor, std::floorf, std::floorl
====================================
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
|
```
float floor ( float arg );
```
| (1) | (constexpr since C++23) |
|
```
float floorf( float arg );
```
| (2) | (since C++11) (constexpr since C++23) |
|
```
double floor ( double arg );
```
| (3) | (constexpr since C++23) |
|
```
long double floor ( long double arg );
```
| (4) | (constexpr since C++23) |
|
```
long double floorl( long double arg );
```
| (5) | (since C++11) (constexpr since C++23) |
|
```
double floor ( IntegralType arg );
```
| (6) | (since C++11) (constexpr since C++23) |
1-5) Computes the largest integer value not greater than `arg`.
6) A set of overloads or a function template accepting an argument of any [integral type](../../types/is_integral "cpp/types/is integral"). Equivalent to (3) (the argument is cast to `double`). ### Parameters
| | | |
| --- | --- | --- |
| arg | - | floating point value |
### Return value
If no errors occur, the largest integer value not greater than `arg`, that is โargโ, is returned.
Return value ![math-floor.svg]() Argument ### Error handling
Errors are reported as specified in `[math\_errhandling](math_errhandling "cpp/numeric/math/math errhandling")`.
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* The current [rounding mode](../fenv/fe_round "cpp/numeric/fenv/FE round") has no effect.
* If `arg` is ยฑโ, it is returned, unmodified
* If `arg` is ยฑ0, it is returned, unmodified
* If arg is NaN, NaN is returned
### Notes
`[FE\_INEXACT](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` may be (but isn't required to be) raised when rounding a non-integer finite value.
The largest representable floating-point values are exact integers in all standard floating-point formats, so this function never overflows on its own; however the result may overflow any integer type (including `[std::intmax\_t](../../types/integer "cpp/types/integer")`), when stored in an integer variable.
### Example
```
#include <cmath>
#include <iostream>
int main()
{
std::cout << std::fixed
<< "floor(+2.7) = " << std::floor(+2.7) << '\n'
<< "floor(-2.7) = " << std::floor(-2.7) << '\n'
<< "floor(-0.0) = " << std::floor(-0.0) << '\n'
<< "floor(-Inf) = " << std::floor(-INFINITY) << '\n';
}
```
Output:
```
floor(+2.7) = 2.000000
floor(-2.7) = -3.000000
floor(-0.0) = -0.000000
floor(-Inf) = -inf
```
### See also
| | |
| --- | --- |
| [ceilceilfceill](ceil "cpp/numeric/math/ceil")
(C++11)(C++11) | nearest integer not less than the given value (function) |
| [trunctruncftruncl](trunc "cpp/numeric/math/trunc")
(C++11)(C++11)(C++11) | nearest integer not greater in magnitude than the given value (function) |
| [roundroundfroundllroundlroundflroundlllroundllroundfllroundl](round "cpp/numeric/math/round")
(C++11)(C++11)(C++11)(C++11)(C++11)(C++11)(C++11)(C++11)(C++11) | nearest integer, rounding away from zero in halfway cases (function) |
| [C documentation](https://en.cppreference.com/w/c/numeric/math/floor "c/numeric/math/floor") for `floor` |
cpp std::erfc, std::erfcf, std::erfcl std::erfc, std::erfcf, std::erfcl
=================================
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
|
```
float erfc ( float arg );
float erfcf( float arg );
```
| (1) | (since C++11) |
|
```
double erfc ( double arg );
```
| (2) | (since C++11) |
|
```
long double erfc ( long double arg );
long double erfcl( long double arg );
```
| (3) | (since C++11) |
|
```
double erfc ( IntegralType arg );
```
| (4) | (since C++11) |
1-3) Computes the [complementary error function](https://en.wikipedia.org/wiki/Complementary_error_function "enwiki:Complementary error function") of `arg`, that is `1.0-erf(arg)`, but without loss of precision for large `arg`
4) A set of overloads or a function template accepting an argument of any [integral type](../../types/is_integral "cpp/types/is integral"). Equivalent to (2) (the argument is cast to `double`). ### Parameters
| | | |
| --- | --- | --- |
| arg | - | value of a floating-point or [integral type](../../types/is_integral "cpp/types/is integral") |
### Return value
If no errors occur, value of the complementary error function of `arg`, that is \(\frac{2}{\sqrt{\pi} }\int\_{arg}^{\infty}{e^{-{t^2} }\mathsf{d}t}\)2/โฯโซโ
arg*e*-t2d*t* or \({\small 1-\operatorname{erf}(arg)}\)1-erf(arg), is returned. If a range error occurs due to underflow, the correct result (after rounding) is returned.
### Error handling
Errors are reported as specified in `[math\_errhandling](math_errhandling "cpp/numeric/math/math errhandling")`.
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* If the argument is +โ, +0 is returned
* If the argument is -โ, 2 is returned
* If the argument is NaN, NaN is returned
### Notes
For the IEEE-compatible type `double`, underflow is guaranteed if `arg` > 26.55.
### Example
```
#include <iostream>
#include <cmath>
#include <iomanip>
double normalCDF(double x) // Phi(-โ, x) aka N(x)
{
return std::erfc(-x/std::sqrt(2))/2;
}
int main()
{
std::cout << "normal cumulative distribution function:\n"
<< std::fixed << std::setprecision(2);
for(double n=0; n<1; n+=0.1)
std::cout << "normalCDF(" << n << ") " << 100*normalCDF(n) << "%\n";
std::cout << "special values:\n"
<< "erfc(-Inf) = " << std::erfc(-INFINITY) << '\n'
<< "erfc(Inf) = " << std::erfc(INFINITY) << '\n';
}
```
Output:
```
normal cumulative distribution function:
normalCDF(0.00) 50.00%
normalCDF(0.10) 53.98%
normalCDF(0.20) 57.93%
normalCDF(0.30) 61.79%
normalCDF(0.40) 65.54%
normalCDF(0.50) 69.15%
normalCDF(0.60) 72.57%
normalCDF(0.70) 75.80%
normalCDF(0.80) 78.81%
normalCDF(0.90) 81.59%
normalCDF(1.00) 84.13%
special values:
erfc(-Inf) = 2.00
erfc(Inf) = 0.00
```
### See also
| | |
| --- | --- |
| [erferfferfl](erf "cpp/numeric/math/erf")
(C++11)(C++11)(C++11) | error function (function) |
| [C documentation](https://en.cppreference.com/w/c/numeric/math/erfc "c/numeric/math/erfc") for `erfc` |
### External links
[Weisstein, Eric W. "Erfc."](http://mathworld.wolfram.com/Erfc.html) From MathWorld--A Wolfram Web Resource.
cpp std::fmin, std::fminf, std::fminl std::fmin, std::fminf, std::fminl
=================================
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
|
```
float fmin ( float x, float y );
```
| (1) | (since C++11) (constexpr since C++23) |
|
```
float fminf( float x, float y );
```
| (2) | (since C++11) (constexpr since C++23) |
|
```
double fmin ( double x, double y );
```
| (3) | (since C++11) (constexpr since C++23) |
|
```
long double fmin ( long double x, long double y );
```
| (4) | (since C++11) (constexpr since C++23) |
|
```
long double fminl( long double x, long double y );
```
| (5) | (since C++11) (constexpr since C++23) |
|
```
Promoted fmin ( Arithmetic1 x, Arithmetic2 y );
```
| (6) | (since C++11) (constexpr since C++23) |
1-5) Returns the smaller of two floating point arguments, treating NaNs as missing data (between a NaN and a numeric value, the numeric value is chosen).
6) A set of overloads or a function template for all combinations of arguments of [arithmetic type](../../types/is_arithmetic "cpp/types/is arithmetic") not covered by (1-5). If any argument has [integral type](../../types/is_integral "cpp/types/is integral"), it is cast to `double`. If any other argument is `long double`, then the return type is `long double`, otherwise it is `double`. ### Parameters
| | | |
| --- | --- | --- |
| x, y | - | values of floating-point or [integral types](../../types/is_integral "cpp/types/is integral") |
### Return value
If successful, returns the smaller of two floating point values. The value returned is exact and does not depend on any rounding modes.
### Error handling
This function is not subject to any of the error conditions specified in `[math\_errhandling](math_errhandling "cpp/numeric/math/math errhandling")`.
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* If one of the two arguments is NaN, the value of the other argument is returned
* Only if both arguments are NaN, NaN is returned
### Notes
This function is not required to be sensitive to the sign of zero, although some implementations additionally enforce that if one argument is `+0` and the other is `-0`, then `-0` is returned.
### Example
```
#include <iostream>
#include <cmath>
int main()
{
std::cout << "fmin(2,1) = " << std::fmin(2,1) << '\n'
<< "fmin(-Inf,0) = " << std::fmin(-INFINITY,0) << '\n'
<< "fmin(NaN,-1) = " << std::fmin(NAN,-1) << '\n';
}
```
Possible output:
```
fmin(2,1) = 1
fmin(-Inf,0) = -inf
fmin(NaN,-1) = -1
```
### See also
| | |
| --- | --- |
| [isless](isless "cpp/numeric/math/isless")
(C++11) | checks if the first floating-point argument is less than the second (function) |
| [fmaxfmaxffmaxl](fmax "cpp/numeric/math/fmax")
(C++11)(C++11)(C++11) | larger of two floating-point values (function) |
| [min](../../algorithm/min "cpp/algorithm/min") | returns the smaller of the given values (function template) |
| [min\_element](../../algorithm/min_element "cpp/algorithm/min element") | returns the smallest element in a range (function template) |
| [minmax](../../algorithm/minmax "cpp/algorithm/minmax")
(C++11) | returns the smaller and larger of two elements (function template) |
| [minmax\_element](../../algorithm/minmax_element "cpp/algorithm/minmax element")
(C++11) | returns the smallest and the largest elements in a range (function template) |
| [C documentation](https://en.cppreference.com/w/c/numeric/math/fmin "c/numeric/math/fmin") for `fmin` |
cpp std::fdim, std::fdimf, std::fdiml std::fdim, std::fdimf, std::fdiml
=================================
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
|
```
float fdim ( float x, float y );
```
| (1) | (since C++11) (constexpr since C++23) |
|
```
float fdimf( float x, float y );
```
| (2) | (since C++11) (constexpr since C++23) |
|
```
double fdim ( double x, double y );
```
| (3) | (since C++11) (constexpr since C++23) |
|
```
long double fdim ( long double x, long double y );
```
| (4) | (since C++11) (constexpr since C++23) |
|
```
long double fdiml( long double x, long double y );
```
| (5) | (since C++11) (constexpr since C++23) |
|
```
Promoted fdim ( Arithmetic1 x, Arithmetic2 y );
```
| (6) | (since C++11) (constexpr since C++23) |
1-5) Returns the positive difference between `x` and `y`, that is, if `x>y`, returns `x-y`, otherwise (if `xโคy`), returns `+0`.
6) A set of overloads or a function template for all combinations of arguments of [arithmetic type](../../types/is_arithmetic "cpp/types/is arithmetic") not covered by (1-5). If any argument has [integral type](../../types/is_integral "cpp/types/is integral"), it is cast to `double`. If any argument is `long double`, then the return type `Promoted` is also `long double`, otherwise the return type is always `double`. ### Parameters
| | | |
| --- | --- | --- |
| x, y | - | values of floating-point or [integral types](../../types/is_integral "cpp/types/is integral") |
### Return value
If successful, returns the positive difference between x and y.
If a range error due to overflow occurs, `[+HUGE\_VAL](huge_val "cpp/numeric/math/HUGE VAL")`, `+HUGE_VALF`, or `+HUGE_VALL` is returned.
If a range error due to underflow occurs, the correct value (after rounding) is returned.
### Error handling
Errors are reported as specified in `[math\_errhandling](math_errhandling "cpp/numeric/math/math errhandling")`.
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* If either argument is NaN, NaN is returned
### Notes
Equivalent to `[std::fmax](http://en.cppreference.com/w/cpp/numeric/math/fmax)(x-y, 0)`, except for the NaN handling requirements.
### Example
```
#include <iostream>
#include <cmath>
#include <cerrno>
#include <cstring>
#include <cfenv>
#ifndef __GNUC__
#pragma STDC FENV_ACCESS ON
#endif
int main()
{
std::cout << "fdim(4, 1) = " << std::fdim(4, 1)
<< " fdim(1, 4) = " << std::fdim(1, 4) << '\n'
<< "fdim(4,-1) = " << std::fdim(4, -1)
<< " fdim(1,-4) = " << std::fdim(1, -4) << '\n';
// error handling
errno = 0;
std::feclearexcept(FE_ALL_EXCEPT);
std::cout << "fdim(1e308, -1e308) = " << std::fdim(1e308, -1e308) << '\n';
if (errno == ERANGE)
std::cout << " errno == ERANGE: " << std::strerror(errno) << '\n';
if (std::fetestexcept(FE_OVERFLOW))
std::cout << " FE_OVERFLOW raised\n";
}
```
Output:
```
fdim(4, 1) = 3 fdim(1, 4) = 0
fdim(4,-1) = 5 fdim(1,-4) = 5
fdim(1e308, -1e308) = inf
errno == ERANGE: Numerical result out of range
FE_OVERFLOW raised
```
### See also
| | |
| --- | --- |
| [abs(int)labsllabs](abs "cpp/numeric/math/abs")
(C++11) | computes absolute value of an integral value (\(\small{|x|}\)|x|) (function) |
| [fmaxfmaxffmaxl](fmax "cpp/numeric/math/fmax")
(C++11)(C++11)(C++11) | larger of two floating-point values (function) |
| [C documentation](https://en.cppreference.com/w/c/numeric/math/fdim "c/numeric/math/fdim") for `fdim` |
cpp std::fmax, std::fmaxf, std::fmaxl std::fmax, std::fmaxf, std::fmaxl
=================================
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
|
```
float fmax ( float x, float y );
```
| (1) | (since C++11) (constexpr since C++23) |
|
```
float fmaxf( float x, float y );
```
| (2) | (since C++11) (constexpr since C++23) |
|
```
double fmax ( double x, double y );
```
| (3) | (since C++11) (constexpr since C++23) |
|
```
long double fmax ( long double x, long double y );
```
| (4) | (since C++11) (constexpr since C++23) |
|
```
long double fmaxl( long double x, long double y );
```
| (5) | (since C++11) (constexpr since C++23) |
|
```
Promoted fmax ( Arithmetic1 x, Arithmetic2 y );
```
| (6) | (since C++11) (constexpr since C++23) |
1-5) Returns the larger of two floating point arguments, treating NaNs as missing data (between a NaN and a numeric value, the numeric value is chosen)
6) A set of overloads or a function template for all combinations of arguments of [arithmetic type](../../types/is_arithmetic "cpp/types/is arithmetic") not covered by (1-5). If any argument has [integral type](../../types/is_integral "cpp/types/is integral"), it is cast to `double`. If any other argument is `long double`, then the return type is `long double`, otherwise it is `double`. ### Parameters
| | | |
| --- | --- | --- |
| x, y | - | values of floating-point or [integral types](../../types/is_integral "cpp/types/is integral") |
### Return value
If successful, returns the larger of two floating point values. The value returned is exact and does not depend on any rounding modes.
### Error handling
This function is not subject to any of the error conditions specified in `[math\_errhandling](math_errhandling "cpp/numeric/math/math errhandling")`.
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* If one of the two arguments is NaN, the value of the other argument is returned
* Only if both arguments are NaN, NaN is returned
### Notes
This function is not required to be sensitive to the sign of zero, although some implementations additionally enforce that if one argument is `+0` and the other is `-0`, then `+0` is returned.
### Example
```
#include <iostream>
#include <cmath>
int main()
{
std::cout << "fmax(2,1) = " << std::fmax(2,1) << '\n'
<< "fmax(-Inf,0) = " << std::fmax(-INFINITY,0) << '\n'
<< "fmax(NaN,-1) = " << std::fmax(NAN,-1) << '\n';
}
```
Output:
```
fmax(2,1) = 2
fmax(-Inf,0) = 0
fmax(NaN,-1) = -1
```
### See also
| | |
| --- | --- |
| [isgreater](isgreater "cpp/numeric/math/isgreater")
(C++11) | checks if the first floating-point argument is greater than the second (function) |
| [fminfminffminl](fmin "cpp/numeric/math/fmin")
(C++11)(C++11)(C++11) | smaller of two floating point values (function) |
| [max](../../algorithm/max "cpp/algorithm/max") | returns the greater of the given values (function template) |
| [max\_element](../../algorithm/max_element "cpp/algorithm/max element") | returns the largest element in a range (function template) |
| [minmax](../../algorithm/minmax "cpp/algorithm/minmax")
(C++11) | returns the smaller and larger of two elements (function template) |
| [minmax\_element](../../algorithm/minmax_element "cpp/algorithm/minmax element")
(C++11) | returns the smallest and the largest elements in a range (function template) |
| [C documentation](https://en.cppreference.com/w/c/numeric/math/fmax "c/numeric/math/fmax") for `fmax` |
| programming_docs |
cpp std::isless std::isless
===========
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
|
```
bool isless( float x, float y );
```
| (1) | (since C++11) (constexpr since C++23) |
|
```
bool isless( double x, double y );
```
| (2) | (since C++11) (constexpr since C++23) |
|
```
bool isless( long double x, long double y );
```
| (3) | (since C++11) (constexpr since C++23) |
|
```
bool isless( Arithmetic x, Arithmetic y );
```
| (4) | (since C++11) (constexpr since C++23) |
1-3) Determines if the floating point number `x` is less than the floating-point number `y`, without setting floating-point exceptions.
4) A set of overloads or a function template for all combinations of arguments of arithmetic type not covered by (1-3). If any argument has [integral type](../../types/is_integral "cpp/types/is integral"), it is cast to `double`. ### Parameters
| | | |
| --- | --- | --- |
| x | - | floating point value |
| y | - | floating point value |
### Return value
`true` if `x < y`, `false` otherwise.
### Notes
The built-in `operator<` for floating-point numbers may raise `[FE\_INVALID](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` if one or both of the arguments is NaN. This function is a "quiet" version of `operator<`.
### See also
| | |
| --- | --- |
| [less](../../utility/functional/less "cpp/utility/functional/less") | function object implementing `x < y` (class template) |
| [isgreater](isgreater "cpp/numeric/math/isgreater")
(C++11) | checks if the first floating-point argument is greater than the second (function) |
| [C documentation](https://en.cppreference.com/w/c/numeric/math/isless "c/numeric/math/isless") for `isless` |
cpp std::atanh, std::atanhf, std::atanhl std::atanh, std::atanhf, std::atanhl
====================================
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
|
```
float atanh ( float arg );
float atanhf( float arg );
```
| (1) | (since C++11) |
|
```
double atanh ( double arg );
```
| (2) | (since C++11) |
|
```
long double atanh ( long double arg );
long double atanhl( long double arg );
```
| (3) | (since C++11) |
|
```
double atanh ( IntegralType arg );
```
| (4) | (since C++11) |
1-3) Computes the inverse hyperbolic tangent of `arg`.
4) A set of overloads or a function template accepting an argument of any [integral type](../../types/is_integral "cpp/types/is integral"). Equivalent to 2) (the argument is cast to `double`). ### Parameters
| | | |
| --- | --- | --- |
| arg | - | value of a floating-point or [Integral type](../../types/is_integral "cpp/types/is integral") |
### Return value
If no errors occur, the inverse hyperbolic tangent of `arg` (tanh-1
(arg), or artanh(arg)), is returned.
If a domain error occurs, an implementation-defined value is returned (NaN where supported).
If a pole error occurs, `[ยฑHUGE\_VAL](huge_val "cpp/numeric/math/HUGE VAL")`, `ยฑHUGE_VALF`, or `ยฑHUGE_VALL` is returned (with the correct sign).
If a range error occurs due to underflow, the correct result (after rounding) is returned.
### Error handling
Errors are reported as specified in `[math\_errhandling](math_errhandling "cpp/numeric/math/math errhandling")`.
If the argument is not on the interval [-1, +1], a range error occurs.
If the argument is ยฑ1, a pole error occurs.
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* if the argument is ยฑ0, it is returned unmodified
* if the argument is ยฑ1, ยฑโ is returned and `[FE\_DIVBYZERO](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` is raised.
* if |arg|>1, NaN is returned and `[FE\_INVALID](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` is raised.
* if the argument is NaN, NaN is returned
### Notes
Although the C standard (to which C++ refers for this function) names this function "arc hyperbolic tangent", the inverse functions of the hyperbolic functions are the area functions. Their argument is the area of a hyperbolic sector, not an arc. The correct name is "inverse hyperbolic tangent" (used by POSIX) or "area hyperbolic tangent".
[POSIX specifies](http://pubs.opengroup.org/onlinepubs/9699919799/functions/atanh.html) that in case of underflow, `arg` is returned unmodified, and if that is not supported, an implementation-defined value no greater than DBL\_MIN, FLT\_MIN, and LDBL\_MIN is returned.
### Example
```
#include <iostream>
#include <cmath>
#include <cfloat>
#include <cerrno>
#include <cfenv>
#include <cstring>
#pragma STDC FENV_ACCESS ON
int main()
{
std::cout << "atanh(0) = " << std::atanh(0) << '\n'
<< "atanh(-0) = " << std::atanh(-0.0) << '\n'
<< "atanh(0.9) = " << std::atanh(0.9) << '\n';
// error handling
errno = 0;
std::feclearexcept(FE_ALL_EXCEPT);
std::cout << "atanh(-1) = " << std::atanh(-1) << '\n';
if (errno == ERANGE)
std::cout << " errno == ERANGE: " << std::strerror(errno) << '\n';
if (std::fetestexcept(FE_DIVBYZERO))
std::cout << " FE_DIVBYZERO raised\n";
}
```
Possible output:
```
atanh(0) = 0
atanh(-0) = -0
atanh(0.9) = 1.47222
atanh(-1) = -inf
errno == ERANGE: Numerical result out of range
FE_DIVBYZERO raised
```
### See also
| | |
| --- | --- |
| [asinhasinhfasinhl](asinh "cpp/numeric/math/asinh")
(C++11)(C++11)(C++11) | computes the inverse hyperbolic sine (\({\small\operatorname{arsinh}{x} }\)arsinh(x)) (function) |
| [acoshacoshfacoshl](acosh "cpp/numeric/math/acosh")
(C++11)(C++11)(C++11) | computes the inverse hyperbolic cosine (\({\small\operatorname{arcosh}{x} }\)arcosh(x)) (function) |
| [tanhtanhftanhl](tanh "cpp/numeric/math/tanh")
(C++11)(C++11) | computes hyperbolic tangent (\({\small\tanh{x} }\)tanh(x)) (function) |
| [atanh(std::complex)](../complex/atanh "cpp/numeric/complex/atanh")
(C++11) | computes area hyperbolic tangent of a complex number (\({\small\operatorname{artanh}{z} }\)artanh(z)) (function template) |
| [C documentation](https://en.cppreference.com/w/c/numeric/math/atanh "c/numeric/math/atanh") for `atanh` |
### External links
[Weisstein, Eric W. "Inverse Hyperbolic Tangent."](http://mathworld.wolfram.com/InverseHyperbolicTangent.html) From MathWorld--A Wolfram Web Resource.
cpp std::scalbn, std::scalbnf, std::scalbnl, std::scalbln, std::scalblnf, std::scalblnl std::scalbn, std::scalbnf, std::scalbnl, std::scalbln, std::scalblnf, std::scalblnl
===================================================================================
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
|
```
float scalbn ( float x, int exp );
```
| (1) | (since C++11) (constexpr since C++23) |
|
```
float scalbnf( float x, int exp );
```
| (2) | (since C++11) (constexpr since C++23) |
|
```
double scalbn ( double x, int exp );
```
| (3) | (since C++11) (constexpr since C++23) |
|
```
long double scalbn ( long double x, int exp );
```
| (4) | (since C++11) (constexpr since C++23) |
|
```
long double scalbnl( long double x, int exp );
```
| (5) | (since C++11) (constexpr since C++23) |
|
```
double scalbn ( IntegralType x, int exp );
```
| (6) | (since C++11) (constexpr since C++23) |
|
```
float scalbln ( float x, long exp );
```
| (7) | (since C++11) (constexpr since C++23) |
|
```
float scalblnf( float x, long exp );
```
| (8) | (since C++11) (constexpr since C++23) |
|
```
double scalbln ( double x, long exp );
```
| (9) | (since C++11) (constexpr since C++23) |
|
```
long double scalbln ( long double x, long exp );
```
| (10) | (since C++11) (constexpr since C++23) |
|
```
long double scalblnl( long double x, long exp );
```
| (11) | (since C++11) (constexpr since C++23) |
|
```
double scalbln ( IntegralType x, long exp );
```
| (12) | (since C++11) (constexpr since C++23) |
1-5,7-11) Multiplies a floating point value `x` by `[FLT\_RADIX](../../types/climits "cpp/types/climits")` raised to power `exp`.
6,12) A set of overloads or a function template accepting an argument of any [integral type](../../types/is_integral "cpp/types/is integral"). Equivalent to (3) or (9) (the argument is cast to `double`). ### Parameters
| | | |
| --- | --- | --- |
| x | - | floating point value |
| exp | - | integer value |
### Return value
If no errors occur, `x` multiplied by `[FLT\_RADIX](../../types/climits "cpp/types/climits")` to the power of `arg` (xรFLT\_RADIXexp
) is returned.
If a range error due to overflow occurs, `[ยฑHUGE\_VAL](huge_val "cpp/numeric/math/HUGE VAL")`, `ยฑHUGE_VALF`, or `ยฑHUGE_VALL` is returned.
If a range error due to underflow occurs, the correct result (after rounding) is returned.
### Error handling
Errors are reported as specified in `[math\_errhandling](math_errhandling "cpp/numeric/math/math errhandling")`.
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* Unless a range error occurs, `[FE\_INEXACT](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` is never raised (the result is exact)
* Unless a range error occurs, [the current rounding mode](../fenv/fe_round "cpp/numeric/fenv/FE round") is ignored
* If `x` is ยฑ0, it is returned, unmodified
* If `x` is ยฑโ, it is returned, unmodified
* If `exp` is 0, then `x` is returned, unmodified
* If `x` is NaN, NaN is returned
### Notes
On binary systems (where `[FLT\_RADIX](../../types/climits "cpp/types/climits")` is `2`), `std::scalbn` is equivalent to `[std::ldexp](ldexp "cpp/numeric/math/ldexp")`.
Although `std::scalbn` and `std::scalbln` are specified to perform the operation efficiently, on many implementations they are less efficient than multiplication or division by a power of two using arithmetic operators.
The function name stands for "new scalb", where `scalb` was an older non-standard function whose second argument had floating-point type.
The `scalbln` function is provided because the factor required to scale from the smallest positive floating-point value to the largest finite one may be greater than 32767, the standard-guaranteed `[INT\_MAX](../../types/climits "cpp/types/climits")`. In particular, for the 80-bit `long double`, the factor is 32828.
The GNU implementation does not set `errno` regardless of `math_errhandling`.
### Example
```
#include <iostream>
#include <cmath>
#include <cerrno>
#include <cstring>
#include <cfenv>
// #pragma STDC FENV_ACCESS ON
int main()
{
std::cout << "scalbn(7, -4) = " << std::scalbn(7, -4) << '\n'
<< "scalbn(1, -1074) = " << std::scalbn(1, -1074)
<< " (minimum positive subnormal double)\n"
<< "scalbn(nextafter(1,0), 1024) = "
<< std::scalbn(std::nextafter(1,0), 1024)
<< " (largest finite double)\n";
// special values
std::cout << "scalbn(-0, 10) = " << std::scalbn(-0.0, 10) << '\n'
<< "scalbn(-Inf, -1) = " << std::scalbn(-INFINITY, -1) << '\n';
// error handling
errno = 0;
std::feclearexcept(FE_ALL_EXCEPT);
std::cout << "scalbn(1, 1024) = " << std::scalbn(1, 1024) << '\n';
if (errno == ERANGE)
std::cout << " errno == ERANGE: " << std::strerror(errno) << '\n';
if (std::fetestexcept(FE_OVERFLOW))
std::cout << " FE_OVERFLOW raised\n";
}
```
Possible output:
```
scalbn(7, -4) = 0.4375
scalbn(1, -1074) = 4.94066e-324 (minimum positive subnormal double)
scalbn(nextafter(1,0), 1024) = 1.79769e+308 (largest finite double)
scalbn(-0, 10) = -0
scalbn(-Inf, -1) = -inf
scalbn(1, 1024) = inf
errno == ERANGE: Numerical result out of range
FE_OVERFLOW raised
```
### See also
| | |
| --- | --- |
| [frexpfrexpffrexpl](frexp "cpp/numeric/math/frexp")
(C++11)(C++11) | decomposes a number into significand and a power of `2` (function) |
| [ldexpldexpfldexpl](ldexp "cpp/numeric/math/ldexp")
(C++11)(C++11) | multiplies a number by `2` raised to a power (function) |
| [C documentation](https://en.cppreference.com/w/c/numeric/math/scalbn "c/numeric/math/scalbn") for `scalbn` |
cpp std::tan, std::tanf, std::tanl std::tan, std::tanf, std::tanl
==============================
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
| | (1) | |
|
```
float tan ( float arg );
```
| |
|
```
float tanf( float arg );
```
| (since C++11) |
|
```
double tan ( double arg );
```
| (2) | |
| | (3) | |
|
```
long double tan ( long double arg );
```
| |
|
```
long double tanl( long double arg );
```
| (since C++11) |
|
```
double tan ( IntegralType arg );
```
| (4) | (since C++11) |
1-3) Computes the tangent of `arg` (measured in radians).
4) A set of overloads or a function template accepting an argument of any [integral type](../../types/is_integral "cpp/types/is integral"). Equivalent to 2) (the argument is cast to `double`). ### Parameters
| | | |
| --- | --- | --- |
| arg | - | value representing angle in radians, of a floating-point or [Integral type](../../types/is_integral "cpp/types/is integral") |
### Return value
If no errors occur, the tangent of `arg` (tan(arg)) is returned.
| | |
| --- | --- |
| The result may have little or no significance if the magnitude of `arg` is large. | (until C++11) |
If a domain error occurs, an implementation-defined value is returned (NaN where supported).
If a range error occurs due to underflow, the correct result (after rounding) is returned.
### Error handling
Errors are reported as specified in `[math\_errhandling](math_errhandling "cpp/numeric/math/math errhandling")`.
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* if the argument is ยฑ0, it is returned unmodified
* if the argument is ยฑโ, NaN is returned and `[FE\_INVALID](../fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` is raised
* if the argument is NaN, NaN is returned
### Notes
The case where the argument is infinite is not specified to be a domain error in C (to which C++ defers), but it is defined as a [domain error in POSIX](http://pubs.opengroup.org/onlinepubs/9699919799/functions/tan.html).
The function has mathematical poles at ฯ(1/2 + n); however no common floating-point representation is able to represent ฯ/2 exactly, thus there is no value of the argument for which a pole error occurs.
### Example
```
#include <iostream>
#include <cmath>
#include <cerrno>
#include <cfenv>
// #pragma STDC FENV_ACCESS ON
const double pi = std::acos(-1); // or C++20's std::numbers::pi
int main()
{
// typical usage
std::cout << "tan(1*pi/4) = " << std::tan(1*pi/4) << '\n' // 45ยฐ
<< "tan(3*pi/4) = " << std::tan(3*pi/4) << '\n' // 135ยฐ
<< "tan(5*pi/4) = " << std::tan(5*pi/4) << '\n' // -135ยฐ
<< "tan(7*pi/4) = " << std::tan(7*pi/4) << '\n'; // -45ยฐ
// special values
std::cout << "tan(+0) = " << std::tan(0.0) << '\n'
<< "tan(-0) = " << std::tan(-0.0) << '\n';
// error handling
std::feclearexcept(FE_ALL_EXCEPT);
std::cout << "tan(INFINITY) = " << std::tan(INFINITY) << '\n';
if (std::fetestexcept(FE_INVALID))
std::cout << " FE_INVALID raised\n";
}
```
Possible output:
```
tan(1*pi/4) = 1
tan(3*pi/4) = -1
tan(5*pi/4) = 1
tan(7*pi/4) = -1
tan(+0) = 0
tan(-0) = -0
tan(INFINITY) = -nan
FE_INVALID raised
```
### See also
| | |
| --- | --- |
| [sinsinfsinl](sin "cpp/numeric/math/sin")
(C++11)(C++11) | computes sine (\({\small\sin{x} }\)sin(x)) (function) |
| [coscosfcosl](cos "cpp/numeric/math/cos")
(C++11)(C++11) | computes cosine (\({\small\cos{x} }\)cos(x)) (function) |
| [atanatanfatanl](atan "cpp/numeric/math/atan")
(C++11)(C++11) | computes arc tangent (\({\small\arctan{x} }\)arctan(x)) (function) |
| [tan(std::complex)](../complex/tan "cpp/numeric/complex/tan") | computes tangent of a complex number (\({\small\tan{z} }\)tan(z)) (function template) |
| [tan(std::valarray)](../valarray/tan "cpp/numeric/valarray/tan") | applies the function `std::tan` to each element of valarray (function template) |
| [C documentation](https://en.cppreference.com/w/c/numeric/math/tan "c/numeric/math/tan") for `tan` |
cpp std::isnormal std::isnormal
=============
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
|
```
bool isnormal( float arg );
```
| (1) | (since C++11) (constexpr since C++23) |
|
```
bool isnormal( double arg );
```
| (2) | (since C++11) (constexpr since C++23) |
|
```
bool isnormal( long double arg );
```
| (3) | (since C++11) (constexpr since C++23) |
|
```
bool isnormal( IntegralType arg );
```
| (4) | (since C++11) (constexpr since C++23) |
1-3) Determines if the given floating point number `arg` is normal, i.e. is neither zero, subnormal, infinite, nor NaN.
4) A set of overloads or a function template accepting the `arg` argument of any [integral type](../../types/is_integral "cpp/types/is integral"). Equivalent to (2) (the argument is cast to `double`). ### Parameters
| | | |
| --- | --- | --- |
| arg | - | floating point value |
### Return value
`true` if `arg` is normal, `false` otherwise.
### Example
```
#include <iostream>
#include <cmath>
#include <cfloat>
int main()
{
std::cout << std::boolalpha
<< "isnormal(NaN) = " << std::isnormal(NAN) << '\n'
<< "isnormal(Inf) = " << std::isnormal(INFINITY) << '\n'
<< "isnormal(0.0) = " << std::isnormal(0.0) << '\n'
<< "isnormal(DBL_MIN/2.0) = " << std::isnormal(DBL_MIN/2.0) << '\n'
<< "isnormal(1.0) = " << std::isnormal(1.0) << '\n';
}
```
Output:
```
isnormal(NaN) = false
isnormal(Inf) = false
isnormal(0.0) = false
isnormal(DBL_MIN/2.0) = false
isnormal(1.0) = true
```
### See also
| | |
| --- | --- |
| [fpclassify](fpclassify "cpp/numeric/math/fpclassify")
(C++11) | categorizes the given floating-point value (function) |
| [isfinite](isfinite "cpp/numeric/math/isfinite")
(C++11) | checks if the given number has finite value (function) |
| [isinf](isinf "cpp/numeric/math/isinf")
(C++11) | checks if the given number is infinite (function) |
| [isnan](isnan "cpp/numeric/math/isnan")
(C++11) | checks if the given number is NaN (function) |
| [C documentation](https://en.cppreference.com/w/c/numeric/math/isnormal "c/numeric/math/isnormal") for `isnormal` |
cpp std::ratio_subtract std::ratio\_subtract
====================
| Defined in header `[<ratio>](../../header/ratio "cpp/header/ratio")` | | |
| --- | --- | --- |
|
```
template< class R1, class R2 >
using ratio_subtract = /* see below */;
```
| | (since C++11) |
The alias template `std::ratio_subtract` denotes the result of subtracting two exact rational fractions represented by the `[std::ratio](ratio "cpp/numeric/ratio/ratio")` specializations `R1` and `R2`.
The result is a `[std::ratio](ratio "cpp/numeric/ratio/ratio")` specialization `[std::ratio](http://en.cppreference.com/w/cpp/numeric/ratio/ratio)<U, V>`, such that given `Num == R1::num * R2::den - R2::num * R1::den` and `Denom == R1::den * R2::den` (computed without arithmetic overflow), `U` is `[std::ratio](http://en.cppreference.com/w/cpp/numeric/ratio/ratio)<Num, Denom>::num` and `V` is `[std::ratio](http://en.cppreference.com/w/cpp/numeric/ratio/ratio)<Num, Denom>::den`.
### Notes
If `U` or `V` is not representable in `std::intmax_t`, the program is ill-formed. If `Num` or `Denom` is not representable in `std::intmax_t`, the program is ill-formed unless the implementation yields correct values for `U` and `V`.
The above definition requires that the result of `std::ratio_subtract<R1, R2>` be already reduced to lowest terms; for example, `std::ratio\_subtract<[std::ratio](http://en.cppreference.com/w/cpp/numeric/ratio/ratio)<1, 2>, [std::ratio](http://en.cppreference.com/w/cpp/numeric/ratio/ratio)<1, 6>>` is the same type as `[std::ratio](http://en.cppreference.com/w/cpp/numeric/ratio/ratio)<1, 3>`.
### Example
```
#include <iostream>
#include <ratio>
int main()
{
using two_third = std::ratio<2, 3>;
using one_sixth = std::ratio<1, 6>;
using diff = std::ratio_subtract<two_third, one_sixth>;
std::cout << "2/3 - 1/6 = " << diff::num << '/' << diff::den << '\n';
}
```
Output:
```
2/3 - 1/6 = 1/2
```
| programming_docs |
cpp std::ratio_divide std::ratio\_divide
==================
| Defined in header `[<ratio>](../../header/ratio "cpp/header/ratio")` | | |
| --- | --- | --- |
|
```
template< class R1, class R2 >
using ratio_divide = /* see below */;
```
| | (since C++11) |
The alias template `std::ratio_divide` denotes the result of dividing two exact rational fractions represented by the `[std::ratio](ratio "cpp/numeric/ratio/ratio")` specializations `R1` and `R2`.
The result is a `[std::ratio](ratio "cpp/numeric/ratio/ratio")` specialization `[std::ratio](http://en.cppreference.com/w/cpp/numeric/ratio/ratio)<U, V>`, such that given `Num == R1::num * R2::den` and `Denom == R1::den * R2::num` (computed without arithmetic overflow), `U` is `[std::ratio](http://en.cppreference.com/w/cpp/numeric/ratio/ratio)<Num, Denom>::num` and `V` is `[std::ratio](http://en.cppreference.com/w/cpp/numeric/ratio/ratio)<Num, Denom>::den`.
### Notes
If `U` or `V` is not representable in `std::intmax_t`, the program is ill-formed. If `Num` or `Denom` is not representable in `std::intmax_t`, the program is ill-formed unless the implementation yields correct values for `U` and `V`.
The above definition requires that the result of `std::ratio_divide<R1, R2>` be already reduced to lowest terms; for example, `std::ratio\_divide<[std::ratio](http://en.cppreference.com/w/cpp/numeric/ratio/ratio)<1, 12>, [std::ratio](http://en.cppreference.com/w/cpp/numeric/ratio/ratio)<1, 6>>` is the same type as `[std::ratio](http://en.cppreference.com/w/cpp/numeric/ratio/ratio)<1, 2>`.
### Example
```
#include <iostream>
#include <ratio>
int main()
{
using two_third = std::ratio<2, 3>;
using one_sixth = std::ratio<1, 6>;
using quotient = std::ratio_divide<two_third, one_sixth>;
std::cout << "(2/3) / (1/6) = " << quotient::num << '/' << quotient::den << '\n';
}
```
Output:
```
(2/3) / (1/6) = 4/1
```
cpp std::ratio_not_equal std::ratio\_not\_equal
======================
| Defined in header `[<ratio>](../../header/ratio "cpp/header/ratio")` | | |
| --- | --- | --- |
|
```
template< class R1, class R2 >
struct ratio_not_equal : std::integral_constant<bool, /* see below */> { };
```
| | (since C++11) |
If the ratios R1 and R2 are not equal, provides the member constant `value` equal `true`. Otherwise, `value` is `false`.
### Helper variable template
| | | |
| --- | --- | --- |
|
```
template< class R1, class R2 >
inline constexpr bool ratio_not_equal_v = ratio_not_equal<R1, R2>::value;
```
| | (since C++17) |
Inherited from [std::integral\_constant](../../types/integral_constant "cpp/types/integral constant")
-------------------------------------------------------------------------------------------------------
### Member constants
| | |
| --- | --- |
| value
[static] | `true` if `R1::num != R2::num || R1::den != R2::den` , `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>` |
### Possible implementation
| |
| --- |
|
```
template< class R1, class R2 >
struct ratio_not_equal : std::integral_constant <
bool,
!std::ratio_equal<R1, R2>
> {};
```
|
### Example
```
#include <iostream>
#include <ratio>
int main()
{
if(std::ratio_not_equal<std::ratio<2,3>, std::ratio<1,3>>::value) {
std::cout << "2/3 != 1/3\n";
} else {
std::cout << "2/3 == 1/3\n";
}
}
```
Output:
```
2/3 != 1/3
```
### See also
| |
| --- |
| |
cpp std::ratio std::ratio
==========
| Defined in header `[<ratio>](../../header/ratio "cpp/header/ratio")` | | |
| --- | --- | --- |
|
```
template<
std::intmax_t Num,
std::intmax_t Denom = 1
> class ratio;
```
| | (since C++11) |
The class template `std::ratio` provides [compile-time rational arithmetic](../ratio "cpp/numeric/ratio") support. Each instantiation of this template exactly represents any finite rational number as long as its numerator `Num` and denominator `Denom` are representable as compile-time constants of type `[std::intmax\_t](../../types/integer "cpp/types/integer")`. In addition, `Denom` may not be zero and may not be equal to the most negative value.
The static data members `num` and `den` representing the numerator and denominator are calculated by dividing `Num` and `Denom` by their greatest common divisor. However, two `std::ratio` with different `Num` or `Denom` are distinct types even if they represent the same rational number (after reduction). A `ratio` type can be reduced to the lowest terms via its `type` member: `std::ratio<3, 6>::type` is `std::ratio<1, 2>`.
Several convenience typedefs that correspond to the SI ratios are provided by the standard library:
| Defined in header `[<ratio>](../../header/ratio "cpp/header/ratio")` |
| --- |
| Type | Definition |
| `yocto` | `std::ratio<1, 1000000000000000000000000>`, if `[std::intmax\_t](../../types/integer "cpp/types/integer")` can represent the denominator |
| `zepto` | `std::ratio<1, 1000000000000000000000>`, if `[std::intmax\_t](../../types/integer "cpp/types/integer")` can represent the denominator |
| `atto` | `std::ratio<1, 1000000000000000000>` |
| `femto` | `std::ratio<1, 1000000000000000>` |
| `pico` | `std::ratio<1, 1000000000000>` |
| `nano` | `std::ratio<1, 1000000000>` |
| `micro` | `std::ratio<1, 1000000>` |
| `milli` | `std::ratio<1, 1000>` |
| `centi` | `std::ratio<1, 100>` |
| `deci` | `std::ratio<1, 10>` |
| `deca` | `std::ratio<10, 1>` |
| `hecto` | `std::ratio<100, 1>` |
| `kilo` | `std::ratio<1000, 1>` |
| `mega` | `std::ratio<1000000, 1>` |
| `giga` | `std::ratio<1000000000, 1>` |
| `tera` | `std::ratio<1000000000000, 1>` |
| `peta` | `std::ratio<1000000000000000, 1>` |
| `exa` | `std::ratio<1000000000000000000, 1>` |
| `zetta` | `std::ratio<1000000000000000000000, 1>`, if `[std::intmax\_t](../../types/integer "cpp/types/integer")` can represent the numerator |
| `yotta` | `std::ratio<1000000000000000000000000, 1>`, if `[std::intmax\_t](../../types/integer "cpp/types/integer")` can represent the numerator |
### Member types
| Member type | Definition |
| --- | --- |
| `type` | `std::ratio<num, den>` |
### Member objects
| | |
| --- | --- |
| constexpr intmax\_t num
[static] | `constexpr` value of type `[std::intmax\_t](../../types/integer "cpp/types/integer")` equal to `sign(Denom) * Num / gcd(Num, Denom)` (public static member constant) |
| constexpr intmax\_t den
[static] | `constexpr` value of type `[std::intmax\_t](../../types/integer "cpp/types/integer")` equal to `abs(Denom) / gcd(Num, Denom)` (public static member constant) |
### See also
| | |
| --- | --- |
| [Mathematical constants](../constants "cpp/numeric/constants") (C++20) | provides several mathematical constants, such as `[std::numbers::e](../constants "cpp/numeric/constants")` for e |
cpp std::ratio_add std::ratio\_add
===============
| Defined in header `[<ratio>](../../header/ratio "cpp/header/ratio")` | | |
| --- | --- | --- |
|
```
template< class R1, class R2 >
using ratio_add = /* see below */;
```
| | (since C++11) |
The alias template `std::ratio_add` denotes the result of adding two exact rational fractions represented by the `[std::ratio](ratio "cpp/numeric/ratio/ratio")` specializations `R1` and `R2`.
The result is a `[std::ratio](ratio "cpp/numeric/ratio/ratio")` specialization `[std::ratio](http://en.cppreference.com/w/cpp/numeric/ratio/ratio)<U, V>`, such that given `Num == R1::num * R2::den + R2::num * R1::den` and `Denom == R1::den * R2::den` (computed without arithmetic overflow), `U` is `[std::ratio](http://en.cppreference.com/w/cpp/numeric/ratio/ratio)<Num, Denom>::num` and `V` is `[std::ratio](http://en.cppreference.com/w/cpp/numeric/ratio/ratio)<Num, Denom>::den`.
### Notes
If `U` or `V` is not representable in `std::intmax_t`, the program is ill-formed. If `Num` or `Denom` is not representable in `std::intmax_t`, the program is ill-formed unless the implementation yields correct values for `U` and `V`.
The above definition requires that the result of `std::ratio_add<R1, R2>` be already reduced to lowest terms; for example, `std::ratio\_add<[std::ratio](http://en.cppreference.com/w/cpp/numeric/ratio/ratio)<1, 3>, [std::ratio](http://en.cppreference.com/w/cpp/numeric/ratio/ratio)<1, 6>>` is the same type as `[std::ratio](http://en.cppreference.com/w/cpp/numeric/ratio/ratio)<1, 2>`.
### Example
```
#include <iostream>
#include <ratio>
int main()
{
using two_third = std::ratio<2, 3>;
using one_sixth = std::ratio<1, 6>;
using sum = std::ratio_add<two_third, one_sixth>;
std::cout << "2/3 + 1/6 = " << sum::num << '/' << sum::den << '\n';
}
```
Output:
```
2/3 + 1/6 = 5/6
```
cpp std::ratio_multiply std::ratio\_multiply
====================
| Defined in header `[<ratio>](../../header/ratio "cpp/header/ratio")` | | |
| --- | --- | --- |
|
```
template< class R1, class R2 >
using ratio_multiply = /* see below */;
```
| | (since C++11) |
The alias template `std::ratio_multiply` denotes the result of multiplying two exact rational fractions represented by the `[std::ratio](ratio "cpp/numeric/ratio/ratio")` specializations `R1` and `R2`.
The result is a `[std::ratio](ratio "cpp/numeric/ratio/ratio")` specialization `[std::ratio](http://en.cppreference.com/w/cpp/numeric/ratio/ratio)<U, V>`, such that given `Num == R1::num * R2::num` and `Denom == R1::den * R2::den` (computed without arithmetic overflow), `U` is `[std::ratio](http://en.cppreference.com/w/cpp/numeric/ratio/ratio)<Num, Denom>::num` and `V` is `[std::ratio](http://en.cppreference.com/w/cpp/numeric/ratio/ratio)<Num, Denom>::den`.
### Notes
If `U` or `V` is not representable in `std::intmax_t`, the program is ill-formed. If `Num` or `Denom` is not representable in `std::intmax_t`, the program is ill-formed unless the implementation yields correct values for `U` and `V`.
The above definition requires that the result of `std::ratio_multiply<R1, R2>` be already reduced to lowest terms; for example, `std::ratio\_multiply<[std::ratio](http://en.cppreference.com/w/cpp/numeric/ratio/ratio)<1, 6>, [std::ratio](http://en.cppreference.com/w/cpp/numeric/ratio/ratio)<4, 5>>` is the same type as `[std::ratio](http://en.cppreference.com/w/cpp/numeric/ratio/ratio)<2, 15>`.
### Example
```
#include <iostream>
#include <ratio>
int main()
{
using two_third = std::ratio<2, 3>;
using one_sixth = std::ratio<1, 6>;
using product = std::ratio_multiply<two_third, one_sixth>;
std::cout << "2/3 * 1/6 = " << product::num << '/' << product::den << '\n';
}
```
Output:
```
2/3 * 1/6 = 1/9
```
cpp std::ratio_greater std::ratio\_greater
===================
| Defined in header `[<ratio>](../../header/ratio "cpp/header/ratio")` | | |
| --- | --- | --- |
|
```
template< class R1, class R2 >
struct ratio_greater : std::integral_constant<bool, /* see below */> { };
```
| | (since C++11) |
If the ratio `R1` is greater than the ratio `R2`, provides the member constant `value` equal `true`. Otherwise, `value` is `false`.
### Helper variable template
| | | |
| --- | --- | --- |
|
```
template< class R1, class R2 >
inline constexpr bool ratio_greater_v = ratio_greater<R1, R2>::value;
```
| | (since C++17) |
Inherited from [std::integral\_constant](../../types/integral_constant "cpp/types/integral constant")
-------------------------------------------------------------------------------------------------------
### Member constants
| | |
| --- | --- |
| value
[static] | `true` if `R1::num * R2::den > R2::num * R1::den`, or equivalent expression that avoids overflow , `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>` |
### Example
```
#include <ratio>
#include <iostream>
auto main() -> int
{
static_assert(std::ratio_greater<std::ratio<3, 4>, std::ratio<1, 2>>::value,
"3/4 > 1/2");
if (std::ratio_greater<std::ratio<11, 12>, std::ratio<10, 11>>::value) {
std::cout << "11/12 > 10/11" "\n";
}
// Since C++17
static_assert(std::ratio_greater_v<std::ratio<12, 13>, std::ratio<11, 12>> );
if constexpr (std::ratio_greater_v<std::ratio<12, 13>, std::ratio<11, 12>>) {
std::cout << "12/13 > 11/12" "\n";
}
}
```
Output:
```
11/12 > 10/11
12/13 > 11/12
```
### See also
| |
| --- |
| |
cpp std::ratio_less_equal std::ratio\_less\_equal
=======================
| Defined in header `[<ratio>](../../header/ratio "cpp/header/ratio")` | | |
| --- | --- | --- |
|
```
template< class R1, class R2 >
struct ratio_less_equal : std::integral_constant<bool, /* see below */> { };
```
| | (since C++11) |
If the ratio `R1` is less than or equal to the ratio `R2`, provides the member constant `value` equal `true`. Otherwise, `value` is `false`.
### Helper variable template
| | | |
| --- | --- | --- |
|
```
template< class R1, class R2 >
inline constexpr bool ratio_less_equal_v = ratio_less_equal<R1, R2>::value;
```
| | (since C++17) |
Inherited from [std::integral\_constant](../../types/integral_constant "cpp/types/integral constant")
-------------------------------------------------------------------------------------------------------
### Member constants
| | |
| --- | --- |
| value
[static] | `true` if `R1::num * R2::den <= R2::num * R1::den`, or equivalent expression that avoids overflow , `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>` |
### Example
```
#include <ratio>
#include <iostream>
auto main() -> int
{
static_assert(std::ratio_less_equal<std::ratio<1, 2>, std::ratio<3, 4>>::value,
"1/2 <= 3/4");
if (std::ratio_less_equal<std::ratio<10,11>, std::ratio<11,12>>::value) {
std::cout << "10/11 <= 11/12" "\n";
}
// Since C++17
static_assert(std::ratio_less_equal_v<std::ratio<10, 11>, std::ratio<11, 12>> );
if constexpr (std::ratio_less_equal_v<std::ratio<10, 11>, std::ratio<11, 12>>) {
std::cout << "11/12 <= 12/13" "\n";
}
}
```
Output:
```
10/11 <= 11/12
11/12 <= 12/13
```
### See also
| |
| --- |
| |
cpp std::ratio_less std::ratio\_less
================
| Defined in header `[<ratio>](../../header/ratio "cpp/header/ratio")` | | |
| --- | --- | --- |
|
```
template< class R1, class R2 >
struct ratio_less : std::integral_constant<bool, /* see below */> { };
```
| | (since C++11) |
If the ratio R1 is less than the ratio R2, provides the member constant `value` equal `true`. Otherwise, `value` is `false`.
### Helper variable template
| | | |
| --- | --- | --- |
|
```
template< class R1, class R2 >
inline constexpr bool ratio_less_v = ratio_less<R1, R2>::value;
```
| | (since C++17) |
Inherited from [std::integral\_constant](../../types/integral_constant "cpp/types/integral constant")
-------------------------------------------------------------------------------------------------------
### Member constants
| | |
| --- | --- |
| value
[static] | `true` if `R1::num * R2::den < R2::num * R1::den`, or equivalent expression that avoids overflow , `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>` |
### Example
```
#include <iostream>
#include <ratio>
int main()
{
if (std::ratio_less<std::ratio<23,37>, std::ratio<57,90>>::value) {
std::cout << "23/37 < 57/90\n";
}
}
```
Output:
```
23/37 < 57/90
```
### See also
| |
| --- |
| |
cpp std::ratio_greater_equal std::ratio\_greater\_equal
==========================
| Defined in header `[<ratio>](../../header/ratio "cpp/header/ratio")` | | |
| --- | --- | --- |
|
```
template< class R1, class R2 >
struct ratio_greater_equal : std::integral_constant<bool, /* see below */> { };
```
| | (since C++11) |
If the ratio `R1` is greater than or equal to the ratio `R2`, provides the member constant `value` equal `true`. Otherwise, `value` is `false`.
### Helper variable template
| | | |
| --- | --- | --- |
|
```
template< class R1, class R2 >
inline constexpr bool ratio_greater_equal_v = ratio_greater_equal<R1, R2>::value;
```
| | (since C++17) |
Inherited from [std::integral\_constant](../../types/integral_constant "cpp/types/integral constant")
-------------------------------------------------------------------------------------------------------
### Member constants
| | |
| --- | --- |
| value
[static] | `true` if `R1::num * R2::den >= R2::num * R1::den`, or equivalent expression that avoids overflow , `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>` |
### Example
```
#include <ratio>
#include <iostream>
auto main() -> int
{
static_assert(std::ratio_greater_equal<
std::ratio<2, 3>,
std::ratio<2, 3>>::value, "2/3 >= 2/3");
if (std::ratio_greater_equal<
std::ratio<2,1>, std::ratio<1, 2>>::value) {
std::cout << "2/1 >= 1/2" "\n";
}
if (std::ratio_greater_equal<
std::ratio<1,2>, std::ratio<1, 2>>::value) {
std::cout << "1/2 >= 1/2" "\n";
}
// Since C++17
static_assert(std::ratio_greater_equal_v<
std::ratio<999'999, 1'000'000>,
std::ratio<999'998, 999'999>> );
if constexpr (std::ratio_greater_equal_v<
std::ratio<999'999, 1'000'000>,
std::ratio<999'998, 999'999>>) {
std::cout << "999'999/1'000'000 >= 999'998/999'999" "\n";
}
if constexpr (std::ratio_greater_equal_v<
std::ratio<999'999, 1'000'000>,
std::ratio<999'999, 1'000'000>>) {
std::cout << "999'999/1'000'000 >= 999'999/1'000'000" "\n";
}
}
```
Output:
```
2/1 >= 1/2
1/2 >= 1/2
999'999/1'000'000 >= 999'998/999'999
999'999/1'000'000 >= 999'999/1'000'000
```
### See also
| |
| --- |
| |
cpp std::ratio_equal std::ratio\_equal
=================
| Defined in header `[<ratio>](../../header/ratio "cpp/header/ratio")` | | |
| --- | --- | --- |
|
```
template< class R1, class R2 >
struct ratio_equal : std::integral_constant<bool, /* see below */> { };
```
| | (since C++11) |
If the ratios R1 and R2 are equal, provides the member constant `value` equal `true`. Otherwise, `value` is `false`.
### Helper variable template
| | | |
| --- | --- | --- |
|
```
template< class R1, class R2 >
inline constexpr bool ratio_equal_v = ratio_equal<R1, R2>::value;
```
| | (since C++17) |
Inherited from [std::integral\_constant](../../types/integral_constant "cpp/types/integral constant")
-------------------------------------------------------------------------------------------------------
### Member constants
| | |
| --- | --- |
| value
[static] | `true` if `R1::num == R2::num && R1::den == R2::den` , `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>` |
### Possible implementation
| |
| --- |
|
```
template< class R1, class R2 >
struct ratio_equal : public std::integral_constant <
bool,
R1::num == R2::num && R1::den == R2::den
> {};
```
|
### Example
```
#include <iostream>
#include <ratio>
int main()
{
constexpr bool equ = std::ratio_equal_v<std::ratio<2,3>,
std::ratio<4,6>>;
std::cout << "2/3 " << (equ ? "==" : "!=") << " 4/6\n";
}
```
Output:
```
2/3 == 4/6
```
### See also
| |
| --- |
| |
| programming_docs |
cpp std::cyl_bessel_i, std::cyl_bessel_if, std::cyl_bessel_il std::cyl\_bessel\_i, std::cyl\_bessel\_if, std::cyl\_bessel\_il
===============================================================
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
|
```
double cyl_bessel_i( double ฮฝ, double x );
float cyl_bessel_if( float ฮฝ, float x );
long double cyl_bessel_il( long double ฮฝ, long double x );
```
| (1) | (since C++17) |
|
```
Promoted cyl_bessel_i( Arithmetic ฮฝ, Arithmetic x );
```
| (2) | (since C++17) |
1) Computes the [regular modified cylindrical Bessel function](https://en.wikipedia.org/wiki/Bessel_function#Modified_Bessel_functions:_I.CE.B1_.2C_K.CE.B1 "enwiki:Bessel function") of `ฮฝ` and `x`.
2) A set of overloads or a function template for all combinations of arguments of arithmetic type not covered by (1). If any argument has [integral type](../../types/is_integral "cpp/types/is integral"), it is cast to `double`. If any argument is `long double`, then the return type `Promoted` is also `long double`, otherwise the return type is always `double`. ### Parameters
| | | |
| --- | --- | --- |
| ฮฝ | - | the order of the function |
| x | - | the argument of the function |
### Return value
If no errors occur, value of the regular modified cylindrical Bessel function of `ฮฝ` and `x`, that is I
ฮฝ(x) = ฮฃโ
k=0(x/2)ฮฝ+2k/k!ฮ(ฮฝ+k+1) (for xโฅ0), is returned. ### Error handling
Errors may be reported as specified in [math\_errhandling](../math/math_errhandling "cpp/numeric/math/math errhandling").
* If the argument is NaN, NaN is returned and domain error is not reported
* If ฮฝ>=128, the behavior is implementation-defined
### Notes
Implementations that do not support C++17, but support [ISO 29124:2010](https://en.cppreference.com/w/cpp/experimental/special_math "cpp/experimental/special math"), provide this function if `__STDCPP_MATH_SPEC_FUNCS__` is defined by the implementation to a value at least 201003L and if the user defines `__STDCPP_WANT_MATH_SPEC_FUNCS__` before including any standard library headers.
Implementations that do not support ISO 29124:2010 but support TR 19768:2007 (TR1), provide this function in the header `tr1/cmath` and namespace `std::tr1`.
An implementation of this function is also [available in boost.math](http://www.boost.org/doc/libs/release/libs/math/doc/html/math_toolkit/bessel/mbessel.html).
### Example
```
#include <cmath>
#include <iostream>
int main()
{
// spot check for ฮฝ == 0
double x = 1.2345;
std::cout << "I_0(" << x << ") = " << std::cyl_bessel_i(0, x) << '\n';
// series expansion for I_0
double fct = 1;
double sum = 0;
for(int k = 0; k < 5; fct*=++k) {
sum += std::pow((x/2),2*k) / std::pow(fct,2);
std::cout << "sum = " << sum << '\n';
}
}
```
Output:
```
I_0(1.2345) = 1.41886
sum = 1
sum = 1.381
sum = 1.41729
sum = 1.41882
sum = 1.41886
```
### See also
| | |
| --- | --- |
| [cyl\_bessel\_jcyl\_bessel\_jfcyl\_bessel\_jl](cyl_bessel_j "cpp/numeric/special functions/cyl bessel j")
(C++17)(C++17)(C++17) | cylindrical Bessel functions (of the first kind) (function) |
### External links
[Weisstein, Eric W. "Modified Bessel Function of the First Kind."](http://mathworld.wolfram.com/ModifiedBesselFunctionoftheFirstKind.html) From MathWorld โ A Wolfram Web Resource.
cpp std::ellint_1, std::ellint_1f, std::ellint_1l std::ellint\_1, std::ellint\_1f, std::ellint\_1l
================================================
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
|
```
double ellint_1( double k, double ฯ );
float ellint_1f( float k, float ฯ );
long double ellint_1l( long double k, long double ฯ );
```
| (1) | (since C++17) |
|
```
Promoted ellint_1( Arithmetic k, Arithmetic ฯ );
```
| (2) | (since C++17) |
1) Computes the [incomplete elliptic integral of the first kind](https://en.wikipedia.org/wiki/Elliptic_integral#Elliptic_integral_of_the_first_kind "enwiki:Elliptic integral") of `k` and `ฯ`.
2) A set of overloads or a function template for all combinations of arguments of arithmetic type not covered by (1). If any argument has [integral type](../../types/is_integral "cpp/types/is integral"), it is cast to `double`. If any argument is `long double`, then the return type `Promoted` is also `long double`, otherwise the return type is always `double`. ### Parameters
| | | |
| --- | --- | --- |
| k | - | elliptic modulus or eccentricity (a value of a floating-point or integral type) |
| ฯ | - | Jacobi amplitude (a value of floating-point or integral type, measured in radians) |
### Return value
If no errors occur, value of the incomplete elliptic integral of the first kind of `k` and `ฯ`, that is โซฯ
0dฮธ/โ1-k2sin2ฮธ, is returned. ### Error handling
Errors may be reported as specified in [`math_errhandling`](../math/math_errhandling "cpp/numeric/math/math errhandling"):
* If the argument is NaN, NaN is returned and domain error is not reported
* If |k|>1, a domain error may occur
### Notes
Implementations that do not support C++17, but support [ISO 29124:2010](https://en.cppreference.com/w/cpp/experimental/special_math "cpp/experimental/special math"), provide this function if `__STDCPP_MATH_SPEC_FUNCS__` is defined by the implementation to a value at least 201003L and if the user defines `__STDCPP_WANT_MATH_SPEC_FUNCS__` before including any standard library headers.
Implementations that do not support ISO 29124:2010 but support TR 19768:2007 (TR1), provide this function in the header `tr1/cmath` and namespace `std::tr1`.
An implementation of this function is also available in [boost.math](http://www.boost.org/doc/libs/release/libs/math/doc/html/math_toolkit/ellint/ellint_1.html).
### Example
```
#include <cmath>
#include <iostream>
int main()
{
double hpi = std::acos(-1)/2;
std::cout << "F(0,ฯ/2) = " << std::ellint_1(0, hpi) << '\n'
<< "F(0,-ฯ/2) = " << std::ellint_1(0, -hpi) << '\n'
<< "ฯ/2 = " << hpi << '\n'
<< "F(0.7,0) = " << std::ellint_1(0.7, 0) << '\n';
}
```
Output:
```
F(0,ฯ/2) = 1.5708
F(0,-ฯ/2) = -1.5708
ฯ/2 = 1.5708
F(0.7,0) = 0
```
### See also
| | |
| --- | --- |
| [comp\_ellint\_1comp\_ellint\_1fcomp\_ellint\_1l](comp_ellint_1 "cpp/numeric/special functions/comp ellint 1")
(C++17)(C++17)(C++17) | (complete) elliptic integral of the first kind (function) |
### External links
[Weisstein, Eric W. "Elliptic Integral of the First Kind."](http://mathworld.wolfram.com/EllipticIntegraloftheFirstKind.html) From MathWorld โ A Wolfram Web Resource.
cpp std::comp_ellint_1, std::comp_ellint_1f, std::comp_ellint_1l std::comp\_ellint\_1, std::comp\_ellint\_1f, std::comp\_ellint\_1l
==================================================================
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
|
```
double comp_ellint_1( double k );
float comp_ellint_1( float k );
long double comp_ellint_1( long double k );
float comp_ellint_1f( float k );
long double comp_ellint_1l( long double k );
```
| (1) | (since C++17) |
|
```
double comp_ellint_1( IntegralType k );
```
| (2) | (since C++17) |
1) Computes the [complete elliptic integral of the first kind](https://en.wikipedia.org/wiki/Elliptic_integral#Complete_elliptic_integral_of_the_first_kind "enwiki:Elliptic integral") of `k`.
2) A set of overloads or a function template accepting an argument of any [integral type](../../types/is_integral "cpp/types/is integral"). Equivalent to (1) after casting the argument to `double`. ### Parameters
| | | |
| --- | --- | --- |
| k | - | elliptic modulus or eccentricity (a value of a floating-point or integral type) |
### Return value
If no errors occur, value of the complete elliptic integral of the first kind of `k`, that is `ellint_1(k,ฯ/2)`, is returned.
### Error handling
Errors may be reported as specified in [math\_errhandling](../math/math_errhandling "cpp/numeric/math/math errhandling").
* If the argument is NaN, NaN is returned and domain error is not reported
* If |k|>1, a domain error may occur
### Notes
Implementations that do not support C++17, but support [ISO 29124:2010](https://en.cppreference.com/w/cpp/experimental/special_math "cpp/experimental/special math"), provide this function if `__STDCPP_MATH_SPEC_FUNCS__` is defined by the implementation to a value at least 201003L and if the user defines `__STDCPP_WANT_MATH_SPEC_FUNCS__` before including any standard library headers.
Implementations that do not support ISO 29124:2010 but support TR 19768:2007 (TR1), provide this function in the header `tr1/cmath` and namespace `std::tr1`.
An implementation of this function is also [available in boost.math](https://www.boost.org/doc/libs/release/libs/math/doc/html/math_toolkit/ellint/ellint_1.html).
The [period of a pendulum](https://en.wikipedia.org/wiki/Pendulum_(mathematics) "enwiki:Pendulum (mathematics)") of length l, given acceleration due to gravity g, and initial angle ฮธ equals 4โl/gK(sin2
(ฮธ/2)), where K is `std::comp_ellint_1`.
### Example
```
#include <cmath>
#include <iostream>
int main()
{
double hpi = std::acos(-1)/2;
std::cout << "K(0) = " << std::comp_ellint_1(0) << '\n'
<< "ฯ/2 = " << hpi << '\n'
<< "K(0.5) = " << std::comp_ellint_1(0.5) << '\n'
<< "F(0.5, ฯ/2) = " << std::ellint_1(0.5, hpi) << '\n';
std::cout << "Period of a pendulum length 1 m at 90ยฐ initial angle is "
<< 4*std::sqrt(1/9.80665)*
std::comp_ellint_1(std::pow(std::sin(hpi/2),2)) << " s\n";
}
```
Output:
```
K(0) = 1.5708
ฯ/2 = 1.5708
K(0.5) = 1.68575
F(0.5, ฯ/2) = 1.68575
Period of a pendulum length 1 m at 90ยฐ initial angle is 2.15324 s
```
### See also
| | |
| --- | --- |
| [ellint\_1ellint\_1fellint\_1l](ellint_1 "cpp/numeric/special functions/ellint 1")
(C++17)(C++17)(C++17) | (incomplete) elliptic integral of the first kind (function) |
### External links
[Weisstein, Eric W. "Complete Elliptic Integral of the First Kind."](http://mathworld.wolfram.com/CompleteEllipticIntegraloftheFirstKind.html) From MathWorld โ A Wolfram Web Resource.
cpp std::sph_legendre, std::sph_legendref, std::sph_legendrel std::sph\_legendre, std::sph\_legendref, std::sph\_legendrel
============================================================
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
|
```
double sph_legendre ( unsigned l, unsigned m, double ฮธ );
float sph_legendre ( unsigned l, unsigned m, float ฮธ );
long double sph_legendre ( unsigned l, unsigned m, long double ฮธ );
float sph_legendref( unsigned l, unsigned m, float ฮธ );
long double sph_legendrel( unsigned l, unsigned m, long double ฮธ );
```
| (1) | (since C++17) |
|
```
double sph_legendre ( unsigned l, unsigned m, IntegralType ฮธ );
```
| (2) | (since C++17) |
1) Computes the spherical associated Legendre function of degree `l`, order `m`, and polar angle `ฮธ`.
2) A set of overloads or a function template accepting an argument of any [integral type](../../types/is_integral "cpp/types/is integral"). Equivalent to (1) after casting the argument to `double`. ### Parameters
| | | |
| --- | --- | --- |
| l | - | degree |
| m | - | order |
| ฮธ | - | polar angle, measured in radians |
### Return value
If no errors occur, returns the value of the spherical associated Legendre function (that is, spherical harmonic with ฯ = 0) of `l`, `m`, and `ฮธ`, where the spherical harmonic function is defined as Ym
l(ฮธ,ฯ) = (-1)m
[(2l+1)(l-m)!/4ฯ(l+m)!]1/2
Pm
l(cosฮธ)eimฯ
where Pm
l(x) is `[std::assoc\_legendre](http://en.cppreference.com/w/cpp/numeric/special_functions/assoc_legendre)(l,m,x)`) and |m|โคl Note that the [Condon-Shortley phase term](http://mathworld.wolfram.com/Condon-ShortleyPhase.html) (-1)m
is included in this definition because it is omitted from the definition of Pm
l in `[std::assoc\_legendre](assoc_legendre "cpp/numeric/special functions/assoc legendre")`.
### Error handling
Errors may be reported as specified in [math\_errhandling](../math/math_errhandling "cpp/numeric/math/math errhandling").
* If the argument is NaN, NaN is returned and domain error is not reported
* If lโฅ128, the behavior is implementation-defined
### Notes
Implementations that do not support C++17, but support [ISO 29124:2010](https://en.cppreference.com/w/cpp/experimental/special_math "cpp/experimental/special math"), provide this function if `__STDCPP_MATH_SPEC_FUNCS__` is defined by the implementation to a value at least 201003L and if the user defines `__STDCPP_WANT_MATH_SPEC_FUNCS__` before including any standard library headers.
Implementations that do not support ISO 29124:2010 but support TR 19768:2007 (TR1), provide this function in the header `tr1/cmath` and namespace `std::tr1`.
An implementation of the spherical harmonic function is available in [boost.math](http://www.boost.org/doc/libs/release/libs/math/doc/html/math_toolkit/sf_poly/sph_harm.html), and it reduces to this function when called with the parameter phi set to zero.
### Example
```
#include <cmath>
#include <iostream>
int main()
{
// spot check for l=3, m=0
double x = 1.2345;
std::cout << "Y_3^0(" << x << ") = " << std::sph_legendre(3, 0, x) << '\n';
// exact solution
double pi = std::acos(-1);
std::cout << "exact solution = "
<< 0.25*std::sqrt(7/pi)*(5*std::pow(std::cos(x),3)-3*std::cos(x))
<< '\n';
}
```
Output:
```
Y_3^0(1.2345) = -0.302387
exact solution = -0.302387
```
### See also
| | |
| --- | --- |
| [assoc\_legendreassoc\_legendrefassoc\_legendrel](assoc_legendre "cpp/numeric/special functions/assoc legendre")
(C++17)(C++17)(C++17) | associated Legendre polynomials (function) |
### External links
[Weisstein, Eric W. "Spherical Harmonic."](http://mathworld.wolfram.com/SphericalHarmonic.html) From MathWorld โ A Wolfram Web Resource.
cpp std::riemann_zeta, std::riemann_zetaf, std::riemann_zetal std::riemann\_zeta, std::riemann\_zetaf, std::riemann\_zetal
============================================================
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
|
```
double riemann_zeta( double arg );
float riemann_zeta( float arg );
long double riemann_zeta( long double arg );
float riemann_zetaf( float arg );
long double riemann_zetal( long double arg );
```
| (1) | (since C++17) |
|
```
double riemann_zeta( IntegralType arg );
```
| (2) | (since C++17) |
1) Computes the [Riemann zeta function](https://en.wikipedia.org/wiki/Riemann_zeta_function "enwiki:Riemann zeta function") of `arg`.
2) A set of overloads or a function template accepting an argument of any [integral type](../../types/is_integral "cpp/types/is integral"). Equivalent to (1) after casting the argument to `double`. ### Parameters
| | | |
| --- | --- | --- |
| arg | - | value of a floating-point or integral type |
### Return value
If no errors occur, value of the Riemann zeta function of `arg`, ฮถ(arg), defined for the entire real axis:
* For arg>1, ฮฃโ
n=1n-arg
* For 0โคargโค1, 1/21-arg-1ฮฃโ
n=1 (-1)n
n-arg
* For arg<0, 2arg
ฯarg-1
sin(ฯarg/2)ฮ(1โarg)ฮถ(1โarg)
### Error handling
Errors may be reported as specified in [math\_errhandling](../math/math_errhandling "cpp/numeric/math/math errhandling").
* If the argument is NaN, NaN is returned and domain error is not reported
### Notes
Implementations that do not support C++17, but support [ISO 29124:2010](https://en.cppreference.com/w/cpp/experimental/special_math "cpp/experimental/special math"), provide this function if `__STDCPP_MATH_SPEC_FUNCS__` is defined by the implementation to a value at least 201003L and if the user defines `__STDCPP_WANT_MATH_SPEC_FUNCS__` before including any standard library headers.
Implementations that do not support ISO 29124:2010 but support TR 19768:2007 (TR1), provide this function in the header `tr1/cmath` and namespace `std::tr1`.
An implementation of this function is also [available in boost.math](http://www.boost.org/doc/libs/release/libs/math/doc/html/math_toolkit/zetas/zeta.html).
### Example
```
#include <cmath>
#include <iostream>
#include <numbers>
const auto ฯยฒ = std::pow(std::numbers::pi,2);
int main()
{
// spot checks for well-known values
std::cout << "ฮถ(-1) = " << std::riemann_zeta(-1) << '\n'
<< "ฮถ(0) = " << std::riemann_zeta(0) << '\n'
<< "ฮถ(1) = " << std::riemann_zeta(1) << '\n'
<< "ฮถ(0.5) = " << std::riemann_zeta(0.5) << '\n'
<< "ฮถ(2) = " << std::riemann_zeta(2) << ' '
<< "(ฯยฒ/6 = " << ฯยฒ/6 << ")\n";
}
```
Output:
```
ฮถ(-1) = -0.0833333
ฮถ(0) = -0.5
ฮถ(1) = inf
ฮถ(0.5) = -1.46035
ฮถ(2) = 1.64493 (ฯยฒ/6 = 1.64493)
```
### External links
[Weisstein, Eric W. "Riemann Zeta Function."](http://mathworld.wolfram.com/RiemannZetaFunction.html) From MathWorld--A Wolfram Web Resource.
cpp std::comp_ellint_3, std::comp_ellint_3f, std::comp_ellint_3l std::comp\_ellint\_3, std::comp\_ellint\_3f, std::comp\_ellint\_3l
==================================================================
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
|
```
double comp_ellint_3( double k, double ฮฝ );
float comp_ellint_3f( float k, float ฮฝ );
long double comp_ellint_3l( long double k, long double ฮฝ );
```
| (1) | (since C++17) |
|
```
Promoted comp_ellint_3( Arithmetic k, Arithmetic ฮฝ );
```
| (2) | (since C++17) |
1) Computes the [complete elliptic integral of the third kind](https://en.wikipedia.org/wiki/Elliptic_integral#Complete_elliptic_integral_of_the_third_kind "enwiki:Elliptic integral") of the arguments `k` and `ฮฝ`.
2) A set of overloads or a function template for all combinations of arguments of arithmetic type not covered by (1). If any argument has [integral type](../../types/is_integral "cpp/types/is integral"), it is cast to `double`. If any argument is `long double`, then the return type `Promoted` is also `long double`, otherwise the return type is always `double`. ### Parameters
| | | |
| --- | --- | --- |
| k | - | elliptic modulus or eccentricity (a value of a floating-point or integral type) |
| ฮฝ | - | elliptic characteristic (a value of floating-point or integral type) |
### Return value
If no errors occur, value of the complete elliptic integral of the third kind of `k` and `ฮฝ`, that is `[std::ellint\_3](http://en.cppreference.com/w/cpp/numeric/special_functions/ellint_3)(k,ฮฝ,ฯ/2)`, is returned.
### Error handling
Errors may be reported as specified in [math\_errhandling](../math/math_errhandling "cpp/numeric/math/math errhandling").
* If the argument is NaN, NaN is returned and domain error is not reported
* If |k|>1, a domain error may occur
### Notes
Implementations that do not support C++17, but support [ISO 29124:2010](https://en.cppreference.com/w/cpp/experimental/special_math "cpp/experimental/special math"), provide this function if `__STDCPP_MATH_SPEC_FUNCS__` is defined by the implementation to a value at least 201003L and if the user defines `__STDCPP_WANT_MATH_SPEC_FUNCS__` before including any standard library headers.
Implementations that do not support ISO 29124:2010 but support TR 19768:2007 (TR1), provide this function in the header `tr1/cmath` and namespace `std::tr1`.
An implementation of this function is also available in [boost.math](https://www.boost.org/doc/libs/release/libs/math/doc/html/math_toolkit/ellint/ellint_3.html).
### Example
```
#include <cmath>
#include <iostream>
int main()
{
std::cout << std::fixed
<< "ฮ (0.5,0) = " << std::comp_ellint_3(0.5, 0) << '\n'
<< "K(0.5) = " << std::comp_ellint_1(0.5) << '\n'
<< "ฮ (0,0) = " << std::comp_ellint_3(0, 0) << '\n'
<< "ฯ/2 = " << std::acos(-1)/2 << '\n'
<< "ฮ (0.5,1) = " << std::comp_ellint_3(0.5, 1) << '\n';
}
```
Output:
```
ฮ (0.5,0) = 1.685750
K(0.5) = 1.685750
ฮ (0,0) = 1.570796
ฯ/2 = 1.570796
ฮ (0.5,1) = inf
```
### See also
| | |
| --- | --- |
| [ellint\_3ellint\_3fellint\_3l](ellint_3 "cpp/numeric/special functions/ellint 3")
(C++17)(C++17)(C++17) | (incomplete) elliptic integral of the third kind (function) |
### External links
[Weisstein, Eric W. "Elliptic Integral of the Third Kind."](http://mathworld.wolfram.com/EllipticIntegraloftheThirdKind.html) From MathWorld โ A Wolfram Web Resource.
| programming_docs |
cpp std::assoc_legendre, std::assoc_legendref, std::assoc_legendrel std::assoc\_legendre, std::assoc\_legendref, std::assoc\_legendrel
==================================================================
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
|
```
double assoc_legendre( unsigned int n, unsigned int m, double x );
float assoc_legendre( unsigned int n, unsigned int m, float x );
long double assoc_legendre( unsigned int n, unsigned int m, long double x );
float assoc_legendref( unsigned int n, unsigned int m, float x );
long double assoc_legendrel( unsigned int n, unsigned int m, long double x );
```
| (1) | (since C++17) |
|
```
double assoc_legendre( unsigned int n, unsigned int m, IntegralType x );
```
| (2) | (since C++17) |
1) Computes the [associated Legendre polynomials](https://en.wikipedia.org/wiki/Associated_Legendre_polynomials "enwiki:Associated Legendre polynomials") of the degree `n`, order `m`, and argument `x`
2) A set of overloads or a function template accepting an argument of any [integral type](../../types/is_integral "cpp/types/is integral"). Equivalent to (1) after casting the argument to `double`. ### Parameters
| | | |
| --- | --- | --- |
| n | - | the degree of the polynomial, a value of unsigned integer type |
| m | - | the order of the polynomial, a value of unsigned integer type |
| x | - | the argument, a value of a floating-point or integral type |
### Return value
If no errors occur, value of the associated Legendre polynomial \(\mathsf{P}\_n^m\)Pm
n of `x`, that is \((1 - x^2) ^ {m/2} \: \frac{ \mathsf{d} ^ m}{ \mathsf{d}x ^ m} \, \mathsf{P}\_n(x)\)(1-x2
)m/2
dm/dxmP
n(x), is returned (where \(\mathsf{P}\_n(x)\)P
n(x) is the unassociated Legendre polynomial, `[std::legendre](http://en.cppreference.com/w/cpp/numeric/special_functions/legendre)(n, x)`). Note that the [Condon-Shortley phase term](http://mathworld.wolfram.com/Condon-ShortleyPhase.html) \((-1)^m\)(-1)m
is omitted from this definition.
### Error handling
Errors may be reported as specified in [math\_errhandling](../math/math_errhandling "cpp/numeric/math/math errhandling").
* If the argument is NaN, NaN is returned and domain error is not reported
* If |x| > 1, a domain error may occur
* If `n` is greater or equal to 128, the behavior is implementation-defined.
### Notes
Implementations that do not support C++17, but support [ISO 29124:2010](https://en.cppreference.com/w/cpp/experimental/special_math "cpp/experimental/special math"), provide this function if `__STDCPP_MATH_SPEC_FUNCS__` is defined by the implementation to a value at least 201003L and if the user defines `__STDCPP_WANT_MATH_SPEC_FUNCS__` before including any standard library headers.
Implementations that do not support ISO 29124:2010 but support TR 19768:2007 (TR1), provide this function in the header `tr1/cmath` and namespace `std::tr1`.
An implementation of this function is also [available in boost.math](http://www.boost.org/doc/libs/release/libs/math/doc/html/math_toolkit/sf_poly/legendre.html) as `boost::math::legendre_p`, except that the boost.math definition includes the Condon-Shortley phase term.
The first few associated Legendre polynomials are:
* assoc\_legendre(0, 0, x) = 1
* assoc\_legendre(1, 0, x) = x
* assoc\_legendre(1, 1, x) = (1-x2
)1/2
* assoc\_legendre(2, 0, x) = 1/2(3x2
-1)
* assoc\_legendre(2, 1, x) = 3x(1-x2
)1/2
* assoc\_legendre(2, 2, x) = 3(1-x2
)
### Example
```
#include <cmath>
#include <iostream>
double P20(double x) { return 0.5*(3*x*x-1); }
double P21(double x) { return 3.0*x*std::sqrt(1-x*x); }
double P22(double x) { return 3*(1-x*x); }
int main()
{
// spot-checks
std::cout << std::assoc_legendre(2, 0, 0.5) << '=' << P20(0.5) << '\n'
<< std::assoc_legendre(2, 1, 0.5) << '=' << P21(0.5) << '\n'
<< std::assoc_legendre(2, 2, 0.5) << '=' << P22(0.5) << '\n';
}
```
Output:
```
-0.125=-0.125
1.29904=1.29904
2.25=2.25
```
### See also
| | |
| --- | --- |
| [legendrelegendreflegendrel](legendre "cpp/numeric/special functions/legendre")
(C++17)(C++17)(C++17) | Legendre polynomials (function) |
### External links
[Weisstein, Eric W. "Associated Legendre Polynomial."](http://mathworld.wolfram.com/AssociatedLegendrePolynomial.html) From MathWorld--A Wolfram Web Resource.
cpp std::comp_ellint_2, std::comp_ellint_2f, std::comp_ellint_2l std::comp\_ellint\_2, std::comp\_ellint\_2f, std::comp\_ellint\_2l
==================================================================
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
|
```
double comp_ellint_2( double k);
float comp_ellint_2( float k );
long double comp_ellint_2( long double k );
float comp_ellint_2f( float k );
long double comp_ellint_2l( long double k );
```
| (1) | (since C++17) |
|
```
double comp_ellint_2( IntegralType k );
```
| (2) | (since C++17) |
1) Computes the [complete elliptic integral of the second kind](https://en.wikipedia.org/wiki/Elliptic_integral#Complete_elliptic_integral_of_the_second_kind "enwiki:Elliptic integral") of `k`.
2) A set of overloads or a function template accepting an argument of any [integral type](../../types/is_integral "cpp/types/is integral"). Equivalent to (1) after casting the argument to `double`. ### Parameters
| | | |
| --- | --- | --- |
| k | - | elliptic modulus or eccentricity (a value of a floating-point or integral type) |
### Return value
If no errors occur, value of the complete elliptic integral of the second kind of `k`, that is `ellint_2(k,ฯ/2)`, is returned.
### Error handling
Errors may be reported as specified in [math\_errhandling](../math/math_errhandling "cpp/numeric/math/math errhandling").
* If the argument is NaN, NaN is returned and domain error is not reported
* If |k|>1, a domain error may occur
### Notes
Implementations that do not support C++17, but support [ISO 29124:2010](https://en.cppreference.com/w/cpp/experimental/special_math "cpp/experimental/special math"), provide this function if `__STDCPP_MATH_SPEC_FUNCS__` is defined by the implementation to a value at least 201003L and if the user defines `__STDCPP_WANT_MATH_SPEC_FUNCS__` before including any standard library headers.
Implementations that do not support ISO 29124:2010 but support TR 19768:2007 (TR1), provide this function in the header `tr1/cmath` and namespace `std::tr1`.
An implementation of this function is also [available in boost.math](http://www.boost.org/doc/libs/release/libs/math/doc/html/math_toolkit/ellint/ellint_2.html).
The perimeter of an ellipse with eccentricity `k` and semimajor axis a equals 4aE(k), where E is `std::comp_ellint_2`. When eccentricity equals 0, the ellipse degenerates to a circle with radius a and the perimeter equals 2ฯa, so E(0) = ฯ/2. When eccentricity equals 1, the ellipse degenerates to a line of length 2a, whose perimeter is 4a, so E(1) = 1.
### Example
```
#include <cmath>
#include <iostream>
int main()
{
double hpi = std::acos(-1)/2;
std::cout << "E(0) = " << std::comp_ellint_2(0) << '\n'
<< "ฯ/2 = " << hpi << '\n'
<< "E(1) = " << std::comp_ellint_2(1) << '\n'
<< "E(1, ฯ/2) = " << std::ellint_2(1, hpi) << '\n';
}
```
Output:
```
E(0) = 1.5708
ฯ/2 = 1.5708
E(1) = 1
E(1, ฯ/2) = 1
```
### See also
| | |
| --- | --- |
| [ellint\_2ellint\_2fellint\_2l](ellint_2 "cpp/numeric/special functions/ellint 2")
(C++17)(C++17)(C++17) | (incomplete) elliptic integral of the second kind (function) |
### External links
[Weisstein, Eric W. "Complete Elliptic Integral of the Second Kind."](http://mathworld.wolfram.com/CompleteEllipticIntegraloftheSecondKind.html) From MathWorld โ A Wolfram Web Resource.
cpp std::sph_bessel, std::sph_besself, std::sph_bessell std::sph\_bessel, std::sph\_besself, std::sph\_bessell
======================================================
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
|
```
double sph_bessel ( unsigned n, double x );
float sph_bessel ( unsigned n, float x );
long double sph_bessel ( unsigned n, long double x );
float sph_besself( unsigned n, float x );
long double sph_bessell( unsigned n, long double x );
```
| (1) | (since C++17) |
|
```
double sph_bessel( unsigned n, IntegralType x );
```
| (2) | (since C++17) |
1) Computes the [spherical Bessel function of the first kind](https://en.wikipedia.org/wiki/Bessel_function#Spherical_Bessel_functions:_jn.2C_yn "enwiki:Bessel function") of `n` and `x`.
2) A set of overloads or a function template accepting an argument of any [integral type](../../types/is_integral "cpp/types/is integral"). Equivalent to (1) after casting the argument to `double`. ### Parameters
| | | |
| --- | --- | --- |
| n | - | the order of the function |
| x | - | the argument of the function |
### Return value
If no errors occur, returns the value of the spherical Bessel function of the first kind of `n` and `x`, that is j
n(x) = (ฯ/2x)1/2
J
n+1/2(x) where J
n(x) is `[std::cyl\_bessel\_j](http://en.cppreference.com/w/cpp/numeric/special_functions/cyl_bessel_j)(n,x)` and xโฅ0.
### Error handling
Errors may be reported as specified in [math\_errhandling](../math/math_errhandling "cpp/numeric/math/math errhandling").
* If the argument is NaN, NaN is returned and domain error is not reported
* If n>=128, the behavior is implementation-defined
### Notes
Implementations that do not support C++17, but support [ISO 29124:2010](https://en.cppreference.com/w/cpp/experimental/special_math "cpp/experimental/special math"), provide this function if `__STDCPP_MATH_SPEC_FUNCS__` is defined by the implementation to a value at least 201003L and if the user defines `__STDCPP_WANT_MATH_SPEC_FUNCS__` before including any standard library headers.
Implementations that do not support ISO 29124:2010 but support TR 19768:2007 (TR1), provide this function in the header `tr1/cmath` and namespace `std::tr1`.
An implementation of this function is also available in [boost.math](http://www.boost.org/doc/libs/release/libs/math/doc/html/math_toolkit/bessel/sph_bessel.html).
### Example
```
#include <cmath>
#include <iostream>
int main()
{
// spot check for n == 1
double x = 1.2345;
std::cout << "j_1(" << x << ") = " << std::sph_bessel(1, x) << '\n';
// exact solution for j_1
std::cout << "(sin x)/x^2 - (cos x)/x = " << std::sin(x)/(x*x) - std::cos(x)/x << '\n';
}
```
Output:
```
j_1(1.2345) = 0.352106
(sin x)/x^2 - (cos x)/x = 0.352106
```
### See also
| | |
| --- | --- |
| [cyl\_bessel\_jcyl\_bessel\_jfcyl\_bessel\_jl](cyl_bessel_j "cpp/numeric/special functions/cyl bessel j")
(C++17)(C++17)(C++17) | cylindrical Bessel functions (of the first kind) (function) |
| [sph\_neumannsph\_neumannfsph\_neumannl](sph_neumann "cpp/numeric/special functions/sph neumann")
(C++17)(C++17)(C++17) | spherical Neumann functions (function) |
### External links
[Weisstein, Eric W. "Spherical Bessel Function of the First Kind."](http://mathworld.wolfram.com/SphericalBesselFunctionoftheFirstKind.html) From MathWorld โ A Wolfram Web Resource.
cpp std::beta, std::betaf, std::betal std::beta, std::betaf, std::betal
=================================
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
|
```
double beta( double x, double y );
float betaf( float x, float y );
long double betal( long double x, long double y );
```
| (1) | (since C++17) |
|
```
Promoted beta( Arithmetic x, Arithmetic y );
```
| (2) | (since C++17) |
1) Computes the [beta function](https://en.wikipedia.org/wiki/Beta_function "enwiki:Beta function") of `x` and `y`.
2) A set of overloads or a function template for all combinations of arguments of arithmetic type not covered by (1). If any argument has [integral type](../../types/is_integral "cpp/types/is integral"), it is cast to `double`. If any argument is `long double`, then the return type `Promoted` is also `long double`, otherwise the return type is always `double`. ### Parameters
| | | |
| --- | --- | --- |
| x, y | - | values of a floating-point or integral type |
### Return value
If no errors occur, value of the beta function of `x` and `y`, that is \(\int\_{0}^{1}{ {t}^{x-1}{(1-t)}^{y-1}\mathsf{d}t}\)โซ1
0tx-1
(1-t)(y-1)
d*t*, or, equivalently, \(\frac{\Gamma(x)\Gamma(y)}{\Gamma(x+y)}\)ฮ(x)ฮ(y)/ฮ(x+y) is returned. ### Error handling
Errors may be reported as specified in [math\_errhandling](../math/math_errhandling "cpp/numeric/math/math errhandling").
* If any argument is NaN, NaN is returned and domain error is not reported
* The function is only required to be defined where both `x` and `y` are greater than zero, and is allowed to report a domain error otherwise.
### Notes
Implementations that do not support C++17, but support [ISO 29124:2010](https://en.cppreference.com/w/cpp/experimental/special_math "cpp/experimental/special math"), provide this function if `__STDCPP_MATH_SPEC_FUNCS__` is defined by the implementation to a value at least 201003L and if the user defines `__STDCPP_WANT_MATH_SPEC_FUNCS__` before including any standard library headers.
Implementations that do not support ISO 29124:2010 but support TR 19768:2007 (TR1), provide this function in the header `tr1/cmath` and namespace `std::tr1`.
An implementation of this function is also [available in boost.math](http://www.boost.org/doc/libs/release/libs/math/doc/html/math_toolkit/sf_beta/beta_function.html).
`beta(x, y)` equals `beta(y, x)` When `x` and `y` are positive integers, beta(x,y) equals \(\frac{(x-1)!(y-1)!}{(x+y-1)!}\).
(x-1)!(y-1)!/(x+y-1)!.
Binomial coefficients can be expressed in terms of the beta function: \(\binom{n}{k} = \frac{1}{(n+1)B(n-k+1,k+1)}\).
โ
โ
โn
kโ
โ
โ =1/(n+1)ฮ(n-k+1,k+1) ### Example
```
#include <cmath>
#include <string>
#include <iostream>
#include <iomanip>
double binom(int n, int k) { return 1/((n+1)*std::beta(n-k+1,k+1)); }
int main()
{
std::cout << "Pascal's triangle:\n";
for(int n = 1; n < 10; ++n) {
std::cout << std::string(20-n*2, ' ');
for(int k = 1; k < n; ++k)
std::cout << std::setw(3) << binom(n,k) << ' ';
std::cout << '\n';
}
}
```
Output:
```
Pascal's triangle:
2
3 3
4 6 4
5 10 10 5
6 15 20 15 6
7 21 35 35 21 7
8 28 56 70 56 28 8
9 36 84 126 126 84 36 9
```
### See also
| | |
| --- | --- |
| [tgammatgammaftgammal](../math/tgamma "cpp/numeric/math/tgamma")
(C++11)(C++11)(C++11) | gamma function (function) |
### External links
[Weisstein, Eric W. "Beta Function."](http://mathworld.wolfram.com/BetaFunction.html) From MathWorld--A Wolfram Web Resource.
cpp std::assoc_laguerre, std::assoc_laguerref, std::assoc_laguerrel std::assoc\_laguerre, std::assoc\_laguerref, std::assoc\_laguerrel
==================================================================
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
|
```
double assoc_laguerre( unsigned int n, unsigned int m, double x );
float assoc_laguerre( unsigned int n, unsigned int m, float x );
long double assoc_laguerre( unsigned int n, unsigned int m, long double x );
float assoc_laguerref( unsigned int n, unsigned int m, float x );
long double assoc_laguerrel( unsigned int n, unsigned int m, long double x );
```
| (1) | (since C++17) |
|
```
double assoc_laguerre( unsigned int n, unsigned int m, IntegralType x );
```
| (2) | (since C++17) |
1) Computes the [associated Laguerre polynomials](https://en.wikipedia.org/wiki/Laguerre_polynomials#Generalized_Laguerre_polynomials "enwiki:Laguerre polynomials") of the degree `n`, order `m`, and argument `x`
2) A set of overloads or a function template accepting an argument of any [integral type](../../types/is_integral "cpp/types/is integral"). Equivalent to (1) after casting the argument to `double`. ### Parameters
| | | |
| --- | --- | --- |
| n | - | the degree of the polymonial, a value of unsigned integer type |
| m | - | the order of the polynomial, a value of unsigned integer type |
| x | - | the argument, a value of a floating-point or integral type |
### Return value
If no errors occur, value of the associated Laguerre polynomial of `x`, that is \((-1)^m \: \frac{ \mathsf{d} ^ m}{ \mathsf{d}x ^ m} \, \mathsf{L}\_{n+m}(x)\)(-1)m
dm/dxmL
n+m(x), is returned (where \(\mathsf{L}\_{n+m}(x)\)L
n+m(x) is the unassociated Laguerre polynomial, `[std::laguerre](http://en.cppreference.com/w/cpp/numeric/special_functions/laguerre)(n+m, x)`). ### Error handling
Errors may be reported as specified in [math\_errhandling](../math/math_errhandling "cpp/numeric/math/math errhandling").
* If the argument is NaN, NaN is returned and domain error is not reported
* If `x` is negative, a domain error may occur
* If `n` or `m` is greater or equal to 128, the behavior is implementation-defined.
### Notes
Implementations that do not support C++17, but support [ISO 29124:2010](https://en.cppreference.com/w/cpp/experimental/special_math "cpp/experimental/special math"), provide this function if `__STDCPP_MATH_SPEC_FUNCS__` is defined by the implementation to a value at least 201003L and if the user defines `__STDCPP_WANT_MATH_SPEC_FUNCS__` before including any standard library headers.
Implementations that do not support ISO 29124:2010 but support TR 19768:2007 (TR1), provide this function in the header `tr1/cmath` and namespace `std::tr1`.
An implementation of this function is also [available in boost.math](http://www.boost.org/doc/libs/release/libs/math/doc/html/math_toolkit/sf_poly/laguerre.html).
The associated Laguerre polynomials are the polynomial solutions of the equation \(x\ddot{y} + (m+1-x)\dot{y} + ny = 0\)xy,,
+(m+1-x)y,
+ny = 0.
The first few are:
* assoc\_laguerre(0, m, x) = 1
* assoc\_laguerre(1, m, x) = -x + m + 1
* assoc\_laguerre(2, m, x) = 1/2[x2
-2(m+2)x+(m+1)(m+2)]
* assoc\_laguerre(3, m, x) = 1/6[-x3
-3(m+3)x2
-3(m+2)(m+3)x+(m+1)(m+2)(m+3)]
### Example
```
#include <cmath>
#include <iostream>
double L1(unsigned m, double x) { return -x + m + 1; }
double L2(unsigned m, double x) { return 0.5*(x*x-2*(m+2)*x+(m+1)*(m+2)); }
int main()
{
// spot-checks
std::cout << std::assoc_laguerre(1, 10, 0.5) << '=' << L1(10, 0.5) << '\n'
<< std::assoc_laguerre(2, 10, 0.5) << '=' << L2(10, 0.5) << '\n';
}
```
Output:
```
10.5=10.5
60.125=60.125
```
### See also
| | |
| --- | --- |
| [laguerrelaguerreflaguerrel](laguerre "cpp/numeric/special functions/laguerre")
(C++17)(C++17)(C++17) | Laguerre polynomials (function) |
### External links
[Weisstein, Eric W. "Associated Laguerre Polynomial."](http://mathworld.wolfram.com/AssociatedLaguerrePolynomial.html) From MathWorld โ A Wolfram Web Resource.
cpp std::sph_neumann, std::sph_neumannf, std::sph_neumannl std::sph\_neumann, std::sph\_neumannf, std::sph\_neumannl
=========================================================
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
|
```
double sph_neumann ( unsigned n, double x );
float sph_neumann ( unsigned n, float x );
long double sph_neumann ( unsigned n, long double x );
float sph_neumannf( unsigned n, float x );
long double sph_neumannl( unsigned n, long double x );
```
| (1) | (since C++17) |
|
```
double sph_neumann( unsigned n, IntegralType x );
```
| (2) | (since C++17) |
1) Computes the [spherical Bessel function of the second kind](https://en.wikipedia.org/wiki/Bessel_function#Spherical_Bessel_functions:_jn.2C_yn "enwiki:Bessel function"), also known as the spherical Neumann function, of `n` and `x`.
2) A set of overloads or a function template accepting an argument of any [integral type](../../types/is_integral "cpp/types/is integral"). Equivalent to (1) after casting the argument to `double`. ### Parameters
| | | |
| --- | --- | --- |
| n | - | the order of the function |
| x | - | the argument of the function |
### Return value
If no errors occur, returns the value of the spherical Bessel function of the second kind (spherical Neumann function) of `n` and `x`, that is n
n(x) = (ฯ/2x)1/2
N
n+1/2(x) where N
n(x) is `[std::cyl\_neumann](http://en.cppreference.com/w/cpp/numeric/special_functions/cyl_neumann)(n,x)` and xโฅ0.
### Error handling
Errors may be reported as specified in [math\_errhandling](../math/math_errhandling "cpp/numeric/math/math errhandling").
* If the argument is NaN, NaN is returned and domain error is not reported
* If n>=128, the behavior is implementation-defined
### Notes
Implementations that do not support C++17, but support [ISO 29124:2010](https://en.cppreference.com/w/cpp/experimental/special_math "cpp/experimental/special math"), provide this function if `__STDCPP_MATH_SPEC_FUNCS__` is defined by the implementation to a value at least 201003L and if the user defines `__STDCPP_WANT_MATH_SPEC_FUNCS__` before including any standard library headers.
Implementations that do not support ISO 29124:2010 but support TR 19768:2007 (TR1), provide this function in the header `tr1/cmath` and namespace `std::tr1`.
An implementation of this function is also available in [boost.math](http://www.boost.org/doc/libs/release/libs/math/doc/html/math_toolkit/bessel/sph_bessel.html).
### Example
```
#include <cmath>
#include <iostream>
int main()
{
// spot check for n == 1
double x = 1.2345;
std::cout << "n_1(" << x << ") = " << std::sph_neumann(1, x) << '\n';
// exact solution for n_1
std::cout << "-(cos x)/xยฒ - (sin x)/x = "
<< -std::cos(x)/(x*x) - std::sin(x)/x << '\n';
}
```
Output:
```
n_1(1.2345) = -0.981201
-(cos x)/xยฒ - (sin x)/x = -0.981201
```
### See also
| | |
| --- | --- |
| [cyl\_neumanncyl\_neumannfcyl\_neumannl](cyl_neumann "cpp/numeric/special functions/cyl neumann")
(C++17)(C++17)(C++17) | cylindrical Neumann functions (function) |
| [sph\_besselsph\_besselfsph\_bessell](sph_bessel "cpp/numeric/special functions/sph bessel")
(C++17)(C++17)(C++17) | spherical Bessel functions (of the first kind) (function) |
### External links
[Weisstein, Eric W. "Spherical Bessel Function of the Second Kind."](http://mathworld.wolfram.com/SphericalBesselFunctionoftheSecondKind.html) From MathWorld โ A Wolfram Web Resource.
| programming_docs |
cpp std::ellint_2, std::ellint_2f, std::ellint_2l std::ellint\_2, std::ellint\_2f, std::ellint\_2l
================================================
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
|
```
double ellint_2( double k, double ฯ );
float ellint_2f( float k, float ฯ );
long double ellint_2l( long double k, long double ฯ );
```
| (1) | (since C++17) |
|
```
Promoted ellint_2( Arithmetic k, Arithmetic ฯ );
```
| (2) | (since C++17) |
1) Computes the [incomplete elliptic integral of the second kind](https://en.wikipedia.org/wiki/Elliptic_integral#Incomplete_elliptic_integral_of_the_second_kind "enwiki:Elliptic integral") of `k` and `ฯ`.
2) A set of overloads or a function template for all combinations of arguments of arithmetic type not covered by (1). If any argument has [integral type](../../types/is_integral "cpp/types/is integral"), it is cast to `double`. If any argument is `long double`, then the return type `Promoted` is also `long double`, otherwise the return type is always `double`. ### Parameters
| | | |
| --- | --- | --- |
| k | - | elliptic modulus or eccentricity (a value of a floating-point or integral type) |
| ฯ | - | Jacobi amplitude (a value of floating-point or integral type, measured in radians) |
### Return value
If no errors occur, value of the incomplete elliptic integral of the second kind of `k` and `ฯ`, that is โซฯ
0โ1-k2
sin2
ฮธdฮธ, is returned.
### Error handling
Errors may be reported as specified in [`math_errhandling`](../math/math_errhandling "cpp/numeric/math/math errhandling"):
* If the argument is NaN, NaN is returned and domain error is not reported
* If |k|>1, a domain error may occur
### Notes
Implementations that do not support C++17, but support [ISO 29124:2010](https://en.cppreference.com/w/cpp/experimental/special_math "cpp/experimental/special math"), provide this function if `__STDCPP_MATH_SPEC_FUNCS__` is defined by the implementation to a value at least 201003L and if the user defines `__STDCPP_WANT_MATH_SPEC_FUNCS__` before including any standard library headers.
Implementations that do not support ISO 29124:2010 but support TR 19768:2007 (TR1), provide this function in the header `tr1/cmath` and namespace `std::tr1`.
An implementation of this function is also available in [boost.math](http://www.boost.org/doc/libs/release/libs/math/doc/html/math_toolkit/ellint/ellint_2.html).
### Example
```
#include <cmath>
#include <iostream>
int main()
{
double hpi = std::acos(-1)/2;
std::cout << "E(0,ฯ/2) = " << std::ellint_2(0, hpi) << '\n'
<< "E(0,-ฯ/2) = " << std::ellint_2(0, -hpi) << '\n'
<< "ฯ/2 = " << hpi << '\n'
<< "E(0.7,0) = " << std::ellint_2(0.7, 0) << '\n'
<< "E(1,ฯ/2) = " << std::ellint_2(1, hpi) << '\n';
}
```
Output:
```
E(0,ฯ/2) = 1.5708
E(0,-ฯ/2) = -1.5708
ฯ/2 = 1.5708
E(0.7,0) = 0
E(1,ฯ/2) = 1
```
### See also
| | |
| --- | --- |
| [comp\_ellint\_2comp\_ellint\_2fcomp\_ellint\_2l](comp_ellint_2 "cpp/numeric/special functions/comp ellint 2")
(C++17)(C++17)(C++17) | (complete) elliptic integral of the second kind (function) |
### External links
[Weisstein, Eric W. "Elliptic Integral of the Second Kind."](http://mathworld.wolfram.com/EllipticIntegraloftheSecondKind.html) From MathWorld โ A Wolfram Web Resource.
cpp std::cyl_bessel_k, std::cyl_bessel_kf, std::cyl_bessel_kl std::cyl\_bessel\_k, std::cyl\_bessel\_kf, std::cyl\_bessel\_kl
===============================================================
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
|
```
double cyl_bessel_k( double ฮฝ, double x );
float cyl_bessel_kf( float ฮฝ, float x );
long double cyl_bessel_kl( long double ฮฝ, long double x );
```
| (1) | (since C++17) |
|
```
Promoted cyl_bessel_k( Arithmetic ฮฝ, Arithmetic x );
```
| (2) | (since C++17) |
1) Computes the [irregular modified cylindrical Bessel function](https://en.wikipedia.org/wiki/Bessel_function#Modified_Bessel_functions:_I.CE.B1_.2C_K.CE.B1 "enwiki:Bessel function") (also known as modified Bessel function of the second kind) of `ฮฝ` and `x`.
2) A set of overloads or a function template for all combinations of arguments of arithmetic type not covered by (1). If any argument has [integral type](../../types/is_integral "cpp/types/is integral"), it is cast to `double`. If any argument is `long double`, then the return type `Promoted` is also `long double`, otherwise the return type is always `double`. ### Parameters
| | | |
| --- | --- | --- |
| ฮฝ | - | the order of the function |
| x | - | the argument of the function |
### Return value
If no errors occur, value of the irregular modified cylindrical Bessel function (modified Bessel function of the second kind) of `ฮฝ` and `x`, is returned, that is K
ฮฝ(x) = ฯ/2I-ฮฝ(x)-Iฮฝ(x)/sin(ฮฝฯ) (where I
ฮฝ(x) is `[std::cyl\_bessel\_i](http://en.cppreference.com/w/cpp/numeric/special_functions/cyl_bessel_i)(ฮฝ,x))` for xโฅ0 and non-integer ฮฝ; for integer ฮฝ a limit is used. ### Error handling
Errors may be reported as specified in [`math_errhandling`](../math/math_errhandling "cpp/numeric/math/math errhandling"):
* If the argument is NaN, NaN is returned and domain error is not reported
* If ฮฝ>=128, the behavior is implementation-defined
### Notes
Implementations that do not support C++17, but support [ISO 29124:2010](https://en.cppreference.com/w/cpp/experimental/special_math "cpp/experimental/special math"), provide this function if `__STDCPP_MATH_SPEC_FUNCS__` is defined by the implementation to a value at least 201003L and if the user defines `__STDCPP_WANT_MATH_SPEC_FUNCS__` before including any standard library headers.
Implementations that do not support ISO 29124:2010 but support TR 19768:2007 (TR1), provide this function in the header `tr1/cmath` and namespace `std::tr1`.
An implementation of this function is also [available in boost.math](http://www.boost.org/doc/libs/release/libs/math/doc/html/math_toolkit/bessel/mbessel.html).
### Example
```
#include <cmath>
#include <iostream>
int main()
{
double pi = std::acos(-1);
double x = 1.2345;
// spot check for ฮฝ == 0.5
std::cout << "K_.5(" << x << ") = " << std::cyl_bessel_k( .5, x) << '\n'
<< "calculated via I = " <<
(pi/2)*(std::cyl_bessel_i(-.5,x)
-std::cyl_bessel_i(.5,x))/std::sin(.5*pi) << '\n';
}
```
Output:
```
K_.5(1.2345) = 0.32823
calculated via I = 0.32823
```
### See also
| | |
| --- | --- |
| [cyl\_bessel\_icyl\_bessel\_ifcyl\_bessel\_il](cyl_bessel_i "cpp/numeric/special functions/cyl bessel i")
(C++17)(C++17)(C++17) | regular modified cylindrical Bessel functions (function) |
| [cyl\_bessel\_jcyl\_bessel\_jfcyl\_bessel\_jl](cyl_bessel_j "cpp/numeric/special functions/cyl bessel j")
(C++17)(C++17)(C++17) | cylindrical Bessel functions (of the first kind) (function) |
### External links
[Weisstein, Eric W. "Modified Bessel Function of the Second Kind."](http://mathworld.wolfram.com/ModifiedBesselFunctionoftheSecondKind.html) From MathWorld โ A Wolfram Web Resource.
cpp std::legendre, std::legendref, std::legendrel std::legendre, std::legendref, std::legendrel
=============================================
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
|
```
double legendre( unsigned int n, double x );
float legendre( unsigned int n, float x );
long double legendre( unsigned int n, long double x );
float legendref( unsigned int n, float x );
long double legendrel( unsigned int n, long double x );
```
| (1) | (since C++17) |
|
```
double legendre( unsigned int n, IntegralType x );
```
| (2) | (since C++17) |
1) Computes the unassociated [Legendre polynomials](https://en.wikipedia.org/wiki/Legendre_polynomials "enwiki:Legendre polynomials") of the degree `n` and argument `x`
2) A set of overloads or a function template accepting an argument of any [integral type](../../types/is_integral "cpp/types/is integral"). Equivalent to (1) after casting the argument to `double`. ### Parameters
| | | |
| --- | --- | --- |
| n | - | the degree of the polynomial |
| x | - | the argument, a value of a floating-point or integral type |
### Return value
If no errors occur, value of the order-`n` unassociated Legendre polynomial of `x`, that is \(\mathsf{P}\_n(x) = \frac{1}{2^n n!} \frac{\mathsf{d}^n}{\mathsf{d}x^n} (x^2-1)^n \)1/2nn!dn/dxn(x2
-1)n
, is returned. ### Error handling
Errors may be reported as specified in [math\_errhandling](../math/math_errhandling "cpp/numeric/math/math errhandling").
* If the argument is NaN, NaN is returned and domain error is not reported
* The function is not required to be defined for |x|>1
* If `n` is greater or equal than 128, the behavior is implementation-defined
### Notes
Implementations that do not support C++17, but support [ISO 29124:2010](https://en.cppreference.com/w/cpp/experimental/special_math "cpp/experimental/special math"), provide this function if `__STDCPP_MATH_SPEC_FUNCS__` is defined by the implementation to a value at least 201003L and if the user defines `__STDCPP_WANT_MATH_SPEC_FUNCS__` before including any standard library headers.
Implementations that do not support ISO 29124:2010 but support TR 19768:2007 (TR1), provide this function in the header `tr1/cmath` and namespace `std::tr1`.
An implementation of this function is also [available in boost.math](http://www.boost.org/doc/libs/release/libs/math/doc/html/math_toolkit/sf_poly/legendre.html).
The first few Legendre polynomials are:
* legendre(0, x) = 1
* legendre(1, x) = x
* legendre(2, x) = 1/2(3x2
-1)
* legendre(3, x) = 1/2(5x3
-3x)
* legendre(4, x) = 1/8(35x4
-30x2
+3)
### Example
```
#include <cmath>
#include <iostream>
double P3(double x) { return 0.5*(5*std::pow(x,3) - 3*x); }
double P4(double x) { return 0.125*(35*std::pow(x,4)-30*x*x+3); }
int main()
{
// spot-checks
std::cout << std::legendre(3, 0.25) << '=' << P3(0.25) << '\n'
<< std::legendre(4, 0.25) << '=' << P4(0.25) << '\n';
}
```
Output:
```
-0.335938=-0.335938
0.157715=0.157715
```
### See also
| | |
| --- | --- |
| [laguerrelaguerreflaguerrel](laguerre "cpp/numeric/special functions/laguerre")
(C++17)(C++17)(C++17) | Laguerre polynomials (function) |
| [hermitehermitefhermitel](hermite "cpp/numeric/special functions/hermite")
(C++17)(C++17)(C++17) | Hermite polynomials (function) |
### External links
[Weisstein, Eric W. "Legendre Polynomial."](http://mathworld.wolfram.com/LegendrePolynomial.html) From MathWorld--A Wolfram Web Resource.
cpp std::cyl_neumann, std::cyl_neumannf, std::cyl_neumannl std::cyl\_neumann, std::cyl\_neumannf, std::cyl\_neumannl
=========================================================
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
|
```
double cyl_neumann( double ฮฝ, double x );
float cyl_neumannf( float ฮฝ, float x );
long double cyl_neumannl( long double ฮฝ, long double x );
```
| (1) | (since C++17) |
|
```
Promoted cyl_neumann( Arithmetic ฮฝ, Arithmetic x );
```
| (2) | (since C++17) |
1) Computes the [cylindrical Neumann function](https://en.wikipedia.org/wiki/Bessel_function#Bessel_functions_of_the_second_kind:_Y.CE.B1 "enwiki:Bessel function") (also known as Bessel function of the second kind or Weber function) of `ฮฝ` and `x`.
2) A set of overloads or a function template for all combinations of arguments of arithmetic type not covered by (1). If any argument has [integral type](../../types/is_integral "cpp/types/is integral"), it is cast to `double`. If any argument is `long double`, then the return type `Promoted` is also `long double`, otherwise the return type is always `double`. ### Parameters
| | | |
| --- | --- | --- |
| ฮฝ | - | the order of the function |
| x | - | the argument of the function |
### Return value
If no errors occur, value of the cylindrical Neumann function (Bessel function of the second kind) of `ฮฝ` and `x`, is returned, that is N
ฮฝ(x) = Jฮฝ(x)cos(ฮฝฯ)-J-ฮฝ(x)/sin(ฮฝฯ) (where J
ฮฝ(x) is `[std::cyl\_bessel\_j](http://en.cppreference.com/w/cpp/numeric/special_functions/cyl_bessel_j)(ฮฝ,x)`) for xโฅ0 and non-integer ฮฝ; for integer ฮฝ a limit is used. ### Error handling
Errors may be reported as specified in [`math_errhandling`](../math/math_errhandling "cpp/numeric/math/math errhandling"):
* If the argument is NaN, NaN is returned and domain error is not reported
* If ฮฝ>=128, the behavior is implementation-defined
### Notes
Implementations that do not support C++17, but support [ISO 29124:2010](https://en.cppreference.com/w/cpp/experimental/special_math "cpp/experimental/special math"), provide this function if `__STDCPP_MATH_SPEC_FUNCS__` is defined by the implementation to a value at least 201003L and if the user defines `__STDCPP_WANT_MATH_SPEC_FUNCS__` before including any standard library headers.
Implementations that do not support ISO 29124:2010 but support TR 19768:2007 (TR1), provide this function in the header `tr1/cmath` and namespace `std::tr1`.
An implementation of this function is also available in [boost.math](http://www.boost.org/doc/libs/release/libs/math/doc/html/math_toolkit/bessel/bessel_first.html).
### Example
```
#include <cassert>
#include <cmath>
#include <iostream>
#include <numbers>
const double ฯ = std::numbers::pi; // or std::acos(-1) in pre C++20
// To calculate the cylindrical Neumann function via cylindrical Bessel function of the
// first kind we have to implement the Jโแตฅ, because the direct invocation of the
// std::cyl_bessel_j(ฮฝ,x), per formula above, for negative ฮฝ raises 'std::domain_error':
// Bad argument in __cyl_bessel_j.
double Jโแตฅ (double ฮฝ, double x) {
return std::cos(-ฮฝ*ฯ) * std::cyl_bessel_j(-ฮฝ,x)
-std::sin(-ฮฝ*ฯ) * std::cyl_neumann(-ฮฝ,x);
}
double Jโแตฅ (double ฮฝ, double x) { return std::cyl_bessel_j(ฮฝ,x); }
double Jแตฅ (double ฮฝ, double x) { return ฮฝ < 0.0 ? Jโแตฅ(ฮฝ,x) : Jโแตฅ(ฮฝ,x); }
int main()
{
std::cout << "spot checks for ฮฝ == 0.5\n" << std::fixed << std::showpos;
double ฮฝ = 0.5;
for (double x = 0.0; x <= 2.0; x += 0.333) {
const double n = std::cyl_neumann(ฮฝ, x);
const double j = (Jแตฅ(ฮฝ, x)*std::cos(ฮฝ*ฯ) - Jแตฅ(-ฮฝ, x)) / std::sin(ฮฝ*ฯ);
std::cout << "N_.5(" << x << ") = " << n << ", calculated via J = " << j << '\n';
assert(n == j);
}
}
```
Output:
```
spot checks for ฮฝ == 0.5
N_.5(+0.000000) = -inf, calculated via J = -inf
N_.5(+0.333000) = -1.306713, calculated via J = -1.306713
N_.5(+0.666000) = -0.768760, calculated via J = -0.768760
N_.5(+0.999000) = -0.431986, calculated via J = -0.431986
N_.5(+1.332000) = -0.163524, calculated via J = -0.163524
N_.5(+1.665000) = +0.058165, calculated via J = +0.058165
N_.5(+1.998000) = +0.233876, calculated via J = +0.233876
```
### See also
| | |
| --- | --- |
| [cyl\_bessel\_icyl\_bessel\_ifcyl\_bessel\_il](cyl_bessel_i "cpp/numeric/special functions/cyl bessel i")
(C++17)(C++17)(C++17) | regular modified cylindrical Bessel functions (function) |
| [cyl\_bessel\_jcyl\_bessel\_jfcyl\_bessel\_jl](cyl_bessel_j "cpp/numeric/special functions/cyl bessel j")
(C++17)(C++17)(C++17) | cylindrical Bessel functions (of the first kind) (function) |
| [cyl\_bessel\_kcyl\_bessel\_kfcyl\_bessel\_kl](cyl_bessel_k "cpp/numeric/special functions/cyl bessel k")
(C++17)(C++17)(C++17) | irregular modified cylindrical Bessel functions (function) |
### External links
[Weisstein, Eric W. "Bessel Function of the Second Kind."](http://mathworld.wolfram.com/BesselFunctionoftheSecondKind.html) From MathWorld โ A Wolfram Web Resource.
cpp std::cyl_bessel_j, std::cyl_bessel_jf, std::cyl_bessel_jl std::cyl\_bessel\_j, std::cyl\_bessel\_jf, std::cyl\_bessel\_jl
===============================================================
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
|
```
double cyl_bessel_j( double ฮฝ, double x );
float cyl_bessel_jf( float ฮฝ, float x );
long double cyl_bessel_jl( long double ฮฝ, long double x );
```
| (1) | (since C++17) |
|
```
Promoted cyl_bessel_j( Arithmetic ฮฝ, Arithmetic x );
```
| (2) | (since C++17) |
1) Computes the [cylindrical Bessel function of the first kind](https://en.wikipedia.org/wiki/Bessel_function#Bessel_functions_of_the_first_kind:_J.CE.B1 "enwiki:Bessel function") of `ฮฝ` and `x`.
2) A set of overloads or a function template for all combinations of arguments of arithmetic type not covered by (1). If any argument has [integral type](../../types/is_integral "cpp/types/is integral"), it is cast to `double`. If any argument is `long double`, then the return type `Promoted` is also `long double`, otherwise the return type is always `double`. ### Parameters
| | | |
| --- | --- | --- |
| ฮฝ | - | the order of the function |
| x | - | the argument of the function |
### Return value
If no errors occur, value of the cylindrical Bessel function of the first kind of `ฮฝ` and `x`, that is J
ฮฝ(x) = ฮฃโ
k=0(-1)k(x/2)ฮฝ+2k/k!ฮ(ฮฝ+k+1) (for xโฅ0), is returned. ### Error handling
Errors may be reported as specified in [`math_errhandling`](../math/math_errhandling "cpp/numeric/math/math errhandling"):
* If the argument is NaN, NaN is returned and domain error is not reported
* If ฮฝ>=128, the behavior is implementation-defined
### Notes
Implementations that do not support C++17, but support [ISO 29124:2010](https://en.cppreference.com/w/cpp/experimental/special_math "cpp/experimental/special math"), provide this function if `__STDCPP_MATH_SPEC_FUNCS__` is defined by the implementation to a value at least 201003L and if the user defines `__STDCPP_WANT_MATH_SPEC_FUNCS__` before including any standard library headers.
Implementations that do not support ISO 29124:2010 but support TR 19768:2007 (TR1), provide this function in the header `tr1/cmath` and namespace `std::tr1`.
An implementation of this function is also available in [boost.math](http://www.boost.org/doc/libs/release/libs/math/doc/html/math_toolkit/bessel/bessel_first.html).
### Example
```
#include <cmath>
#include <iostream>
int main()
{
// spot check for ฮฝ == 0
double x = 1.2345;
std::cout << "J_0(" << x << ") = " << std::cyl_bessel_j(0, x) << '\n';
// series expansion for J_0
double fct = 1;
double sum = 0;
for(int k = 0; k < 6; fct*=++k) {
sum += std::pow(-1, k)*std::pow((x/2),2*k) / std::pow(fct,2);
std::cout << "sum = " << sum << '\n';
}
}
```
Output:
```
J_0(1.2345) = 0.653792
sum = 1
sum = 0.619002
sum = 0.655292
sum = 0.653756
sum = 0.653793
sum = 0.653792
```
### See also
| | |
| --- | --- |
| [cyl\_bessel\_icyl\_bessel\_ifcyl\_bessel\_il](cyl_bessel_i "cpp/numeric/special functions/cyl bessel i")
(C++17)(C++17)(C++17) | regular modified cylindrical Bessel functions (function) |
### External links
[Weisstein, Eric W. "Bessel Function of the First Kind."](http://mathworld.wolfram.com/BesselFunctionoftheFirstKind.html) From MathWorld โ A Wolfram Web Resource.
cpp std::hermite, std::hermitef, std::hermitel std::hermite, std::hermitef, std::hermitel
==========================================
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
|
```
double hermite( unsigned int n, double x );
float hermite( unsigned int n, float x );
long double hermite( unsigned int n, long double x );
float hermitef( unsigned int n, float x );
long double hermitel( unsigned int n, long double x );
```
| (1) | (since C++17) |
|
```
double hermite( unsigned int n, IntegralType x );
```
| (2) | (since C++17) |
1) Computes the (physicist's) [Hermite polynomials](https://en.wikipedia.org/wiki/Hermite_polynomials "enwiki:Hermite polynomials") of the degree `n` and argument `x`
2) A set of overloads or a function template accepting an argument of any [integral type](../../types/is_integral "cpp/types/is integral"). Equivalent to (1) after casting the argument to `double`. ### Parameters
| | | |
| --- | --- | --- |
| n | - | the degree of the polynomial |
| x | - | the argument, a value of a floating-point or integral type |
### Return value
If no errors occur, value of the order-`n` Hermite polynomial of `x`, that is (-1)n
*e*x2dn/dxn*e*-x2, is returned. ### Error handling
Errors may be reported as specified in [math\_errhandling](../math/math_errhandling "cpp/numeric/math/math errhandling").
* If the argument is NaN, NaN is returned and domain error is not reported
* If `n` is greater or equal than 128, the behavior is implementation-defined
### Notes
Implementations that do not support C++17, but support [ISO 29124:2010](https://en.cppreference.com/w/cpp/experimental/special_math "cpp/experimental/special math"), provide this function if `__STDCPP_MATH_SPEC_FUNCS__` is defined by the implementation to a value at least 201003L and if the user defines `__STDCPP_WANT_MATH_SPEC_FUNCS__` before including any standard library headers.
Implementations that do not support ISO 29124:2010 but support TR 19768:2007 (TR1), provide this function in the header `tr1/cmath` and namespace `std::tr1`.
An implementation of this function is also [available in boost.math](http://www.boost.org/doc/libs/release/libs/math/doc/html/math_toolkit/sf_poly/hermite.html).
The Hermite polynomials are the polynomial solutions of the equation u,,
-2xu,
= -2nu.
The first few are:
* hermite(0, x) = 1
* hermite(1, x) = 2x
* hermite(2, x) = 4x2
-2
* hermite(3, x) = 8x3
-12x
* hermite(4, x) = 16x4
-48x2
+12
### Example
```
#include <cmath>
#include <iostream>
double H3(double x) { return 8*std::pow(x,3) - 12*x; }
double H4(double x) { return 16*std::pow(x,4)-48*x*x+12; }
int main()
{
// spot-checks
std::cout << std::hermite(3, 10) << '=' << H3(10) << '\n'
<< std::hermite(4, 10) << '=' << H4(10) << '\n';
}
```
Output:
```
7880=7880
155212=155212
```
### See also
| | |
| --- | --- |
| [laguerrelaguerreflaguerrel](laguerre "cpp/numeric/special functions/laguerre")
(C++17)(C++17)(C++17) | Laguerre polynomials (function) |
| [legendrelegendreflegendrel](legendre "cpp/numeric/special functions/legendre")
(C++17)(C++17)(C++17) | Legendre polynomials (function) |
### External links
[Weisstein, Eric W. "Hermite Polynomial."](http://mathworld.wolfram.com/HermitePolynomial.html) From MathWorld--A Wolfram Web Resource.
| programming_docs |
cpp std::expint, std::expintf, std::expintl std::expint, std::expintf, std::expintl
=======================================
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
|
```
double expint( double arg );
float expint( float arg );
long double expint( long double arg );
float expintf( float arg );
long double expintl( long double arg );
```
| (1) | (since C++17) |
|
```
double expint( IntegralType arg );
```
| (2) | (since C++17) |
1) Computes the [exponential integral](https://en.wikipedia.org/wiki/Exponential_integral "enwiki:Exponential integral") of `arg`.
2) A set of overloads or a function template accepting an argument of any [integral type](../../types/is_integral "cpp/types/is integral"). Equivalent to (1) after casting the argument to `double`. ### Parameters
| | | |
| --- | --- | --- |
| arg | - | value of a floating-point or [Integral type](../../types/is_integral "cpp/types/is integral") |
### Return value
If no errors occur, value of the exponential integral of `arg`, that is -โซโ
-arge-t/td*t*, is returned. ### Error handling
Errors may be reported as specified in [math\_errhandling](../math/math_errhandling "cpp/numeric/math/math errhandling").
* If the argument is NaN, NaN is returned and domain error is not reported
* If the argument is ยฑ0, -โ is returned
### Notes
Implementations that do not support C++17, but support [ISO 29124:2010](https://en.cppreference.com/w/cpp/experimental/special_math "cpp/experimental/special math"), provide this function if `__STDCPP_MATH_SPEC_FUNCS__` is defined by the implementation to a value at least 201003L and if the user defines `__STDCPP_WANT_MATH_SPEC_FUNCS__` before including any standard library headers.
Implementations that do not support ISO 29124:2010 but support TR 19768:2007 (TR1), provide this function in the header `tr1/cmath` and namespace `std::tr1`.
An implementation of this function is also [available in boost.math](http://www.boost.org/doc/libs/release/libs/math/doc/html/math_toolkit/expint/expint_i.html).
### Example
```
#include <algorithm>
#include <iostream>
#include <vector>
#include <cmath>
template <int Height = 5, int BarWidth = 1, int Padding = 1, int Offset = 0, class Seq>
void draw_vbars(Seq&& s, const bool DrawMinMax = true) {
static_assert((Height > 0) && (BarWidth > 0) && (Padding >= 0) && (Offset >= 0));
auto cout_n = [](auto&& v, int n = 1) { while (n-- > 0) std::cout << v; };
const auto [min, max] = std::minmax_element(std::cbegin(s), std::cend(s));
std::vector<std::div_t> qr;
for (typedef decltype(*cbegin(s)) V; V e : s)
qr.push_back(std::div(std::lerp(V(0), Height*8, (e - *min)/(*max - *min)), 8));
for (auto h{Height}; h-- > 0; cout_n('\n')) {
cout_n(' ', Offset);
for (auto dv : qr) {
const auto q{dv.quot}, r{dv.rem};
unsigned char d[] { 0xe2, 0x96, 0x88, 0 }; // Full Block: 'โ'
q < h ? d[0] = ' ', d[1] = 0 : q == h ? d[2] -= (7 - r) : 0;
cout_n(d, BarWidth), cout_n(' ', Padding);
}
if (DrawMinMax && Height > 1)
Height - 1 == h ? std::cout << "โฌ " << *max:
h ? std::cout << "โ "
: std::cout << "โด " << *min;
}
}
int main()
{
std::cout << "Ei(0) = " << std::expint(0) << '\n'
<< "Ei(1) = " << std::expint(1) << '\n'
<< "Gompertz constant = " << -std::exp(1)*std::expint(-1) << '\n';
std::vector<float> v;
for (float x{1.f}; x < 8.8f; x += 0.3565f)
v.push_back(std::expint(x));
draw_vbars<9,1,1>(v);
}
```
Output:
```
Ei(0) = -inf
Ei(1) = 1.89512
Gompertz constant = 0.596347
โ โฌ 666.505
โ โ
โ โ โ
โ โ โ
โ โ โ โ
โ โ โ โ โ
โ โ โ โ โ โ โ
โ โ
โ โ โ โ โ โ โ
โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โด 1.89512
```
### External links
[Weisstein, Eric W. "Exponential Integral."](http://mathworld.wolfram.com/ExponentialIntegral.html) From MathWorld--A Wolfram Web Resource.
cpp std::ellint_3, std::ellint_3f, std::ellint_3l std::ellint\_3, std::ellint\_3f, std::ellint\_3l
================================================
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
|
```
double ellint_3( double k, double ฮฝ, double ฯ );
float ellint_3f( float k, float ฮฝ, float ฯ );
long double ellint_3l( long double k, long double ฮฝ, long double ฯ );
```
| (1) | (since C++17) |
|
```
Promoted ellint_3( Arithmetic k, Arithmetic ฮฝ, Arithmetic ฯ );
```
| (2) | (since C++17) |
1) Computes the [incomplete elliptic integral of the third kind](https://en.wikipedia.org/wiki/Elliptic_integral#Incomplete_elliptic_integral_of_the_third_kind "enwiki:Elliptic integral") of `k`, `ฮฝ`, and `ฯ`.
2) A set of overloads or a function template for all combinations of arguments of arithmetic type not covered by (1). If any argument has [integral type](../../types/is_integral "cpp/types/is integral"), it is cast to `double`. If any argument is `long double`, then the return type `Promoted` is also `long double`, otherwise the return type is always `double`. ### Parameters
| | | |
| --- | --- | --- |
| k | - | elliptic modulus or eccentricity (a value of a floating-point or integral type) |
| ฮฝ | - | elliptic characteristic (a value of floating-point or integral type) |
| ฯ | - | Jacobi amplitude (a value of floating-point or integral type, measured in radians) |
### Return value
If no errors occur, value of the incomplete elliptic integral of the third kind of `k`, `ฮฝ`, and `ฯ`, that is โซฯ
0dฮธ/(1-ฮฝsin2ฮธ)โ1-k2sin2ฮธ, is returned. ### Error handling
Errors may be reported as specified in [`math_errhandling`](../math/math_errhandling "cpp/numeric/math/math errhandling"):
* If the argument is NaN, NaN is returned and domain error is not reported
* If |k|>1, a domain error may occur
### Notes
Implementations that do not support C++17, but support [ISO 29124:2010](https://en.cppreference.com/w/cpp/experimental/special_math "cpp/experimental/special math"), provide this function if `__STDCPP_MATH_SPEC_FUNCS__` is defined by the implementation to a value at least 201003L and if the user defines `__STDCPP_WANT_MATH_SPEC_FUNCS__` before including any standard library headers.
Implementations that do not support ISO 29124:2010 but support TR 19768:2007 (TR1), provide this function in the header `tr1/cmath` and namespace `std::tr1`.
An implementation of this function is also available in [boost.math](http://www.boost.org/doc/libs/release/libs/math/doc/html/math_toolkit/ellint/ellint_3.html).
### Example
```
#include <cmath>
#include <iostream>
int main()
{
double hpi = std::acos(-1)/2;
std::cout << "ฮ (0,0,ฯ/2) = " << std::ellint_3(0, 0, hpi) << '\n'
<< "ฯ/2 = " << hpi << '\n';
}
```
Output:
```
ฮ (0,0,ฯ/2) = 1.5708
ฯ/2 = 1.5708
```
### See also
| | |
| --- | --- |
| [comp\_ellint\_3comp\_ellint\_3fcomp\_ellint\_3l](comp_ellint_3 "cpp/numeric/special functions/comp ellint 3")
(C++17)(C++17)(C++17) | (complete) elliptic integral of the third kind (function) |
### External links
[Weisstein, Eric W. "Elliptic Integral of the Third Kind."](http://mathworld.wolfram.com/EllipticIntegraloftheThirdKind.html) From MathWorld โ A Wolfram Web Resource.
cpp std::laguerre, std::laguerref, std::laguerrel std::laguerre, std::laguerref, std::laguerrel
=============================================
| Defined in header `[<cmath>](../../header/cmath "cpp/header/cmath")` | | |
| --- | --- | --- |
|
```
double laguerre( unsigned int n, double x );
float laguerre( unsigned int n, float x );
long double laguerre( unsigned int n, long double x );
float laguerref( unsigned int n, float x );
long double laguerrel( unsigned int n, long double x );
```
| (1) | (since C++17) |
|
```
double laguerre( unsigned int n, IntegralType x );
```
| (2) | (since C++17) |
1) Computes the non-associated [Laguerre polynomials](https://en.wikipedia.org/wiki/Laguerre_polynomials "enwiki:Laguerre polynomials") of the degree `n` and argument `x`
2) A set of overloads or a function template accepting an argument of any [integral type](../../types/is_integral "cpp/types/is integral"). Equivalent to (1) after casting the argument to `double`. ### Parameters
| | | |
| --- | --- | --- |
| n | - | the degree of the polymonial, a value of unsigned integer type |
| x | - | the argument, a value of a floating-point or integral type |
### Return value
If no errors occur, value of the nonassociated Laguerre polynomial of `x`, that is ex/n!dn/dxn(xn
*e*-x), is returned. ### Error handling
Errors may be reported as specified in [math\_errhandling](../math/math_errhandling "cpp/numeric/math/math errhandling").
* If the argument is NaN, NaN is returned and domain error is not reported
* If `x` is negative, a domain error may occur
* If `n` is greater or equal than 128, the behavior is implementation-defined
### Notes
Implementations that do not support C++17, but support [ISO 29124:2010](https://en.cppreference.com/w/cpp/experimental/special_math "cpp/experimental/special math"), provide this function if `__STDCPP_MATH_SPEC_FUNCS__` is defined by the implementation to a value at least 201003L and if the user defines `__STDCPP_WANT_MATH_SPEC_FUNCS__` before including any standard library headers.
Implementations that do not support ISO 29124:2010 but support TR 19768:2007 (TR1), provide this function in the header `tr1/cmath` and namespace `std::tr1`.
An implementation of this function is also [available in boost.math](http://www.boost.org/doc/libs/release/libs/math/doc/html/math_toolkit/sf_poly/laguerre.html).
The Laguerre polynomials are the polynomial solutions of the equation xy,,
+(1-x)y,
+ny = 0.
The first few are:
* laguerre(0, x) = 1
* laguerre(1, x) = -x + 1
* laguerre(2, x) = 1/2[x2
-4x+2]
* laguerre(3, x) = 1/6[-x3
-9x2
-18x+6]
### Example
```
#include <cmath>
#include <iostream>
double L1(double x) { return -x + 1; }
double L2(double x) { return 0.5*(x*x-4*x+2); }
int main()
{
// spot-checks
std::cout << std::laguerre(1, 0.5) << '=' << L1(0.5) << '\n'
<< std::laguerre(2, 0.5) << '=' << L2(0.5) << '\n'
<< std::laguerre(3, 0.0) << '=' << 1.0 << '\n';
}
```
Output:
```
0.5=0.5
0.125=0.125
1=1
```
### See also
| | |
| --- | --- |
| [assoc\_laguerreassoc\_laguerrefassoc\_laguerrel](assoc_laguerre "cpp/numeric/special functions/assoc laguerre")
(C++17)(C++17)(C++17) | associated Laguerre polynomials (function) |
### External links
[Weisstein, Eric W. "Laguerre Polynomial."](http://mathworld.wolfram.com/LaguerrePolynomial.html) From MathWorld--A Wolfram Web Resource.
cpp std::seed_seq std::seed\_seq
==============
| Defined in header `[<random>](../../header/random "cpp/header/random")` | | |
| --- | --- | --- |
|
```
class seed_seq;
```
| | (since C++11) |
`std::seed_seq` consumes a sequence of integer-valued data and produces a requested number of unsigned integer values `i`, 0 โค i < 232
, based on the consumed data. The produced values are distributed over the entire 32-bit range even if the consumed values are close.
It provides a way to seed a large number of random number engines or to seed a generator that requires a lot of entropy, given a small seed or a poorly distributed initial seed sequence.
`std::seed_seq` meets the requirements of [SeedSequence](../../named_req/seedsequence "cpp/named req/SeedSequence").
### Member types
| Member type | Definition |
| --- | --- |
| `result_type`(C++11) | `[std::uint\_least32\_t](../../types/integer "cpp/types/integer")` |
### Member functions
| | |
| --- | --- |
| [(constructor)](seed_seq/seed_seq "cpp/numeric/random/seed seq/seed seq")
(C++11) | constructs and seeds the std::seed\_seq object (public member function) |
| operator=
[deleted](C++11) | `seed_seq` is not assignable (public member function) |
| [generate](seed_seq/generate "cpp/numeric/random/seed seq/generate")
(C++11) | calculates the bias-eliminated, evenly distributed 32-bit values (public member function) |
| [size](seed_seq/size "cpp/numeric/random/seed seq/size")
(C++11) | obtains the number of 32-bit values stored in std::seed\_seq (public member function) |
| [param](seed_seq/param "cpp/numeric/random/seed seq/param")
(C++11) | obtains the 32-bit values stored in std::seed\_seq (public member function) |
### Example
```
#include <random>
#include <cstdint>
#include <iostream>
int main()
{
std::seed_seq seq{1,2,3,4,5};
std::vector<std::uint32_t> seeds(10);
seq.generate(seeds.begin(), seeds.end());
for (std::uint32_t n : seeds) {
std::cout << n << '\n';
}
}
```
Output:
```
4204997637
4246533866
1856049002
1129615051
690460811
1075771511
46783058
3904109078
1534123438
1495905678
```
cpp std::cauchy_distribution std::cauchy\_distribution
=========================
| Defined in header `[<random>](../../header/random "cpp/header/random")` | | |
| --- | --- | --- |
|
```
template< class RealType = double >
class cauchy_distribution;
```
| | (since C++11) |
Produces random numbers according to a [Cauchy distribution](https://en.wikipedia.org/wiki/Cauchy_distribution) (also called Lorentz distribution): \({\small f(x;a,b)={(b\pi{[1+{(\frac{x-a}{b})}^{2}]} })}^{-1}\)f(x; a,b) =
โ
โ
โbฯ โก
โข
โฃ1 + โ
โ
โx - a/bโ
โ
โ 2
โค
โฅ
โฆโ
โ
โ -1
`std::cauchy_distribution` satisfies all requirements of [RandomNumberDistribution](../../named_req/randomnumberdistribution "cpp/named req/RandomNumberDistribution").
### Template parameters
| | | |
| --- | --- | --- |
| RealType | - | The result type generated by the generator. The effect is undefined if this is not one of `float`, `double`, or `long double`. |
### Member types
| Member type | Definition |
| --- | --- |
| `result_type`(C++11) | `RealType` |
| `param_type`(C++11) | the type of the parameter set, see [RandomNumberDistribution](../../named_req/randomnumberdistribution "cpp/named req/RandomNumberDistribution"). |
### Member functions
| | |
| --- | --- |
| [(constructor)](cauchy_distribution/cauchy_distribution "cpp/numeric/random/cauchy distribution/cauchy distribution")
(C++11) | constructs new distribution (public member function) |
| [reset](cauchy_distribution/reset "cpp/numeric/random/cauchy distribution/reset")
(C++11) | resets the internal state of the distribution (public member function) |
| Generation |
| [operator()](cauchy_distribution/operator() "cpp/numeric/random/cauchy distribution/operator()")
(C++11) | generates the next random number in the distribution (public member function) |
| Characteristics |
| [ab](cauchy_distribution/params "cpp/numeric/random/cauchy distribution/params") | returns the distribution parameters (public member function) |
| [param](cauchy_distribution/param "cpp/numeric/random/cauchy distribution/param")
(C++11) | gets or sets the distribution parameter object (public member function) |
| [min](cauchy_distribution/min "cpp/numeric/random/cauchy distribution/min")
(C++11) | returns the minimum potentially generated value (public member function) |
| [max](cauchy_distribution/max "cpp/numeric/random/cauchy distribution/max")
(C++11) | returns the maximum potentially generated value (public member function) |
### Non-member functions
| | |
| --- | --- |
| [operator==operator!=](cauchy_distribution/operator_cmp "cpp/numeric/random/cauchy distribution/operator cmp")
(C++11)(C++11)(removed in C++20) | compares two distribution objects (function) |
| [operator<<operator>>](cauchy_distribution/operator_ltltgtgt "cpp/numeric/random/cauchy distribution/operator ltltgtgt")
(C++11) | performs stream input and output on pseudo-random number distribution (function template) |
### Example
```
#include <random>
#include <map>
#include <iomanip>
#include <algorithm>
#include <iostream>
#include <vector>
#include <cmath>
template <int Height = 5, int BarWidth = 1, int Padding = 1, int Offset = 0, class Seq>
void draw_vbars(Seq&& s, const bool DrawMinMax = true) {
static_assert((Height > 0) && (BarWidth > 0) && (Padding >= 0) && (Offset >= 0));
auto cout_n = [](auto&& v, int n = 1) { while (n-- > 0) std::cout << v; };
const auto [min, max] = std::minmax_element(std::cbegin(s), std::cend(s));
std::vector<std::div_t> qr;
for (typedef decltype(*cbegin(s)) V; V e : s)
qr.push_back(std::div(std::lerp(V(0), Height*8, (e - *min)/(*max - *min)), 8));
for (auto h{Height}; h-- > 0; cout_n('\n')) {
cout_n(' ', Offset);
for (auto dv : qr) {
const auto q{dv.quot}, r{dv.rem};
unsigned char d[] { 0xe2, 0x96, 0x88, 0 }; // Full Block: 'โ'
q < h ? d[0] = ' ', d[1] = 0 : q == h ? d[2] -= (7 - r) : 0;
cout_n(d, BarWidth), cout_n(' ', Padding);
}
if (DrawMinMax && Height > 1)
Height - 1 == h ? std::cout << "โฌ " << *max:
h ? std::cout << "โ "
: std::cout << "โด " << *min;
}
}
int main() {
std::random_device rd{};
std::mt19937 gen{rd()};
auto cauchy = [&gen](const float x0, const float ๐พ) {
std::cauchy_distribution<float> d{ x0 /* a */, ๐พ /* b */};
const int norm = 1'00'00;
const float cutoff = 0.005f;
std::map<int, int> hist{};
for (int n=0; n!=norm; ++n) { ++hist[std::round(d(gen))]; }
std::vector<float> bars;
std::vector<int> indices;
for (auto const& [n, p] : hist) {
if (float x = p * (1.0/norm); cutoff < x) {
bars.push_back(x);
indices.push_back(n);
}
}
std::cout << "xโ = " << x0 << ", ๐พ = " << ๐พ << ":\n";
draw_vbars<4,3>(bars);
for (int n : indices) { std::cout << "" << std::setw(2) << n << " "; }
std::cout << "\n\n";
};
cauchy(/* xโ = */ -2.0f, /* ๐พ = */ 0.50f);
cauchy(/* xโ = */ +0.0f, /* ๐พ = */ 1.25f);
}
```
Possible output:
```
xโ = -2, ๐พ = 0.5:
โโโ โฌ 0.5006
โโโ โ
โโโ โโโ โโโ โ
โโโ โโโ โโโ โโโ โโโ โโโ โโโ โโโ โโโ โโโ โโโ โด 0.0076
-7 -6 -5 -4 -3 -2 -1 0 1 2 3
xโ = 0, ๐พ = 1.25:
โโโ โฌ 0.2539
โ
โ
โ
โโโ โโโ โ
โโโ โโโ โโโ โโโ โโโ โ
โโโ โโโ โโโ โโโ โโโ โ
โ
โ
โโโ โโโ โโโ โโโ โโโ โ
โ
โ
โโโ โโโ โโโ โโโ โโโ โด 0.0058
-8 -7 -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 7 9
```
### External links
[Weisstein, Eric W. "Cauchy Distribution."](http://mathworld.wolfram.com/CauchyDistribution.html) From MathWorld--A Wolfram Web Resource.
cpp std::random_device std::random\_device
===================
| Defined in header `[<random>](../../header/random "cpp/header/random")` | | |
| --- | --- | --- |
|
```
class random_device;
```
| | (since C++11) |
`std::random_device` is a uniformly-distributed integer random number generator that produces non-deterministic random numbers.
`std::random_device` may be implemented in terms of an implementation-defined pseudo-random number engine if a non-deterministic source (e.g. a hardware device) is not available to the implementation. In this case each `std::random_device` object may generate the same number sequence.
### Member types
| Member type | Definition |
| --- | --- |
| `result_type` | `unsigned int` |
### Member functions
| |
| --- |
| Construction |
| [(constructor)](random_device/random_device "cpp/numeric/random/random device/random device")
(C++11) | constructs the engine (public member function) |
| operator=
(deleted) | the assignment operator is deleted (public member function) |
| Generation |
| [operator()](random_device/operator() "cpp/numeric/random/random device/operator()")
(C++11) | advances the engine's state and returns the generated value (public member function) |
| Characteristics |
| [entropy](random_device/entropy "cpp/numeric/random/random device/entropy") | obtains the entropy estimate for the non-deterministic random number generator (public member function) |
| [min](random_device/min "cpp/numeric/random/random device/min")
[static] (C++11) | gets the smallest possible value in the output range (public static member function) |
| [max](random_device/max "cpp/numeric/random/random device/max")
[static] (C++11) | gets the largest possible value in the output range (public static member function) |
### Notes
A notable implementation where `std::random_device` is deterministic is old versions of MinGW ([bug 338](https://sourceforge.net/p/mingw-w64/bugs/338/), fixed since GCC 9.2). The latest MinGW versions can be downloaded from [GCC with the MCF thread model](https://gcc-mcf.lhmouse.com/).
### Example
```
#include <iostream>
#include <string>
#include <map>
#include <random>
int main()
{
std::random_device rd;
std::map<int, int> hist;
std::uniform_int_distribution<int> dist(0, 9);
for (int n = 0; n < 20000; ++n) {
++hist[dist(rd)]; // note: demo only: the performance of many
// implementations of random_device degrades sharply
// once the entropy pool is exhausted. For practical use
// random_device is generally only used to seed
// a PRNG such as mt19937
}
for (auto p : hist) {
std::cout << p.first << " : " << std::string(p.second/100, '*') << '\n';
}
}
```
Possible output:
```
0 : ********************
1 : *******************
2 : ********************
3 : ********************
4 : ********************
5 : *******************
6 : ********************
7 : ********************
8 : *******************
9 : ********************
```
| programming_docs |
cpp std::uniform_real_distribution std::uniform\_real\_distribution
================================
| Defined in header `[<random>](../../header/random "cpp/header/random")` | | |
| --- | --- | --- |
|
```
template< class RealType = double >
class uniform_real_distribution;
```
| | (since C++11) |
Produces random floating-point values \(\small x\)x, uniformly distributed on the interval \(\small [a, b)\)[a, b), that is, distributed according to the probability density function: \({\small P(x|a,b) =} \frac{1}{b-a}\)P(x|a,b) =
1/b โ a. `std::uniform_real_distribution` satisfies all requirements of [RandomNumberDistribution](../../named_req/randomnumberdistribution "cpp/named req/RandomNumberDistribution").
### Template parameters
| | | |
| --- | --- | --- |
| RealType | - | The result type generated by the generator. The effect is undefined if this is not one of `float`, `double`, or `long double`. |
### Member types
| Member type | Definition |
| --- | --- |
| `result_type`(C++11) | `RealType` |
| `param_type`(C++11) | the type of the parameter set, see [RandomNumberDistribution](../../named_req/randomnumberdistribution "cpp/named req/RandomNumberDistribution"). |
### Member functions
| | |
| --- | --- |
| [(constructor)](uniform_real_distribution/uniform_real_distribution "cpp/numeric/random/uniform real distribution/uniform real distribution")
(C++11) | constructs new distribution (public member function) |
| [reset](uniform_real_distribution/reset "cpp/numeric/random/uniform real distribution/reset")
(C++11) | resets the internal state of the distribution (public member function) |
| Generation |
| [operator()](uniform_real_distribution/operator() "cpp/numeric/random/uniform real distribution/operator()")
(C++11) | generates the next random number in the distribution (public member function) |
| Characteristics |
| [ab](uniform_real_distribution/params "cpp/numeric/random/uniform real distribution/params") | returns the distribution parameters (public member function) |
| [param](uniform_real_distribution/param "cpp/numeric/random/uniform real distribution/param")
(C++11) | gets or sets the distribution parameter object (public member function) |
| [min](uniform_real_distribution/min "cpp/numeric/random/uniform real distribution/min")
(C++11) | returns the minimum potentially generated value (public member function) |
| [max](uniform_real_distribution/max "cpp/numeric/random/uniform real distribution/max")
(C++11) | returns the maximum potentially generated value (public member function) |
### Non-member functions
| | |
| --- | --- |
| [operator==operator!=](uniform_real_distribution/operator_cmp "cpp/numeric/random/uniform real distribution/operator cmp")
(C++11)(C++11)(removed in C++20) | compares two distribution objects (function) |
| [operator<<operator>>](uniform_real_distribution/operator_ltltgtgt "cpp/numeric/random/uniform real distribution/operator ltltgtgt")
(C++11) | performs stream input and output on pseudo-random number distribution (function template) |
### Notes
It is difficult to create a distribution over the closed interval \(\small[a, b]\)[a, b] from this distribution. Using `[std::nextafter](http://en.cppreference.com/w/cpp/numeric/math/nextafter)(b, [std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<RealType>::max())` as the second parameter does not always work due to rounding error.
Most existing implementations have a bug where they may occasionally return \(\small b\)b ([GCC #63176](https://gcc.gnu.org/bugzilla/show_bug.cgi?id=63176) [LLVM #18767](http://llvm.org/bugs/show_bug.cgi?id=18767) [MSVC STL #1074](https://github.com/microsoft/STL/issues/1074)). This was originally only thought to happen when `RealType` is `float` and when [LWG issue 2524](https://cplusplus.github.io/LWG/issue2524) is present, but it has since been shown that [neither is required to trigger the bug](https://hal.archives-ouvertes.fr/hal-03282794/document).
### Example
print 10 random numbers between 1 and 2.
```
#include <random>
#include <iostream>
int main()
{
std::random_device rd; // Will be used to obtain a seed for the random number engine
std::mt19937 gen(rd()); // Standard mersenne_twister_engine seeded with rd()
std::uniform_real_distribution<> dis(1.0, 2.0);
for (int n = 0; n < 10; ++n) {
// Use dis to transform the random unsigned int generated by gen into a
// double in [1, 2). Each call to dis(gen) generates a new random double
std::cout << dis(gen) << ' ';
}
std::cout << '\n';
}
```
Possible output:
```
1.80829 1.15391 1.18483 1.38969 1.36094 1.0648 1.97798 1.27984 1.68261 1.57326
```
cpp std::mersenne_twister_engine std::mersenne\_twister\_engine
==============================
| Defined in header `[<random>](../../header/random "cpp/header/random")` | | |
| --- | --- | --- |
|
```
template<
class UIntType,
std::size_t w, std::size_t n, std::size_t m, std::size_t r,
UIntType a, std::size_t u, UIntType d, std::size_t s,
UIntType b, std::size_t t,
UIntType c, std::size_t l, UIntType f
> class mersenne_twister_engine;
```
| | (since C++11) |
`mersenne_twister_engine` is a random number engine based on [Mersenne Twister](https://en.wikipedia.org/wiki/Mersenne_twister "enwiki:Mersenne twister") algorithm. It produces high quality unsigned integer random numbers of type `UIntType` on the interval \(\scriptsize {[0,2^w)}\)[0, 2w
).
The following type aliases define the random number engine with two commonly used parameter sets:
| Defined in header `[<random>](../../header/random "cpp/header/random")` |
| --- |
| Type | Definition |
| `mt19937`(C++11) | `std::mersenne\_twister\_engine<[std::uint\_fast32\_t](http://en.cppreference.com/w/cpp/types/integer), 32, 624, 397, 31, 0x9908b0df, 11, 0xffffffff, 7, 0x9d2c5680, 15, 0xefc60000, 18, 1812433253>` 32-bit Mersenne Twister by Matsumoto and Nishimura, 1998. |
| `mt19937_64`(C++11) | `std::mersenne\_twister\_engine<[std::uint\_fast64\_t](http://en.cppreference.com/w/cpp/types/integer), 64, 312, 156, 31, 0xb5026f5aa96619e9, 29, 0x5555555555555555, 17, 0x71d67fffeda60000, 37, 0xfff7eee000000000, 43, 6364136223846793005>` 64-bit Mersenne Twister by Matsumoto and Nishimura, 2000. |
### Template parameters
| | | |
| --- | --- | --- |
| UIntType | - | The result type generated by the generator. The effect is undefined if this is not one of `unsigned short`, `unsigned int`, `unsigned long`, or `unsigned long long`. |
| w | - | the power of two that determines the range of values generated by the engine |
| n | - | the degree of recurrence |
| m | - | the middle word, an offset used in the recurrence relation defining the series x, 1 โค m < n |
| r | - | the number of bits of the lower bit-mask, 0 โค r โค w - 1, also known as the twist value |
| a | - | the conditional xor-mask, i.e. the coefficients of the rational normal form twist matrix |
| u | - | 1st component of the bit-scrambling (tempering) matrix |
| d | - | 2nd component of the bit-scrambling (tempering) matrix |
| s | - | 3rd component of the bit-scrambling (tempering) matrix |
| b | - | 4th component of the bit-scrambling (tempering) matrix |
| t | - | 5th component of the bit-scrambling (tempering) matrix |
| c | - | 6th component of the bit-scrambling (tempering) matrix |
| l | - | 7th component of the bit-scrambling (tempering) matrix |
| f | - | the initialization multiplier |
The following relations shall hold:
`0 < m <= n,
2 < w,
r <= w,
u <= w,
s <= w,
t <= w,
l <= w,
w <= [std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<UIntType>::digits,
a <= 2^w-1,
b <= 2^w-1,
c <= 2^w-1,
d <= 2^w-1, and
f.
<= 2^w-1 (a^b denotes a to the power of b)`
### Member types
| Member type | Definition |
| --- | --- |
| `result_type`(C++11) | The integral type, `UIntType`, generated by the engine. Results are undefined if this is not an unsigned integral type. |
### Member functions
| |
| --- |
| Construction and Seeding |
| [(constructor)](mersenne_twister_engine/mersenne_twister_engine "cpp/numeric/random/mersenne twister engine/mersenne twister engine")
(C++11) | constructs the engine (public member function) |
| [seed](mersenne_twister_engine/seed "cpp/numeric/random/mersenne twister engine/seed")
(C++11) | sets the current state of the engine (public member function) |
| Generation |
| [operator()](mersenne_twister_engine/operator() "cpp/numeric/random/mersenne twister engine/operator()")
(C++11) | advances the engine's state and returns the generated value (public member function) |
| [discard](mersenne_twister_engine/discard "cpp/numeric/random/mersenne twister engine/discard")
(C++11) | advances the engine's state by a specified amount (public member function) |
| Characteristics |
| [min](mersenne_twister_engine/min "cpp/numeric/random/mersenne twister engine/min")
[static] (C++11) | gets the smallest possible value in the output range (public static member function) |
| [max](mersenne_twister_engine/max "cpp/numeric/random/mersenne twister engine/max")
[static] (C++11) | gets the largest possible value in the output range (public static member function) |
### Non-member functions
| | |
| --- | --- |
| [operator==operator!=](mersenne_twister_engine/operator_cmp "cpp/numeric/random/mersenne twister engine/operator cmp")
(C++11)(C++11)(removed in C++20) | compares the internal states of two pseudo-random number engines (function) |
| [operator<<operator>>](mersenne_twister_engine/operator_ltltgtgt "cpp/numeric/random/mersenne twister engine/operator ltltgtgt")
(C++11) | performs stream input and output on pseudo-random number engine (function template) |
### Member constants
| | |
| --- | --- |
| constexpr size\_t word\_size
[static] (C++11) | the template parameter `w`, determines the range of values generated by the engine. (public static member constant) |
| constexpr size\_t state\_size
[static] (C++11) | the template parameter `n`. The engine state is `n` values of `UIntType` (public static member constant) |
| constexpr size\_t shift\_size
[static] (C++11) | the template parameter `m` (public static member constant) |
| constexpr size\_t mask\_bits
[static] (C++11) | the template parameter `r`, also known as the twist value. (public static member constant) |
| constexpr UIntType xor\_mask
[static] (C++11) | the template parameter `a`, the conditional xor-mask. (public static member constant) |
| constexpr size\_t tempering\_u
[static] (C++11) | the template parameter `u`, first component of the bit-scrambling (tempering) matrix (public static member constant) |
| constexpr UIntType tempering\_d
[static] (C++11) | the template parameter `d`, second component of the bit-scrambling (tempering) matrix (public static member constant) |
| constexpr size\_t tempering\_s
[static] (C++11) | the template parameter `s`, third component of the bit-scrambling (tempering) matrix (public static member constant) |
| constexpr UIntType tempering\_b
[static] (C++11) | the template parameter `b`, fourth component of the bit-scrambling (tempering) matrix (public static member constant) |
| constexpr size\_t tempering\_t
[static] (C++11) | the template parameter `t`, fifth component of the bit-scrambling (tempering) matrix (public static member constant) |
| constexpr UIntType tempering\_c
[static] (C++11) | the template parameter `c`, sixth component of the bit-scrambling (tempering) matrix (public static member constant) |
| constexpr size\_t tempering\_l
[static] (C++11) | the template parameter `l`, seventh component of the bit-scrambling (tempering) matrix (public static member constant) |
| constexpr UIntType initialization\_multiplier
[static] (C++11) | the template parameter `f` (public static member constant) |
| constexpr UIntType default\_seed
[static] (C++11) | the constant value `5489u` (public static member constant) |
### Notes
The Nth consecutive invocation of a default-constructed engine is required to produce the following value:
| `N` | The random engine type | The value to produce |
| --- | --- | --- |
| `10000` | `std::mt19937` | `4123659995` |
| `10000` | `std::mt19937_64` | `9981545732273789042` |
```
#include <random>
#include <cassert>
int main()
{
std::mt19937 gen32;
std::mt19937_64 gen64;
for (auto n{1}; n != 10'000; gen32(), gen64(), ++n);
assert(gen32() == 4'123'659'995 and
gen64() == 9'981'545'732'273'789'042ULL);
}
```
cpp std::srand std::srand
==========
| Defined in header `[<cstdlib>](../../header/cstdlib "cpp/header/cstdlib")` | | |
| --- | --- | --- |
|
```
void srand( unsigned seed );
```
| | |
Seeds the pseudo-random number generator used by `[std::rand()](rand "cpp/numeric/random/rand")` with the value `seed`.
If `[std::rand()](rand "cpp/numeric/random/rand")` is used before any calls to `srand()`, `[std::rand()](rand "cpp/numeric/random/rand")` behaves as if it was seeded with `srand(1)`.
Each time `[std::rand()](rand "cpp/numeric/random/rand")` is seeded with the same `seed`, it must produce the same sequence of values.
`srand()` is not guaranteed to be thread-safe.
### Parameters
| | | |
| --- | --- | --- |
| seed | - | the seed value |
### Return value
(none).
### Notes
Generally speaking, the pseudo-random number generator should only be seeded once, before any calls to `rand()`, at the start of the program. It should not be repeatedly seeded, or reseeded every time you wish to generate a new batch of pseudo-random numbers.
Standard practice is to use the result of a call to `[std::time](http://en.cppreference.com/w/cpp/chrono/c/time)(0)` as the seed. However, `[std::time](../../chrono/c/time "cpp/chrono/c/time")` returns a `[std::time\_t](http://en.cppreference.com/w/cpp/chrono/c/time_t)` value, and `[std::time\_t](http://en.cppreference.com/w/cpp/chrono/c/time_t)` is not guaranteed to be an integral type. In practice, though, every major implementation defines `[std::time\_t](http://en.cppreference.com/w/cpp/chrono/c/time_t)` to be an integral type, and this is also what POSIX requires.
### Example
```
#include <cstdlib>
#include <iostream>
#include <ctime>
int main()
{
std::srand(std::time(0)); //use current time as seed for random generator
int random_variable = std::rand();
std::cout << "Random value on [0 " << RAND_MAX << "]: "
<< random_variable << '\n';
}
```
Possible output:
```
Random value on [0 2147483647]: 1373858591
```
### See also
| | |
| --- | --- |
| [rand](rand "cpp/numeric/random/rand") | generates a pseudo-random number (function) |
| [RAND\_MAX](rand_max "cpp/numeric/random/RAND MAX") | maximum possible value generated by `[std::rand](rand "cpp/numeric/random/rand")` (macro constant) |
| [reseed](https://en.cppreference.com/w/cpp/experimental/reseed "cpp/experimental/reseed") | reseeds the per-thread random engine (function) |
| [C documentation](https://en.cppreference.com/w/c/numeric/random/srand "c/numeric/random/srand") for `srand` |
cpp std::piecewise_constant_distribution std::piecewise\_constant\_distribution
======================================
| Defined in header `[<random>](../../header/random "cpp/header/random")` | | |
| --- | --- | --- |
|
```
template< class RealType = double >
class piecewise_constant_distribution;
```
| | (since C++11) |
`std::piecewise_constant_distribution` produces random floating-point numbers, which are uniformly distributed within each of the several subintervals [b
i, b
i+1), each with its own weight w
i. The set of interval boundaries and the set of weights are the parameters of this distribution. The probability density for any b.
iโคx<b
i+1 is wi / S (bi+1 - bi) . where S is the sum of all weights. `std::piecewise_constant_distribution` satisfies all requirements of [RandomNumberDistribution](../../named_req/randomnumberdistribution "cpp/named req/RandomNumberDistribution").
### Template parameters
| | | |
| --- | --- | --- |
| RealType | - | The result type generated by the generator. The effect is undefined if this is not one of `float`, `double`, or `long double`. |
### Member types
| Member type | Definition |
| --- | --- |
| `result_type` | `RealType` |
| `param_type`(C++11) | the type of the parameter set, see [RandomNumberDistribution](../../named_req/randomnumberdistribution "cpp/named req/RandomNumberDistribution"). |
### Member functions
| | |
| --- | --- |
| [(constructor)](piecewise_constant_distribution/piecewise_constant_distribution "cpp/numeric/random/piecewise constant distribution/piecewise constant distribution")
(C++11) | constructs new distribution (public member function) |
| [reset](piecewise_constant_distribution/reset "cpp/numeric/random/piecewise constant distribution/reset")
(C++11) | resets the internal state of the distribution (public member function) |
| Generation |
| [operator()](piecewise_constant_distribution/operator() "cpp/numeric/random/piecewise constant distribution/operator()")
(C++11) | generates the next random number in the distribution (public member function) |
| Characteristics |
| [intervalsdensities](piecewise_constant_distribution/params "cpp/numeric/random/piecewise constant distribution/params") | returns the distribution parameters (public member function) |
| [param](piecewise_constant_distribution/param "cpp/numeric/random/piecewise constant distribution/param")
(C++11) | gets or sets the distribution parameter object (public member function) |
| [min](piecewise_constant_distribution/min "cpp/numeric/random/piecewise constant distribution/min")
(C++11) | returns the minimum potentially generated value (public member function) |
| [max](piecewise_constant_distribution/max "cpp/numeric/random/piecewise constant distribution/max")
(C++11) | returns the maximum potentially generated value (public member function) |
### Non-member functions
| | |
| --- | --- |
| [operator==operator!=](piecewise_constant_distribution/operator_cmp "cpp/numeric/random/piecewise constant distribution/operator cmp")
(C++11)(C++11)(removed in C++20) | compares two distribution objects (function) |
| [operator<<operator>>](piecewise_constant_distribution/operator_ltltgtgt "cpp/numeric/random/piecewise constant distribution/operator ltltgtgt")
(C++11) | performs stream input and output on pseudo-random number distribution (function template) |
### Example
```
#include <iostream>
#include <string>
#include <map>
#include <random>
int main()
{
std::random_device rd;
std::mt19937 gen(rd());
// 50% of the time, generate a random number between 0 and 1
// 50% of the time, generate a random number between 10 and 15
std::vector<double> i{0, 1, 10, 15};
std::vector<double> w{ 1, 0, 1 };
std::piecewise_constant_distribution<> d(i.begin(), i.end(), w.begin());
std::map<int, int> hist;
for(int n=0; n<10000; ++n) {
++hist[d(gen)];
}
for(auto p : hist) {
std::cout << std::hex << std::uppercase << p.first << ' '
<< std::string(p.second/100, '*') << '\n';
}
}
```
Possible output:
```
0 **************************************************
A **********
B *********
C *********
D **********
E *********
```
### References
* C++20 standard (ISO/IEC 14882:2020):
+ 29.6.9.6.2 Class template piecewise\_constant\_distribution [rand.dist.samp.pconst] (p: 1207-1208)
* C++17 standard (ISO/IEC 14882:2017):
+ 29.6.8.6.2 Class template piecewise\_constant\_distribution [rand.dist.samp.pconst] (p: 1098-1100)
* C++14 standard (ISO/IEC 14882:2014):
+ 26.5.8.6.2 Class template piecewise\_constant\_distribution [rand.dist.samp.pconst] (p: 962-964)
* C++11 standard (ISO/IEC 14882:2011):
+ 26.5.8.6.2 Class template piecewise\_constant\_distribution [rand.dist.samp.pconst] (p: 955-957)
| programming_docs |
cpp std::exponential_distribution std::exponential\_distribution
==============================
| Defined in header `[<random>](../../header/random "cpp/header/random")` | | |
| --- | --- | --- |
|
```
template< class RealType = double >
class exponential_distribution;
```
| | (since C++11) |
Produces random non-negative floating-point values \(\small x\)x, distributed according to probability density function: \(\small P(x|\lambda) = \lambda e^{-\lambda x}\)P(x|ฮป) = ฮปe.
-ฮปx
The value obtained is the time/distance until the next random event if random events occur at constant rate \(\small\lambda\)ฮป per unit of time/distance. For example, this distribution describes the time between the clicks of a Geiger counter or the distance between point mutations in a DNA strand.
This is the continuous counterpart of `[std::geometric\_distribution](geometric_distribution "cpp/numeric/random/geometric distribution")`.
`std::exponential_distribution` satisfies [RandomNumberDistribution](../../named_req/randomnumberdistribution "cpp/named req/RandomNumberDistribution").
### Template parameters
| | | |
| --- | --- | --- |
| RealType | - | The result type generated by the generator. The effect is undefined if this is not one of `float`, `double`, or `long double`. |
### Member types
| Member type | Definition |
| --- | --- |
| `result_type`(C++11) | `RealType` |
| `param_type`(C++11) | the type of the parameter set, see [RandomNumberDistribution](../../named_req/randomnumberdistribution "cpp/named req/RandomNumberDistribution"). |
### Member functions
| | |
| --- | --- |
| [(constructor)](exponential_distribution/exponential_distribution "cpp/numeric/random/exponential distribution/exponential distribution")
(C++11) | constructs new distribution (public member function) |
| [reset](exponential_distribution/reset "cpp/numeric/random/exponential distribution/reset")
(C++11) | resets the internal state of the distribution (public member function) |
| Generation |
| [operator()](exponential_distribution/operator() "cpp/numeric/random/exponential distribution/operator()")
(C++11) | generates the next random number in the distribution (public member function) |
| Characteristics |
| [lambda](exponential_distribution/lambda "cpp/numeric/random/exponential distribution/lambda") | returns the *lambda* distribution parameter (rate of events) (public member function) |
| [param](exponential_distribution/param "cpp/numeric/random/exponential distribution/param")
(C++11) | gets or sets the distribution parameter object (public member function) |
| [min](exponential_distribution/min "cpp/numeric/random/exponential distribution/min")
(C++11) | returns the minimum potentially generated value (public member function) |
| [max](exponential_distribution/max "cpp/numeric/random/exponential distribution/max")
(C++11) | returns the maximum potentially generated value (public member function) |
### Non-member functions
| | |
| --- | --- |
| [operator==operator!=](exponential_distribution/operator_cmp "cpp/numeric/random/exponential distribution/operator cmp")
(C++11)(C++11)(removed in C++20) | compares two distribution objects (function) |
| [operator<<operator>>](exponential_distribution/operator_ltltgtgt "cpp/numeric/random/exponential distribution/operator ltltgtgt")
(C++11) | performs stream input and output on pseudo-random number distribution (function template) |
### Notes
Some implementations may occasionally return infinity if `RealType` is `float`. This is [LWG issue 2524](https://cplusplus.github.io/LWG/issue2524).
### Example
```
#include <iostream>
#include <iomanip>
#include <random>
#include <string>
#include <map>
int main()
{
std::random_device rd;
std::mt19937 gen(rd());
// if particles decay once per second on average,
// how much time, in seconds, until the next one?
std::exponential_distribution<> d(1);
std::map<int, int> hist;
for(int n=0; n<10000; ++n) {
++hist[2*d(gen)];
}
for(auto p : hist) {
std::cout << std::fixed << std::setprecision(1)
<< p.first/2.0 << '-' << (p.first+1)/2.0 << ' '
<< std::string(p.second/200, '*') << '\n';
}
}
```
Possible output:
```
0.0-0.5 *******************
0.5-1.0 ***********
1.0-1.5 *******
1.5-2.0 ****
2.0-2.5 **
2.5-3.0 *
3.0-3.5
3.5-4.0
```
### External links
[Weisstein, Eric W. "Exponential Distribution."](http://mathworld.wolfram.com/ExponentialDistribution.html) From MathWorld--A Wolfram Web Resource.
cpp std::lognormal_distribution std::lognormal\_distribution
============================
| Defined in header `[<random>](../../header/random "cpp/header/random")` | | |
| --- | --- | --- |
|
```
template< class RealType = double >
class lognormal_distribution;
```
| | (since C++11) |
The lognormal\_distribution random number distribution produces random numbers x > 0 according to a [log-normal distribution](https://en.wikipedia.org/wiki/Log-normal_distribution "enwiki:Log-normal distribution"): \({\small f(x;m,s) = \frac{1}{sx\sqrt{2\pi} } \exp{(-\frac{ {(\ln{x} - m)}^{2} }{2{s}^{2} })} }\)f(x; m,s) =
1/sxโ2 ฯ expโ
โ
โ- (ln x - m)2/ 2s2โ
โ
โ The parameters m and s are, respectively, the mean and standard deviation of the natural logarithm of x.
`std::lognormal_distribution` satisfies all requirements of [RandomNumberDistribution](../../named_req/randomnumberdistribution "cpp/named req/RandomNumberDistribution").
### Template parameters
| | | |
| --- | --- | --- |
| RealType | - | The result type generated by the generator. The effect is undefined if this is not one of `float`, `double`, or `long double`. |
### Member types
| Member type | Definition |
| --- | --- |
| `result_type` | `RealType` |
| `param_type`(C++11) | the type of the parameter set, see [RandomNumberDistribution](../../named_req/randomnumberdistribution "cpp/named req/RandomNumberDistribution"). |
### Member functions
| | |
| --- | --- |
| [(constructor)](lognormal_distribution/lognormal_distribution "cpp/numeric/random/lognormal distribution/lognormal distribution")
(C++11) | constructs new distribution (public member function) |
| [reset](lognormal_distribution/reset "cpp/numeric/random/lognormal distribution/reset")
(C++11) | resets the internal state of the distribution (public member function) |
| Generation |
| [operator()](lognormal_distribution/operator() "cpp/numeric/random/lognormal distribution/operator()")
(C++11) | generates the next random number in the distribution (public member function) |
| Characteristics |
| [ms](lognormal_distribution/params "cpp/numeric/random/lognormal distribution/params") | returns the distribution parameters (public member function) |
| [param](lognormal_distribution/param "cpp/numeric/random/lognormal distribution/param")
(C++11) | gets or sets the distribution parameter object (public member function) |
| [min](lognormal_distribution/min "cpp/numeric/random/lognormal distribution/min")
(C++11) | returns the minimum potentially generated value (public member function) |
| [max](lognormal_distribution/max "cpp/numeric/random/lognormal distribution/max")
(C++11) | returns the maximum potentially generated value (public member function) |
### Non-member functions
| | |
| --- | --- |
| [operator==operator!=](lognormal_distribution/operator_cmp "cpp/numeric/random/lognormal distribution/operator cmp")
(C++11)(C++11)(removed in C++20) | compares two distribution objects (function) |
| [operator<<operator>>](lognormal_distribution/operator_ltltgtgt "cpp/numeric/random/lognormal distribution/operator ltltgtgt")
(C++11) | performs stream input and output on pseudo-random number distribution (function template) |
### Example
```
#include <iostream>
#include <iomanip>
#include <string>
#include <map>
#include <random>
#include <cmath>
int main()
{
std::random_device rd;
std::mt19937 gen(rd());
std::lognormal_distribution<> d(1.6, 0.25);
std::map<int, int> hist;
for(int n=0; n<10000; ++n) {
++hist[std::round(d(gen))];
}
for(auto p : hist) {
std::cout << std::fixed << std::setprecision(1) << std::setw(2)
<< p.first << ' ' << std::string(p.second/200, '*') << '\n';
}
}
```
Possible output:
```
2
3 ***
4 *************
5 ***************
6 *********
7 ****
8 *
9
10
11
12
```
### External links
* [Weisstein, Eric W. "Log Normal Distribution."](http://mathworld.wolfram.com/LogNormalDistribution.html) From MathWorld--A Wolfram Web Resource.
cpp std::geometric_distribution std::geometric\_distribution
============================
| Defined in header `[<random>](../../header/random "cpp/header/random")` | | |
| --- | --- | --- |
|
```
template< class IntType = int >
class geometric_distribution;
```
| | (since C++11) |
Produces random non-negative integer values i, distributed according to discrete probability function: \(P(i|p) = p \cdot (1-p)^i\)P(i|p) = p ยท (1 โ p).
i
The value represents the number of yes/no trials (each succeeding with probability p) which are necessary to obtain a single success.
`std::geometric_distribution<>(p)` is exactly equivalent to `[std::negative\_binomial\_distribution](http://en.cppreference.com/w/cpp/numeric/random/negative_binomial_distribution)<>(1, p)`. It is also the discrete counterpart of `[std::exponential\_distribution](exponential_distribution "cpp/numeric/random/exponential distribution")`.
`std::geometric_distribution` satisfies [RandomNumberDistribution](../../named_req/randomnumberdistribution "cpp/named req/RandomNumberDistribution").
### Template parameters
| | | |
| --- | --- | --- |
| IntType | - | The result type generated by the generator. The effect is undefined if this is not one of `short`, `int`, `long`, `long long`, `unsigned short`, `unsigned int`, `unsigned long`, or `unsigned long long`. |
### Member types
| Member type | Definition |
| --- | --- |
| `result_type` | `IntType` |
| `param_type`(C++11) | the type of the parameter set, see [RandomNumberDistribution](../../named_req/randomnumberdistribution "cpp/named req/RandomNumberDistribution"). |
### Member functions
| | |
| --- | --- |
| [(constructor)](geometric_distribution/geometric_distribution "cpp/numeric/random/geometric distribution/geometric distribution")
(C++11) | constructs new distribution (public member function) |
| [reset](geometric_distribution/reset "cpp/numeric/random/geometric distribution/reset")
(C++11) | resets the internal state of the distribution (public member function) |
| Generation |
| [operator()](geometric_distribution/operator() "cpp/numeric/random/geometric distribution/operator()")
(C++11) | generates the next random number in the distribution (public member function) |
| Characteristics |
| [p](geometric_distribution/p "cpp/numeric/random/geometric distribution/p") | returns the *p* distribution parameter (probability of a trial generating `true`) (public member function) |
| [param](geometric_distribution/param "cpp/numeric/random/geometric distribution/param")
(C++11) | gets or sets the distribution parameter object (public member function) |
| [min](geometric_distribution/min "cpp/numeric/random/geometric distribution/min")
(C++11) | returns the minimum potentially generated value (public member function) |
| [max](geometric_distribution/max "cpp/numeric/random/geometric distribution/max")
(C++11) | returns the maximum potentially generated value (public member function) |
### Non-member functions
| | |
| --- | --- |
| [operator==operator!=](geometric_distribution/operator_cmp "cpp/numeric/random/geometric distribution/operator cmp")
(C++11)(C++11)(removed in C++20) | compares two distribution objects (function) |
| [operator<<operator>>](geometric_distribution/operator_ltltgtgt "cpp/numeric/random/geometric distribution/operator ltltgtgt")
(C++11) | performs stream input and output on pseudo-random number distribution (function template) |
### Example
`std::geometric_distribution<>(0.5)` is the default and represents the number of coin tosses that are required to get heads.
```
#include <iostream>
#include <iomanip>
#include <string>
#include <map>
#include <random>
int main()
{
std::random_device rd;
std::mt19937 gen(rd());
std::geometric_distribution<> d; // same as std::negative_binomial_distribution<> d(1, 0.5);
std::map<int, int> hist;
for(int n=0; n<10000; ++n) {
++hist[d(gen)];
}
for(auto p : hist) {
std::cout << std::hex << p.first << ' '
<< std::string(p.second/100, '*') << '\n';
}
}
```
Possible output:
```
0 *************************************************
1 *************************
2 ************
3 ******
4 **
5 *
6
7
8
9
```
### External links
[Weisstein, Eric W. "Geometric Distribution."](http://mathworld.wolfram.com/GeometricDistribution.html) From MathWorld--A Wolfram Web Resource.
cpp std::uniform_int_distribution std::uniform\_int\_distribution
===============================
| Defined in header `[<random>](../../header/random "cpp/header/random")` | | |
| --- | --- | --- |
|
```
template< class IntType = int >
class uniform_int_distribution;
```
| | (since C++11) |
Produces random integer values \(\small i\)i, uniformly distributed on the closed interval \(\small[a, b]\)[a, b], that is, distributed according to the discrete probability function \({\small P(i|a,b) =}\frac{1}{b - a + 1}\)P(i|a,b) =
1/b โ a + 1. `std::uniform_int_distribution` satisfies all requirements of [RandomNumberDistribution](../../named_req/randomnumberdistribution "cpp/named req/RandomNumberDistribution").
### Template parameters
| | | |
| --- | --- | --- |
| IntType | - | The result type generated by the generator. The effect is undefined if this is not one of `short`, `int`, `long`, `long long`, `unsigned short`, `unsigned int`, `unsigned long`, or `unsigned long long`. |
### Member types
| Member type | Definition |
| --- | --- |
| `result_type`(C++11) | `IntType` |
| `param_type`(C++11) | the type of the parameter set, see [RandomNumberDistribution](../../named_req/randomnumberdistribution "cpp/named req/RandomNumberDistribution"). |
### Member functions
| | |
| --- | --- |
| [(constructor)](uniform_int_distribution/uniform_int_distribution "cpp/numeric/random/uniform int distribution/uniform int distribution")
(C++11) | constructs new distribution (public member function) |
| [reset](uniform_int_distribution/reset "cpp/numeric/random/uniform int distribution/reset")
(C++11) | resets the internal state of the distribution (public member function) |
| Generation |
| [operator()](uniform_int_distribution/operator() "cpp/numeric/random/uniform int distribution/operator()")
(C++11) | generates the next random number in the distribution (public member function) |
| Characteristics |
| [ab](uniform_int_distribution/params "cpp/numeric/random/uniform int distribution/params") | returns the distribution parameters (public member function) |
| [param](uniform_int_distribution/param "cpp/numeric/random/uniform int distribution/param")
(C++11) | gets or sets the distribution parameter object (public member function) |
| [min](uniform_int_distribution/min "cpp/numeric/random/uniform int distribution/min")
(C++11) | returns the minimum potentially generated value (public member function) |
| [max](uniform_int_distribution/max "cpp/numeric/random/uniform int distribution/max")
(C++11) | returns the maximum potentially generated value (public member function) |
### Non-member functions
| | |
| --- | --- |
| [operator==operator!=](uniform_int_distribution/operator_cmp "cpp/numeric/random/uniform int distribution/operator cmp")
(C++11)(C++11)(removed in C++20) | compares two distribution objects (function) |
| [operator<<operator>>](uniform_int_distribution/operator_ltltgtgt "cpp/numeric/random/uniform int distribution/operator ltltgtgt")
(C++11) | performs stream input and output on pseudo-random number distribution (function template) |
### Example
This program simulates throwing 6-sided dice.
```
#include <random>
#include <iostream>
int main()
{
std::random_device rd; //Will be used to obtain a seed for the random number engine
std::mt19937 gen(rd()); //Standard mersenne_twister_engine seeded with rd()
std::uniform_int_distribution<> distrib(1, 6);
for (int n=0; n<10; ++n)
//Use `distrib` to transform the random unsigned int generated by gen into an int in [1, 6]
std::cout << distrib(gen) << ' ';
std::cout << '\n';
}
```
Possible output:
```
1 1 6 5 2 2 5 5 6 2
```
cpp std::independent_bits_engine std::independent\_bits\_engine
==============================
| Defined in header `[<random>](../../header/random "cpp/header/random")` | | |
| --- | --- | --- |
|
```
template<
class Engine,
std::size_t W,
class UIntType
> class independent_bits_engine;
```
| | (since C++11) |
`independent_bits_engine` is a random number engine adaptor that produces random numbers with different number of bits than that of the wrapped engine.
### Template parameters
| | | |
| --- | --- | --- |
| Engine | - | the type of the wrapped engine |
| W | - | the number of bits the generated numbers should have |
| UIntType | - | the type of the generated random numbers. The effect is undefined unless the parameter is cv-unqualified and is one of `unsigned short`, `unsigned int`, `unsigned long`, or `unsigned long long`. |
| Type requirements |
| -`Engine` must meet the requirements of [RandomNumberEngine](../../named_req/randomnumberengine "cpp/named req/RandomNumberEngine"). |
| -`W` must be greater than zero, and no greater than `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<UIntType>::digits`. |
### Member types
| Member type | Definition |
| --- | --- |
| `result_type` | `UIntType` |
### Member functions
| | |
| --- | --- |
| [(constructor)](independent_bits_engine/independent_bits_engine "cpp/numeric/random/independent bits engine/independent bits engine")
(C++11) | constructs the engine adaptor (public member function) |
| [seed](independent_bits_engine/seed "cpp/numeric/random/independent bits engine/seed")
(C++11) | sets the state of the underlying engine (public member function) |
| [base](independent_bits_engine/base "cpp/numeric/random/independent bits engine/base")
(C++11) | returns the underlying engine (public member function) |
| Generation |
| [operator()](independent_bits_engine/operator() "cpp/numeric/random/independent bits engine/operator()")
(C++11) | advances the state of the underlying engine and returns the generated value (public member function) |
| [discard](independent_bits_engine/discard "cpp/numeric/random/independent bits engine/discard")
(C++11) | advances the adaptor's state by a specified amount (public member function) |
| Characteristics |
| [min](independent_bits_engine/min "cpp/numeric/random/independent bits engine/min")
[static] (C++11) | gets the smallest possible value in the output range (always zero). (public static member function) |
| [max](independent_bits_engine/max "cpp/numeric/random/independent bits engine/max")
[static] (C++11) | gets the largest possible value in the output range (always 2w-1). (public static member function) |
### Non-member functions
| | |
| --- | --- |
| [operator==operator!=](independent_bits_engine/operator_cmp "cpp/numeric/random/independent bits engine/operator cmp")
(C++11)(C++11)(removed in C++20) | compares the internal states of the adaptors and underlying engines (function) |
| [operator<<operator>>](independent_bits_engine/operator_ltltgtgt "cpp/numeric/random/independent bits engine/operator ltltgtgt")
(C++11) | performs stream input and output on pseudo-random number engine adaptor (function) |
| programming_docs |
cpp std::uniform_random_bit_generator std::uniform\_random\_bit\_generator
====================================
| Defined in header `[<random>](../../header/random "cpp/header/random")` | | |
| --- | --- | --- |
|
```
template <class G>
concept uniform_random_bit_generator =
std::invocable<G&> && std::unsigned_integral<std::invoke_result_t<G&>> &&
requires {
{ G::min() } -> std::same_as<std::invoke_result_t<G&>>;
{ G::max() } -> std::same_as<std::invoke_result_t<G&>>;
requires std::bool_constant<(G::min() < G::max())>::value;
};
```
| | (since C++20) |
The concept `uniform_random_bit_generator<G>` specifies that `G` is the type of a uniform random bit generator, that is, objects of type `G` is a function object returning unsigned integer values such that each value in the range of possible results has (ideally) equal probability of being returned.
### Semantic requirements
`uniform_random_bit_generator<G>` is modeled only if, given any object `g` of type `G`:
* `g()` is in the range `[G::min(), G::max()]`
* `g()` has amortized constant complexity.
### Notes
In order to satisfy the requirement `[std::bool\_constant](http://en.cppreference.com/w/cpp/types/integral_constant)<(G::min() < G::max())>::value`, both `G::min()` and `G::max()` must be constant expressions, and the result of the comparison must be `true`.
cpp std::chi_squared_distribution std::chi\_squared\_distribution
===============================
| Defined in header `[<random>](../../header/random "cpp/header/random")` | | |
| --- | --- | --- |
|
```
template< class RealType = double >
class chi_squared_distribution;
```
| | (since C++11) |
The `chi_squared_distribution` produces random numbers \(\small x>0\)x>0 according to the [Chi-squared distribution](https://en.wikipedia.org/wiki/Chi-squared_distribution "enwiki:Chi-squared distribution"): \({\small f(x;n) = }\frac{x^{(n/2)-1}\exp{(-x/2)} }{\Gamma{(n/2)}2^{n/2} }\)f(x;n) =
x(n/2)-1 e-x/2 / ฮ(n/2) 2n/2 \(\small\Gamma\)ฮ is the [Gamma function](https://en.wikipedia.org/wiki/Gamma_function "enwiki:Gamma function") (See also `[std::tgamma](../math/tgamma "cpp/numeric/math/tgamma")`) and \(\small n\)n are the [degrees of freedom](https://en.wikipedia.org/wiki/Degrees_of_freedom_(statistics) "enwiki:Degrees of freedom (statistics)") (default 1).
`std::chi_squared_distribution` satisfies all requirements of [RandomNumberDistribution](../../named_req/randomnumberdistribution "cpp/named req/RandomNumberDistribution").
### Template parameters
| | | |
| --- | --- | --- |
| RealType | - | The result type generated by the generator. The effect is undefined if this is not one of `float`, `double`, or `long double`. |
### Member types
| Member type | Definition |
| --- | --- |
| `result_type`(C++11) | `RealType` |
| `param_type`(C++11) | the type of the parameter set, see [RandomNumberDistribution](../../named_req/randomnumberdistribution "cpp/named req/RandomNumberDistribution"). |
### Member functions
| | |
| --- | --- |
| [(constructor)](chi_squared_distribution/chi_squared_distribution "cpp/numeric/random/chi squared distribution/chi squared distribution")
(C++11) | constructs new distribution (public member function) |
| [reset](chi_squared_distribution/reset "cpp/numeric/random/chi squared distribution/reset")
(C++11) | resets the internal state of the distribution (public member function) |
| Generation |
| [operator()](chi_squared_distribution/operator() "cpp/numeric/random/chi squared distribution/operator()")
(C++11) | generates the next random number in the distribution (public member function) |
| Characteristics |
| [n](chi_squared_distribution/n "cpp/numeric/random/chi squared distribution/n")
(C++11) | returns the degrees of freedom (\(\small n\)n) distribution parameter (public member function) |
| [param](chi_squared_distribution/param "cpp/numeric/random/chi squared distribution/param")
(C++11) | gets or sets the distribution parameter object (public member function) |
| [min](chi_squared_distribution/min "cpp/numeric/random/chi squared distribution/min")
(C++11) | returns the minimum potentially generated value (public member function) |
| [max](chi_squared_distribution/max "cpp/numeric/random/chi squared distribution/max")
(C++11) | returns the maximum potentially generated value (public member function) |
### Non-member functions
| | |
| --- | --- |
| [operator==operator!=](chi_squared_distribution/operator_cmp "cpp/numeric/random/chi squared distribution/operator cmp")
(C++11)(C++11)(removed in C++20) | compares two distribution objects (function) |
| [operator<<operator>>](chi_squared_distribution/operator_ltltgtgt "cpp/numeric/random/chi squared distribution/operator ltltgtgt")
(C++11) | performs stream input and output on pseudo-random number distribution (function template) |
### Example
```
#include <random>
#include <iomanip>
#include <map>
#include <algorithm>
#include <iostream>
#include <vector>
#include <cmath>
template <int Height = 5, int BarWidth = 1, int Padding = 1, int Offset = 0, class Seq>
void draw_vbars(Seq&& s, const bool DrawMinMax = true) {
static_assert((Height > 0) && (BarWidth > 0) && (Padding >= 0) && (Offset >= 0));
auto cout_n = [](auto&& v, int n = 1) { while (n-- > 0) std::cout << v; };
const auto [min, max] = std::minmax_element(std::cbegin(s), std::cend(s));
std::vector<std::div_t> qr;
for (typedef decltype(*cbegin(s)) V; V e : s)
qr.push_back(std::div(std::lerp(V(0), Height*8, (e - *min)/(*max - *min)), 8));
for (auto h{Height}; h-- > 0; cout_n('\n')) {
cout_n(' ', Offset);
for (auto dv : qr) {
const auto q{dv.quot}, r{dv.rem};
unsigned char d[] { 0xe2, 0x96, 0x88, 0 }; // Full Block: 'โ'
q < h ? d[0] = ' ', d[1] = 0 : q == h ? d[2] -= (7 - r) : 0;
cout_n(d, BarWidth), cout_n(' ', Padding);
}
if (DrawMinMax && Height > 1)
Height - 1 == h ? std::cout << "โฌ " << *max:
h ? std::cout << "โ "
: std::cout << "โด " << *min;
}
}
int main() {
std::random_device rd{};
std::mt19937 gen{rd()};
auto ฯ2 = [&gen](const float dof) {
std::chi_squared_distribution<float> d{ dof /* n */ };
const int norm = 1'00'00;
const float cutoff = 0.002f;
std::map<int, int> hist{};
for (int n=0; n!=norm; ++n) { ++hist[std::round(d(gen))]; }
std::vector<float> bars;
std::vector<int> indices;
for (auto const& [n, p] : hist) {
if (float x = p * (1.0/norm); cutoff < x) {
bars.push_back(x);
indices.push_back(n);
}
}
std::cout << "dof = " << dof << ":\n";
draw_vbars<4,3>(bars);
for (int n : indices) { std::cout << "" << std::setw(2) << n << " "; }
std::cout << "\n\n";
};
for (float dof : {1.f, 2.f, 3.f, 4.f, 6.f, 9.f}) ฯ2(dof);
}
```
Possible output:
```
dof = 1:
โโโ โฌ 0.5271
โโโ โ
โโโ โโโ โ
โโโ โโโ โโโ โโโ โโโ โโโ โโโ โโโ โโโ โด 0.003
0 1 2 3 4 5 6 7 8
dof = 2:
โโโ โฌ 0.3169
โโโ โโโ โโโ โ
โโโ โโโ โโโ โโโ โ
โโโ โโโ โโโ โโโ โโโ โโโ โโโ โโโ โโโ โโโ โโโ โด 0.004
0 1 2 3 4 5 6 7 8 9 10
dof = 3:
โโโ โโโ โฌ 0.2439
โโโ โโโ โโโ โ
โโโ โโโ โโโ โโโ โโโ โโโ โ
โโโ โโโ โโโ โโโ โโโ โโโ โโโ โโโ โโโ โโโ โโโ โโโ โโโ โด 0.0033
0 1 2 3 4 5 6 7 8 9 10 11 12
dof = 4:
โโโ โโโ โโโ โฌ 0.1864
โโโ โโโ โโโ โโโ โโโ โ
โโโ โโโ โโโ โโโ โโโ โ
โ
โ
โโโ โ
โ
โ
โ
โโโ โโโ โโโ โโโ โโโ โโโ โโโ โโโ โโโ โโโ โโโ โโโ โโโ โโโ โโโ โด 0.0026
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
dof = 6:
โ
โ
โ
โโโ โโโ โโโ โฌ 0.1351
โ
โ
โ
โโโ โโโ โโโ โโโ โโโ โโโ โ
โโโ โโโ โโโ โโโ โโโ โโโ โโโ โโโ โ
โ
โ
โโโ โ
โโโ โโโ โโโ โโโ โโโ โโโ โโโ โโโ โโโ โโโ โโโ โโโ โ
โ
โ
โโโ โโโ โโโ โโโ โโโ โโโ โด 0.0031
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
dof = 9:
โ
โ
โ
โโโ โโโ โโโ โโโ โโโ โฌ 0.1044
โโโ โโโ โโโ โโโ โโโ โโโ โโโ โ
โ
โ
โโโ โ
โโโ โโโ โโโ โโโ โโโ โโโ โโโ โโโ โโโ โโโ โโโ โโโ โ
โโโ โโโ โโโ โโโ โโโ โโโ โโโ โโโ โโโ โโโ โโโ โโโ โโโ โโโ โโโ โโโ โโโ โโโ โโโ โโโ โโโ โด 0.0034
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
```
### External links
* [Weisstein, Eric W. "Chi-Squared Distribution."](http://mathworld.wolfram.com/Chi-SquaredDistribution.html) From MathWorld--A Wolfram Web Resource.
* [Chi-squared distribution.](https://en.wikipedia.org/wiki/Chi-squared_distribution "enwiki:Chi-squared distribution") From Wikipedia.
cpp std::discard_block_engine std::discard\_block\_engine
===========================
| Defined in header `[<random>](../../header/random "cpp/header/random")` | | |
| --- | --- | --- |
|
```
template<
class Engine,
std::size_t P, std::size_t R
> class discard_block_engine;
```
| | (since C++11) |
`discard_block_engine` is a pseudo-random number engine adaptor that discards a certain amount of data produced by the base engine. From each block of size `P` generated by the base engine, the adaptor keeps only `R` numbers, discarding the rest.
### Template parameters
| | | |
| --- | --- | --- |
| Engine | - | the type of the wrapped engine. |
| P | - | the size of a block. Expected that \(\small{P>0}\)P > 0. |
| R | - | the number of used numbers per block. Expected that \(\small{0<R\le P}\)0 < R โค P. |
| Type requirements |
| -`Engine` must meet the requirements of [RandomNumberEngine](../../named_req/randomnumberengine "cpp/named req/RandomNumberEngine"). |
### Member types
| Member type | Definition |
| --- | --- |
| `result_type`(C++11) | `Engine::result_type` |
### Member functions
| | |
| --- | --- |
| [(constructor)](discard_block_engine/discard_block_engine "cpp/numeric/random/discard block engine/discard block engine")
(C++11) | constructs the engine adaptor (public member function) |
| [seed](discard_block_engine/seed "cpp/numeric/random/discard block engine/seed")
(C++11) | sets the state of the underlying engine (public member function) |
| [base](discard_block_engine/base "cpp/numeric/random/discard block engine/base")
(C++11) | returns the underlying engine (public member function) |
| Generation |
| [operator()](discard_block_engine/operator() "cpp/numeric/random/discard block engine/operator()")
(C++11) | advances the state of the underlying engine and returns the generated value (public member function) |
| [discard](discard_block_engine/discard "cpp/numeric/random/discard block engine/discard")
(C++11) | advances the adaptor's state by a specified amount (public member function) |
| Characteristics |
| [min](discard_block_engine/min "cpp/numeric/random/discard block engine/min")
[static] (C++11) | gets the smallest possible value in the output range of the underlying engine. (public static member function) |
| [max](discard_block_engine/max "cpp/numeric/random/discard block engine/max")
[static] (C++11) | gets the largest possible value in the output range of the underlying engine. (public static member function) |
### Non-member functions
| | |
| --- | --- |
| [operator==operator!=](discard_block_engine/operator_cmp "cpp/numeric/random/discard block engine/operator cmp")
(C++11)(C++11)(removed in C++20) | compares the internal states of the adaptors and underlying engines (function) |
| [operator<<operator>>](discard_block_engine/operator_ltltgtgt "cpp/numeric/random/discard block engine/operator ltltgtgt")
(C++11) | performs stream input and output on pseudo-random number engine adaptor (function) |
### Member constants
| | |
| --- | --- |
| constexpr size\_t block\_size
[static] (C++11) | the size of the block, `P` (public static member constant) |
| constexpr size\_t used\_block
[static] (C++11) | the number of used numbers per block, `R` (public static member constant) |
cpp std::generate_canonical std::generate\_canonical
========================
| Defined in header `[<random>](../../header/random "cpp/header/random")` | | |
| --- | --- | --- |
|
```
template< class RealType, std::size_t Bits, class Generator >
RealType generate_canonical( Generator& g );
```
| | (since C++11) |
Generates a random floating point number in range \(\small [0,1)\)[0, 1).
To generate enough entropy, `generate_canonical()` will call `g()` exactly \(\small k\)k times, where \(\small k = \max(1, \lceil \frac{b}{\log\_2 R} \rceil)\)k = max(1, โ b / log
2 R โ) and.
* `b = [std::min](http://en.cppreference.com/w/cpp/algorithm/min)(Bits, [std::size\_t](http://en.cppreference.com/w/cpp/types/size_t){[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<RealType>::digits})`,
* `R = g.max() - g.min() + 1`.
### Parameters
| | | |
| --- | --- | --- |
| g | - | generator to use to acquire entropy |
### Return value
Floating point value in range \(\small [0,1)\)[0, 1).
### Exceptions
None except from those thrown by `g`.
### Notes
Some existing implementations have a bug where they may occasionally return `1.0` if `RealType` is `float` [GCC #63176](https://gcc.gnu.org/bugzilla/show_bug.cgi?id=63176) [LLVM #18767](https://bugs.llvm.org/show_bug.cgi?id=18767) [MSVC STL #1074](https://github.com/microsoft/STL/issues/1074). This is [LWG issue 2524](https://cplusplus.github.io/LWG/issue2524).
### Example
produce random numbers with 10 bits of randomness: this may produce only k\*R distinct values.
```
#include <random>
#include <iostream>
int main()
{
std::random_device rd;
std::mt19937 gen(rd());
for(int n=0; n<10; ++n) {
std::cout << std::generate_canonical<double, 10>(gen) << ' ';
}
}
```
Possible output:
```
0.208143 0.824147 0.0278604 0.343183 0.0173263 0.864057 0.647037 0.539467 0.0583497 0.609219
```
### See also
| | |
| --- | --- |
| [uniform\_real\_distribution](uniform_real_distribution "cpp/numeric/random/uniform real distribution")
(C++11) | produces real values evenly distributed across a range (class template) |
cpp std::subtract_with_carry_engine std::subtract\_with\_carry\_engine
==================================
| Defined in header `[<random>](../../header/random "cpp/header/random")` | | |
| --- | --- | --- |
|
```
template<
class UIntType,
std::size_t w, std::size_t s, std::size_t r
> class subtract_with_carry_engine;
```
| | (since C++11) |
Is a random number engine that uses [subtract with carry](https://en.wikipedia.org/wiki/subtract_with_carry "enwiki:subtract with carry") algorithm.
The state of a `subtract_with_carry_engine` consists of a sequence \(\small{\{ X\_i\}(0 \le i <r)}\){X
i} (0 โค i <r), every \(\small{X\_i}\)X
i is in interval \(\small{[0, 2^w)}\)[0, 2w
).
Let all subscripts applied to sequence be taken modulo `r`, `c` be the carry value which is either `0` or `1`. The state transition is performed as follows:
* let \(\small{Y=X\_{i-s}-X\_{i-r}-c}\)Y=X
i-s-X
i-r-c,
* set \(\small{X\_i}\)X
i to \(\small{Y \mod 2^w}\)Y mod 2w
,
* set `c` to `1`, if \(\small{Y<0}\)Y<0, to `0` otherwise.
The following typedefs define the random number engine with two commonly used parameter sets:
| Defined in header `[<random>](../../header/random "cpp/header/random")` |
| --- |
| Type | Definition |
| `ranlux24_base`(C++11) | `std::subtract\_with\_carry\_engine<[std::uint\_fast32\_t](http://en.cppreference.com/w/cpp/types/integer), 24, 10, 24>` |
| `ranlux48_base`(C++11) | `std::subtract\_with\_carry\_engine<[std::uint\_fast64\_t](http://en.cppreference.com/w/cpp/types/integer), 48, 5, 12>` |
### Template parameters
| | | |
| --- | --- | --- |
| UIntType | - | The result type generated by the generator. The effect is undefined if this is not one of `unsigned short`, `unsigned int`, `unsigned long`, or `unsigned long long`. |
| w | - | The word size, in bits, of the state sequence, `10 < w <= [std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<UIntType>::digits`. |
| s | - | The *short lag*. |
| r | - | The *long lag*, where `0 < s < r`. |
### Member types
| Member type | Definition |
| --- | --- |
| `result_type` (C++11) | The integral type generated by the engine. Results are undefined if this is not an unsigned integral type. |
### Member functions
| |
| --- |
| Construction and Seeding |
| [(constructor)](subtract_with_carry_engine/subtract_with_carry_engine "cpp/numeric/random/subtract with carry engine/subtract with carry engine")
(C++11) | constructs the engine (public member function) |
| [seed](subtract_with_carry_engine/seed "cpp/numeric/random/subtract with carry engine/seed")
(C++11) | sets the current state of the engine (public member function) |
| Generation |
| [operator()](subtract_with_carry_engine/operator() "cpp/numeric/random/subtract with carry engine/operator()")
(C++11) | advances the engine's state and returns the generated value (public member function) |
| [discard](subtract_with_carry_engine/discard "cpp/numeric/random/subtract with carry engine/discard")
(C++11) | advances the engine's state by a specified amount (public member function) |
| Characteristics |
| [min](subtract_with_carry_engine/min "cpp/numeric/random/subtract with carry engine/min")
[static] (C++11) | gets the smallest possible value in the output range (public static member function) |
| [max](subtract_with_carry_engine/max "cpp/numeric/random/subtract with carry engine/max")
[static] (C++11) | gets the largest possible value in the output range (public static member function) |
### Non-member functions
| | |
| --- | --- |
| [operator==operator!=](subtract_with_carry_engine/operator_cmp "cpp/numeric/random/subtract with carry engine/operator cmp")
(C++11)(C++11)(removed in C++20) | compares the internal states of two pseudo-random number engines (function) |
| [operator<<operator>>](subtract_with_carry_engine/operator_ltltgtgt "cpp/numeric/random/subtract with carry engine/operator ltltgtgt")
(C++11) | performs stream input and output on pseudo-random number engine (function template) |
### Member constants
| | |
| --- | --- |
| constexpr size\_t word\_size
[static] (C++11) | template parameter `w`, the word size (public static member constant) |
| constexpr size\_t short\_lag
[static] (C++11) | template parameter `s`, the short lag (public static member constant) |
| constexpr size\_t long\_lag
[static] (C++11) | template parameter `r`, the long lag (public static member constant) |
| constexpr UIntType default\_seed
[static] (C++11) | constant value `19780503u` (public static member constant) |
cpp std::shuffle_order_engine std::shuffle\_order\_engine
===========================
| Defined in header `[<random>](../../header/random "cpp/header/random")` | | |
| --- | --- | --- |
|
```
template<
class Engine,
std::size_t K
> class shuffle_order_engine;
```
| | (since C++11) |
`shuffle_order_engine` is a random number engine adaptor that shuffles the random numbers generated by the base engine. It maintains a table of size `K` and delivers a randomly selected number from that table when requested, replacing it with a number generated by the base engine.
The following typedef defines the random number engine with one commonly used parameter set:
| Defined in header `[<random>](../../header/random "cpp/header/random")` |
| --- |
| Type | Definition |
| `knuth_b`(C++11) | `std::shuffle\_order\_engine<[std::minstd\_rand0](http://en.cppreference.com/w/cpp/numeric/random/linear_congruential_engine), 256>` |
### Template parameters
| | | |
| --- | --- | --- |
| Engine | - | the type of the wrapped engine |
| K | - | the size of the internal table. Must be greater than 0 |
| Type requirements |
| -`Engine` must meet the requirements of [RandomNumberEngine](../../named_req/randomnumberengine "cpp/named req/RandomNumberEngine"). |
### Member types
| Member type | Definition |
| --- | --- |
| `result_type` | `Engine::result_type` |
### Member functions
| | |
| --- | --- |
| [(constructor)](shuffle_order_engine/shuffle_order_engine "cpp/numeric/random/shuffle order engine/shuffle order engine")
(C++11) | constructs the engine adaptor (public member function) |
| [seed](shuffle_order_engine/seed "cpp/numeric/random/shuffle order engine/seed")
(C++11) | sets the state of the underlying engine (public member function) |
| [base](shuffle_order_engine/base "cpp/numeric/random/shuffle order engine/base")
(C++11) | returns the underlying engine (public member function) |
| Generation |
| [operator()](shuffle_order_engine/operator() "cpp/numeric/random/shuffle order engine/operator()")
(C++11) | advances the state of the underlying engine and returns the generated value (public member function) |
| [discard](shuffle_order_engine/discard "cpp/numeric/random/shuffle order engine/discard")
(C++11) | advances the adaptor's state by a specified amount (public member function) |
| Characteristics |
| [min](shuffle_order_engine/min "cpp/numeric/random/shuffle order engine/min")
[static] (C++11) | gets the smallest possible value in the output range of the underlying engine. (public static member function) |
| [max](shuffle_order_engine/max "cpp/numeric/random/shuffle order engine/max")
[static] (C++11) | gets the largest possible value in the output range of the underlying engine. (public static member function) |
### Non-member functions
| | |
| --- | --- |
| [operator==operator!=](shuffle_order_engine/operator_cmp "cpp/numeric/random/shuffle order engine/operator cmp")
(C++11)(C++11)(removed in C++20) | compares the internal states of the adaptors and underlying engines (function) |
| [operator<<operator>>](shuffle_order_engine/operator_ltltgtgt "cpp/numeric/random/shuffle order engine/operator ltltgtgt")
(C++11) | performs stream input and output on pseudo-random number engine adaptor (function) |
### Member objects
| | |
| --- | --- |
| constexpr size\_t table\_size
[static] | the size of the internal table, `K` (public static member constant) |
| programming_docs |
cpp std::poisson_distribution std::poisson\_distribution
==========================
| Defined in header `[<random>](../../header/random "cpp/header/random")` | | |
| --- | --- | --- |
|
```
template< class IntType = int >
class poisson_distribution;
```
| | (since C++11) |
Produces random non-negative integer values i, distributed according to discrete probability function: \(P(i | \mu) = \frac{e^{-\mu}\mu^i}{i!}\)P(i|ฮผ) =
e-ฮผยทฮผi/i! The value obtained is the probability of exactly i occurrences of a random event if the expected, *mean* number of its occurrence under the same conditions (on the same time/space interval) is ฮผ.
`std::poisson_distribution` satisfies [RandomNumberDistribution](../../named_req/randomnumberdistribution "cpp/named req/RandomNumberDistribution").
### Template parameters
| | | |
| --- | --- | --- |
| IntType | - | The result type generated by the generator. The effect is undefined if this is not one of `short`, `int`, `long`, `long long`, `unsigned short`, `unsigned int`, `unsigned long`, or `unsigned long long`. |
### Member types
| Member type | Definition |
| --- | --- |
| `result_type` | `IntType` |
| `param_type`(C++11) | the type of the parameter set, see [RandomNumberDistribution](../../named_req/randomnumberdistribution "cpp/named req/RandomNumberDistribution"). |
### Member functions
| | |
| --- | --- |
| [(constructor)](poisson_distribution/poisson_distribution "cpp/numeric/random/poisson distribution/poisson distribution")
(C++11) | constructs new distribution (public member function) |
| [reset](poisson_distribution/reset "cpp/numeric/random/poisson distribution/reset")
(C++11) | resets the internal state of the distribution (public member function) |
| Generation |
| [operator()](poisson_distribution/operator() "cpp/numeric/random/poisson distribution/operator()")
(C++11) | generates the next random number in the distribution (public member function) |
| Characteristics |
| [mean](poisson_distribution/mean "cpp/numeric/random/poisson distribution/mean") | returns the *mean* distribution parameter (mean number of occurrences of the event) (public member function) |
| [param](poisson_distribution/param "cpp/numeric/random/poisson distribution/param")
(C++11) | gets or sets the distribution parameter object (public member function) |
| [min](poisson_distribution/min "cpp/numeric/random/poisson distribution/min")
(C++11) | returns the minimum potentially generated value (public member function) |
| [max](poisson_distribution/max "cpp/numeric/random/poisson distribution/max")
(C++11) | returns the maximum potentially generated value (public member function) |
### Non-member functions
| | |
| --- | --- |
| [operator==operator!=](poisson_distribution/operator_cmp "cpp/numeric/random/poisson distribution/operator cmp")
(C++11)(C++11)(removed in C++20) | compares two distribution objects (function) |
| [operator<<operator>>](poisson_distribution/operator_ltltgtgt "cpp/numeric/random/poisson distribution/operator ltltgtgt")
(C++11) | performs stream input and output on pseudo-random number distribution (function template) |
### Example
```
#include <iostream>
#include <iomanip>
#include <string>
#include <map>
#include <random>
int main()
{
std::random_device rd;
std::mt19937 gen(rd());
// if an event occurs 4 times a minute on average
// how often is it that it occurs n times in one minute?
std::poisson_distribution<> d(4);
std::map<int, int> hist;
for(int n=0; n<10000; ++n) {
++hist[d(gen)];
}
for(auto p : hist) {
std::cout << std::hex << p.first << ' '
<< std::string(p.second/100, '*') << '\n';
}
}
```
Possible output:
```
0 *
1 *******
2 **************
3 *******************
4 *******************
5 ***************
6 **********
7 *****
8 **
9 *
a
b
c
d
```
### External links
[Weisstein, Eric W. "Poisson Distribution."](http://mathworld.wolfram.com/PoissonDistribution.html) From MathWorld--A Wolfram Web Resource.
cpp std::normal_distribution std::normal\_distribution
=========================
| Defined in header `[<random>](../../header/random "cpp/header/random")` | | |
| --- | --- | --- |
|
```
template< class RealType = double >
class normal_distribution;
```
| | (since C++11) |
Generates random numbers according to the [Normal (or Gaussian) random number distribution](https://en.wikipedia.org/wiki/Normal_distribution "enwiki:Normal distribution"). It is defined as: \(\small{f(x;\mu,\sigma)}=\frac{1}{\sigma\sqrt{2\pi} }\exp{(-\frac{1}{2}{(\frac{x-\mu}{\sigma})}^2)}\)f(x; ฮผ,ฯ) =
1/ฯโ2ฯ expโ
โ
โ-1/2 โ
โ
โx-ฮผ/ฯโ
โ
โ 2
โ
โ
โ Here \(\small\mu\)ฮผ is the [mean](https://en.wikipedia.org/wiki/Mean "enwiki:Mean") and \(\small\sigma\)ฯ is the [standard deviation](https://en.wikipedia.org/wiki/Standard_deviation "enwiki:Standard deviation") (*stddev*).
`std::normal_distribution` satisfies all requirements of [RandomNumberDistribution](../../named_req/randomnumberdistribution "cpp/named req/RandomNumberDistribution").
### Template parameters
| | | |
| --- | --- | --- |
| RealType | - | The result type generated by the generator. The effect is undefined if this is not one of `float`, `double`, or `long double`. |
### Member types
| Member type | Definition |
| --- | --- |
| `result_type`(C++11) | `RealType` |
| `param_type`(C++11) | the type of the parameter set, see [RandomNumberDistribution](../../named_req/randomnumberdistribution "cpp/named req/RandomNumberDistribution"). |
### Member functions
| | |
| --- | --- |
| [(constructor)](normal_distribution/normal_distribution "cpp/numeric/random/normal distribution/normal distribution")
(C++11) | constructs new distribution (public member function) |
| [reset](normal_distribution/reset "cpp/numeric/random/normal distribution/reset")
(C++11) | resets the internal state of the distribution (public member function) |
| Generation |
| [operator()](normal_distribution/operator() "cpp/numeric/random/normal distribution/operator()")
(C++11) | generates the next random number in the distribution (public member function) |
| Characteristics |
| [meanstddev](normal_distribution/params "cpp/numeric/random/normal distribution/params") | returns the distribution parameters (public member function) |
| [param](normal_distribution/param "cpp/numeric/random/normal distribution/param")
(C++11) | gets or sets the distribution parameter object (public member function) |
| [min](normal_distribution/min "cpp/numeric/random/normal distribution/min")
(C++11) | returns the minimum potentially generated value (public member function) |
| [max](normal_distribution/max "cpp/numeric/random/normal distribution/max")
(C++11) | returns the maximum potentially generated value (public member function) |
### Non-member functions
| | |
| --- | --- |
| [operator==operator!=](normal_distribution/operator_cmp "cpp/numeric/random/normal distribution/operator cmp")
(C++11)(C++11)(removed in C++20) | compares two distribution objects (function) |
| [operator<<operator>>](normal_distribution/operator_ltltgtgt "cpp/numeric/random/normal distribution/operator ltltgtgt")
(C++11) | performs stream input and output on pseudo-random number distribution (function template) |
### Example
```
#include <iostream>
#include <iomanip>
#include <string>
#include <map>
#include <random>
#include <cmath>
int main()
{
std::random_device rd{};
std::mt19937 gen{rd()};
// values near the mean are the most likely
// standard deviation affects the dispersion of generated values from the mean
std::normal_distribution<> d{5,2};
std::map<int, int> hist{};
for(int n=0; n<10000; ++n) {
++hist[std::round(d(gen))];
}
for(auto p : hist) {
std::cout << std::setw(2)
<< p.first << ' ' << std::string(p.second/200, '*') << '\n';
}
}
```
Possible output:
```
-2
-1
0
1 *
2 ***
3 ******
4 ********
5 **********
6 ********
7 *****
8 ***
9 *
10
11
12
```
### External links
* [Weisstein, Eric W. "Normal Distribution."](http://mathworld.wolfram.com/NormalDistribution.html) From MathWorld--A Wolfram Web Resource.
* [Normal Distribution.](https://en.wikipedia.org/wiki/Normal_distribution "enwiki:Normal distribution") From Wikipedia.
cpp std::weibull_distribution std::weibull\_distribution
==========================
| Defined in header `[<random>](../../header/random "cpp/header/random")` | | |
| --- | --- | --- |
|
```
template< class RealType = double >
class weibull_distribution;
```
| | (since C++11) |
The `weibull_distribution` meets the requirements of a [RandomNumberDistribution](../../named_req/randomnumberdistribution "cpp/named req/RandomNumberDistribution") and produces random numbers according to the [Weibull distribution](https://en.wikipedia.org/wiki/Weibull_distribution "enwiki:Weibull distribution"): \(\small{f(x;a,b)=\frac{a}{b}{(\frac{x}{b})}^{a-1}\exp{(-{(\frac{x}{b})}^{a})} }\)f(x;a,b) =
a/b โ
โ
โx/bโ
โ
โ a-1
expโ
โ
โ-โ
โ
โx/bโ
โ
โ a
โ
โ
โ a is the [shape parameter](https://en.wikipedia.org/wiki/shape_parameter "enwiki:shape parameter") and b the [scale parameter](https://en.wikipedia.org/wiki/scale_parameter "enwiki:scale parameter").
`std::weibull_distribution` satisfies [RandomNumberDistribution](../../named_req/randomnumberdistribution "cpp/named req/RandomNumberDistribution").
### Template parameters
| | | |
| --- | --- | --- |
| RealType | - | The result type generated by the generator. The effect is undefined if this is not one of `float`, `double`, or `long double`. |
### Member types
| Member type | Definition |
| --- | --- |
| `result_type` | `RealType` |
| `param_type`(C++11) | the type of the parameter set, see [RandomNumberDistribution](../../named_req/randomnumberdistribution "cpp/named req/RandomNumberDistribution"). |
### Member functions
| | |
| --- | --- |
| [(constructor)](weibull_distribution/weibull_distribution "cpp/numeric/random/weibull distribution/weibull distribution")
(C++11) | constructs new distribution (public member function) |
| [reset](weibull_distribution/reset "cpp/numeric/random/weibull distribution/reset")
(C++11) | resets the internal state of the distribution (public member function) |
| Generation |
| [operator()](weibull_distribution/operator() "cpp/numeric/random/weibull distribution/operator()")
(C++11) | generates the next random number in the distribution (public member function) |
| Characteristics |
| [ab](weibull_distribution/params "cpp/numeric/random/weibull distribution/params") | returns the distribution parameters (public member function) |
| [param](weibull_distribution/param "cpp/numeric/random/weibull distribution/param")
(C++11) | gets or sets the distribution parameter object (public member function) |
| [min](weibull_distribution/min "cpp/numeric/random/weibull distribution/min")
(C++11) | returns the minimum potentially generated value (public member function) |
| [max](weibull_distribution/max "cpp/numeric/random/weibull distribution/max")
(C++11) | returns the maximum potentially generated value (public member function) |
### Non-member functions
| | |
| --- | --- |
| [operator==operator!=](weibull_distribution/operator_cmp "cpp/numeric/random/weibull distribution/operator cmp")
(C++11)(C++11)(removed in C++20) | compares two distribution objects (function) |
| [operator<<operator>>](weibull_distribution/operator_ltltgtgt "cpp/numeric/random/weibull distribution/operator ltltgtgt")
(C++11) | performs stream input and output on pseudo-random number distribution (function template) |
### Example
```
#include <iostream>
#include <iomanip>
#include <string>
#include <map>
#include <random>
#include <cmath>
int main()
{
std::random_device rd;
std::mt19937 gen(rd());
std::weibull_distribution<> d;
std::map<int, int> hist;
for(int n=0; n<10000; ++n) {
++hist[std::round(d(gen))];
}
for(auto p : hist) {
std::cout << std::fixed << std::setprecision(1) << std::setw(2)
<< p.first << ' ' << std::string(p.second/200, '*') << '\n';
}
}
```
Possible output:
```
0 *******************
1 *******************
2 ******
3 **
4
5
6
7
8
```
### External links
* [Weisstein, Eric W. "Weibull Distribution."](http://mathworld.wolfram.com/WeibullDistribution.html) From MathWorld--A Wolfram Web Resource.
* [Weibull distribution.](https://en.wikipedia.org/wiki/Weibull_distribution "enwiki:Weibull distribution") From Wikipedia.
cpp std::gamma_distribution std::gamma\_distribution
========================
| Defined in header `[<random>](../../header/random "cpp/header/random")` | | |
| --- | --- | --- |
|
```
template< class RealType = double >
class gamma_distribution;
```
| | (since C++11) |
Produces random positive floating-point values x, distributed according to probability density function: \(\mathsf{p}(x\mid\alpha,\beta) = \frac{e^{-x/\beta} }{\beta^\alpha\cdot\Gamma(\alpha)}\cdot x^{\alpha-1} \)P(x|ฮฑ,ฮฒ) =
e-x/ฮฒ/ฮฒฮฑ ยท ฮ(ฮฑ) ยท xฮฑ-1
where ฮฑ is known as the *shape* parameter and ฮฒ is known as the *scale* parameter. The shape parameter is sometimes denoted by the letter k and the scale parameter is sometimes denoted by the letter ฮธ.
For floating-point ฮฑ, the value obtained is the sum of ฮฑ independent exponentially distributed random variables, each of which has a mean of ฮฒ.
`std::gamma_distribution` satisfies [RandomNumberDistribution](../../named_req/randomnumberdistribution "cpp/named req/RandomNumberDistribution").
### Template parameters
| | | |
| --- | --- | --- |
| RealType | - | The result type generated by the generator. The effect is undefined if this is not one of `float`, `double`, or `long double`. |
### Member types
| Member type | Definition |
| --- | --- |
| `result_type` | `RealType` |
| `param_type`(C++11) | the type of the parameter set, see [RandomNumberDistribution](../../named_req/randomnumberdistribution "cpp/named req/RandomNumberDistribution"). |
### Member functions
| | |
| --- | --- |
| [(constructor)](gamma_distribution/gamma_distribution "cpp/numeric/random/gamma distribution/gamma distribution")
(C++11) | constructs new distribution (public member function) |
| [reset](gamma_distribution/reset "cpp/numeric/random/gamma distribution/reset")
(C++11) | resets the internal state of the distribution (public member function) |
| Generation |
| [operator()](gamma_distribution/operator() "cpp/numeric/random/gamma distribution/operator()")
(C++11) | generates the next random number in the distribution (public member function) |
| Characteristics |
| [alphabeta](gamma_distribution/params "cpp/numeric/random/gamma distribution/params") | returns the distribution parameters (public member function) |
| [param](gamma_distribution/param "cpp/numeric/random/gamma distribution/param")
(C++11) | gets or sets the distribution parameter object (public member function) |
| [min](gamma_distribution/min "cpp/numeric/random/gamma distribution/min")
(C++11) | returns the minimum potentially generated value (public member function) |
| [max](gamma_distribution/max "cpp/numeric/random/gamma distribution/max")
(C++11) | returns the maximum potentially generated value (public member function) |
### Non-member functions
| | |
| --- | --- |
| [operator==operator!=](gamma_distribution/operator_cmp "cpp/numeric/random/gamma distribution/operator cmp")
(C++11)(C++11)(removed in C++20) | compares two distribution objects (function) |
| [operator<<operator>>](gamma_distribution/operator_ltltgtgt "cpp/numeric/random/gamma distribution/operator ltltgtgt")
(C++11) | performs stream input and output on pseudo-random number distribution (function template) |
### Example
```
#include <iostream>
#include <iomanip>
#include <string>
#include <map>
#include <random>
int main()
{
std::random_device rd;
std::mt19937 gen(rd());
// A gamma distribution with alpha=1, and beta=2
// approximates an exponential distribution.
std::gamma_distribution<> d(1,2);
std::map<int, int> hist;
for(int n=0; n<10000; ++n) {
++hist[2*d(gen)];
}
for(auto p : hist) {
if (p.second/100. > 0.5)
std::cout
<< std::fixed << std::setprecision(1)
<< p.first/2.0 << '-' << (p.first+1)/2.0 << ' '
<< std::string(p.second/100, '*') << '\n';
}
}
```
Possible output:
```
0.0-0.5 **********************
0.5-1.0 ****************
1.0-1.5 *************
1.5-2.0 **********
2.0-2.5 ********
2.5-3.0 ******
3.0-3.5 *****
3.5-4.0 ****
4.0-4.5 ***
4.5-5.0 **
5.0-5.5 **
5.5-6.0 *
6.0-6.5 *
6.5-7.0
7.0-7.5
7.5-8.0
```
### External links
[Weisstein, Eric W. "Gamma Distribution."](http://mathworld.wolfram.com/GammaDistribution.html) From MathWorld--A Wolfram Web Resource.
cpp std::extreme_value_distribution std::extreme\_value\_distribution
=================================
| Defined in header `[<random>](../../header/random "cpp/header/random")` | | |
| --- | --- | --- |
|
```
template< class RealType = double >
class extreme_value_distribution;
```
| | (since C++11) |
Produces random numbers according to the [extreme value distribution](https://en.wikipedia.org/wiki/Generalized_extreme_value_distribution "enwiki:Generalized extreme value distribution") (it is also known as Gumbel Type I, log-Weibull, Fisher-Tippett Type I): \({\small p(x;a,b) = \frac{1}{b} \exp{(\frac{a-x}{b}-\exp{(\frac{a-x}{b})})} }\)p(x;a,b) =
1/b expโ
โ
โa-x/b - expโ
โ
โa-x/bโ
โ
โ โ
โ
โ `std::extreme_value_distribution` satisfies all requirements of [RandomNumberDistribution](../../named_req/randomnumberdistribution "cpp/named req/RandomNumberDistribution").
### Template parameters
| | | |
| --- | --- | --- |
| RealType | - | The result type generated by the generator. The effect is undefined if this is not one of `float`, `double`, or `long double`. |
### Member types
| Member type | Definition |
| --- | --- |
| `result_type` | `RealType` |
| `param_type`(C++11) | the type of the parameter set, see [RandomNumberDistribution](../../named_req/randomnumberdistribution "cpp/named req/RandomNumberDistribution"). |
### Member functions
| | |
| --- | --- |
| [(constructor)](extreme_value_distribution/extreme_value_distribution "cpp/numeric/random/extreme value distribution/extreme value distribution")
(C++11) | constructs new distribution (public member function) |
| [reset](extreme_value_distribution/reset "cpp/numeric/random/extreme value distribution/reset")
(C++11) | resets the internal state of the distribution (public member function) |
| Generation |
| [operator()](extreme_value_distribution/operator() "cpp/numeric/random/extreme value distribution/operator()")
(C++11) | generates the next random number in the distribution (public member function) |
| Characteristics |
| [ab](extreme_value_distribution/params "cpp/numeric/random/extreme value distribution/params") | returns the distribution parameters (public member function) |
| [param](extreme_value_distribution/param "cpp/numeric/random/extreme value distribution/param")
(C++11) | gets or sets the distribution parameter object (public member function) |
| [min](extreme_value_distribution/min "cpp/numeric/random/extreme value distribution/min")
(C++11) | returns the minimum potentially generated value (public member function) |
| [max](extreme_value_distribution/max "cpp/numeric/random/extreme value distribution/max")
(C++11) | returns the maximum potentially generated value (public member function) |
### Non-member functions
| | |
| --- | --- |
| [operator==operator!=](extreme_value_distribution/operator_cmp "cpp/numeric/random/extreme value distribution/operator cmp")
(C++11)(C++11)(removed in C++20) | compares two distribution objects (function) |
| [operator<<operator>>](extreme_value_distribution/operator_ltltgtgt "cpp/numeric/random/extreme value distribution/operator ltltgtgt")
(C++11) | performs stream input and output on pseudo-random number distribution (function template) |
### Example
```
#include <random>
#include <map>
#include <iomanip>
#include <algorithm>
#include <iostream>
#include <vector>
#include <cmath>
template <int Height = 5, int BarWidth = 1, int Padding = 1, int Offset = 0, class Seq>
void draw_vbars(Seq&& s, const bool DrawMinMax = true) {
static_assert((Height > 0) && (BarWidth > 0) && (Padding >= 0) && (Offset >= 0));
auto cout_n = [](auto&& v, int n = 1) { while (n-- > 0) std::cout << v; };
const auto [min, max] = std::minmax_element(std::cbegin(s), std::cend(s));
std::vector<std::div_t> qr;
for (typedef decltype(*cbegin(s)) V; V e : s)
qr.push_back(std::div(std::lerp(V(0), Height*8, (e - *min)/(*max - *min)), 8));
for (auto h{Height}; h-- > 0; cout_n('\n')) {
cout_n(' ', Offset);
for (auto dv : qr) {
const auto q{dv.quot}, r{dv.rem};
unsigned char d[] { 0xe2, 0x96, 0x88, 0 }; // Full Block: 'โ'
q < h ? d[0] = ' ', d[1] = 0 : q == h ? d[2] -= (7 - r) : 0;
cout_n(d, BarWidth), cout_n(' ', Padding);
}
if (DrawMinMax && Height > 1)
Height - 1 == h ? std::cout << "โฌ " << *max:
h ? std::cout << "โ "
: std::cout << "โด " << *min;
}
}
int main()
{
std::random_device rd{};
std::mt19937 gen{rd()};
std::extreme_value_distribution<> d{-1.618f, 1.618f};
const int norm = 10'000;
const float cutoff = 0.000'3f;
std::map<int, int> hist{};
for(int n=0; n<norm; ++n) {
++hist[std::round(d(gen))];
}
std::vector<float> bars;
std::vector<int> indices;
for(const auto& [n,p] : hist) {
float x = p*(1.0f/norm);
if (x > cutoff) {
bars.push_back(x);
indices.push_back(n);
}
}
draw_vbars<8,4>(bars);
for (int n : indices) {
std::cout << " " << std::setw(2) << n << " ";
}
std::cout << '\n';
}
```
Possible output:
```
โโโโ โ
โ
โ
โ
โฌ 0.2186
โโโโ โโโโ โ
โโโโ โโโโ โโโโ โโโโ โ
โโโโ โโโโ โโโโ โโโโ โ
โโโโ โโโโ โโโโ โโโโ โโโโ โ
โโโโ โโโโ โโโโ โโโโ โโโโ โโโโ โ
โโโโ โโโโ โโโโ โโโโ โโโโ โโโโ โโโโ โโโโ โ
โโโโ โโโโ โโโโ โโโโ โโโโ โโโโ โโโโ โโโโ โโโโ โโโโ โโโโ โโโโ โโโโ โโโโ โโโโ โโโโ โด 0.0005
-5 -4 -3 -2 -1 0 1 2 3 4 5 6 7 8 9 10
```
### External links
[Weisstein, Eric W. "Extreme Value Distribution."](http://mathworld.wolfram.com/ExtremeValueDistribution.html) From MathWorld--A Wolfram Web Resource.
| programming_docs |
cpp std::negative_binomial_distribution std::negative\_binomial\_distribution
=====================================
| Defined in header `[<random>](../../header/random "cpp/header/random")` | | |
| --- | --- | --- |
|
```
template< class IntType = int >
class negative_binomial_distribution;
```
| | (since C++11) |
Produces random non-negative integer values i, distributed according to discrete probability function: \(P(i|k, p) = \binom{k + i - 1}{i} \cdot p^k \cdot (1 - p)^i\)P(i|k,p) =
โ
โ
โk + i โ 1
iโ
โ
โ ยท pk
ยท (1 โ p)i
The value represents the number of failures in a series of independent yes/no trials (each succeeds with probability p), before exactly k successes occur.
`std::negative_binomial_distribution` satisfies [RandomNumberDistribution](../../named_req/randomnumberdistribution "cpp/named req/RandomNumberDistribution").
### Template parameters
| | | |
| --- | --- | --- |
| IntType | - | The result type generated by the generator. The effect is undefined if this is not one of `short`, `int`, `long`, `long long`, `unsigned short`, `unsigned int`, `unsigned long`, or `unsigned long long`. |
### Member types
| Member type | Definition |
| --- | --- |
| `result_type` | `IntType` |
| `param_type`(C++11) | the type of the parameter set, see [RandomNumberDistribution](../../named_req/randomnumberdistribution "cpp/named req/RandomNumberDistribution"). |
### Member functions
| | |
| --- | --- |
| [(constructor)](negative_binomial_distribution/negative_binomial_distribution "cpp/numeric/random/negative binomial distribution/negative binomial distribution")
(C++11) | constructs new distribution (public member function) |
| [reset](negative_binomial_distribution/reset "cpp/numeric/random/negative binomial distribution/reset")
(C++11) | resets the internal state of the distribution (public member function) |
| Generation |
| [operator()](negative_binomial_distribution/operator() "cpp/numeric/random/negative binomial distribution/operator()")
(C++11) | generates the next random number in the distribution (public member function) |
| Characteristics |
| [pk](negative_binomial_distribution/params "cpp/numeric/random/negative binomial distribution/params") | returns the distribution parameters (public member function) |
| [param](negative_binomial_distribution/param "cpp/numeric/random/negative binomial distribution/param")
(C++11) | gets or sets the distribution parameter object (public member function) |
| [min](negative_binomial_distribution/min "cpp/numeric/random/negative binomial distribution/min")
(C++11) | returns the minimum potentially generated value (public member function) |
| [max](negative_binomial_distribution/max "cpp/numeric/random/negative binomial distribution/max")
(C++11) | returns the maximum potentially generated value (public member function) |
### Non-member functions
| | |
| --- | --- |
| [operator==operator!=](negative_binomial_distribution/operator_cmp "cpp/numeric/random/negative binomial distribution/operator cmp")
(C++11)(C++11)(removed in C++20) | compares two distribution objects (function) |
| [operator<<operator>>](negative_binomial_distribution/operator_ltltgtgt "cpp/numeric/random/negative binomial distribution/operator ltltgtgt")
(C++11) | performs stream input and output on pseudo-random number distribution (function template) |
### Example
```
#include <iostream>
#include <iomanip>
#include <string>
#include <map>
#include <random>
int main()
{
std::random_device rd;
std::mt19937 gen(rd());
// Pat goes door-to-door selling cookies
// At each house, there's a 75% chance that she sells one box
// how many times will she be turned away before selling 5 boxes?
std::negative_binomial_distribution<> d(5, 0.75);
std::map<int, int> hist;
for(int n=0; n<10000; ++n) {
++hist[d(gen)];
}
for(auto p : hist) {
std::cout << std::setw(2) << p.first << ' '
<< std::string(p.second/100, '*') << '\n';
}
}
```
Possible output:
```
0 ***********************
1 *****************************
2 **********************
3 *************
4 ******
5 ***
6 *
7
8
9
10
11
```
### External links
[Weisstein, Eric W. "Negative Binomial Distribution."](http://mathworld.wolfram.com/NegativeBinomialDistribution.html) From MathWorld--A Wolfram Web Resource.
cpp std::linear_congruential_engine std::linear\_congruential\_engine
=================================
| Defined in header `[<random>](../../header/random "cpp/header/random")` | | |
| --- | --- | --- |
|
```
template<
class UIntType,
UIntType a,
UIntType c,
UIntType m
> class linear_congruential_engine;
```
| | (since C++11) |
`linear_congruential_engine` is a random number engine based on [Linear congruential generator (LCG)](https://en.wikipedia.org/wiki/Linear_congruential_generator "enwiki:Linear congruential generator"). A LCG has a state that consists of a single integer.
The transition algorithm of the LCG function is \(\small{x\_{i+1}\leftarrow(a x\_i + c)\mod m}\)x
i+1 โ (ax
i+c) mod m.
The following typedefs define the random number engine with two commonly used parameter sets:
| Defined in header `[<random>](../../header/random "cpp/header/random")` |
| --- |
| Type | Definition |
| `minstd_rand0`(C++11) | `std::linear\_congruential\_engine<[std::uint\_fast32\_t](http://en.cppreference.com/w/cpp/types/integer), 16807, 0, 2147483647>` Discovered in 1969 by Lewis, Goodman and Miller, adopted as "Minimal standard" in 1988 by Park and Miller. |
| `minstd_rand`(C++11) | `std::linear\_congruential\_engine<[std::uint\_fast32\_t](http://en.cppreference.com/w/cpp/types/integer), 48271, 0, 2147483647>` Newer "Minimum standard", recommended by Park, Miller, and Stockmeyer in 1993. |
### Template parameters
| | | |
| --- | --- | --- |
| UIntType | - | The result type generated by the generator. The effect is undefined if this is not one of `unsigned short`, `unsigned int`, `unsigned long`, or `unsigned long long`. |
| a | - | the multiplier term |
| c | - | the increment term |
| m | - | the modulus term |
### Member types
| Member type | Definition |
| --- | --- |
| `result_type`(C++11) | The integral type generated by the engine. Results are undefined if this is not an unsigned integral type. |
### Member functions
| |
| --- |
| Construction and Seeding |
| [(constructor)](linear_congruential_engine/linear_congruential_engine "cpp/numeric/random/linear congruential engine/linear congruential engine")
(C++11) | constructs the engine (public member function) |
| [seed](linear_congruential_engine/seed "cpp/numeric/random/linear congruential engine/seed")
(C++11) | sets the current state of the engine (public member function) |
| Generation |
| [operator()](linear_congruential_engine/operator() "cpp/numeric/random/linear congruential engine/operator()")
(C++11) | advances the engine's state and returns the generated value (public member function) |
| [discard](linear_congruential_engine/discard "cpp/numeric/random/linear congruential engine/discard")
(C++11) | advances the engine's state by a specified amount (public member function) |
| Characteristics |
| [min](linear_congruential_engine/min "cpp/numeric/random/linear congruential engine/min")
[static] (C++11) | gets the smallest possible value in the output range (public static member function) |
| [max](linear_congruential_engine/max "cpp/numeric/random/linear congruential engine/max")
[static] (C++11) | gets the largest possible value in the output range (public static member function) |
### Non-member functions
| | |
| --- | --- |
| [operator==operator!=](linear_congruential_engine/operator_cmp "cpp/numeric/random/linear congruential engine/operator cmp")
(C++11)(C++11)(removed in C++20) | compares the internal states of two pseudo-random number engines (function) |
| [operator<<operator>>](linear_congruential_engine/operator_ltltgtgt "cpp/numeric/random/linear congruential engine/operator ltltgtgt")
(C++11) | performs stream input and output on pseudo-random number engine (function template) |
### Member constants
| | |
| --- | --- |
| constexpr UIntType multiplier
[static] (C++11) | the multiplier term (a). (public static member constant) |
| constexpr UIntType increment
[static] (C++11) | the increment term (c). (public static member constant) |
| constexpr UIntType modulus
[static] (C++11) | the modulus term (m). (public static member constant) |
| constexpr UIntType default\_seed
[static] (C++11) | the default seed (`1`). (public static member constant) |
cpp std::piecewise_linear_distribution std::piecewise\_linear\_distribution
====================================
| Defined in header `[<random>](../../header/random "cpp/header/random")` | | |
| --- | --- | --- |
|
```
template< class RealType = double >
class piecewise_linear_distribution;
```
| | (since C++11) |
`std::piecewise_linear_distribution` produces random floating-point numbers, which are distributed according to a linear probability density function within each of the several subintervals \(\small{[b\_i, b\_{i+1})}\)[b
i, b
i+1). The distribution is such that the probability density at each interval boundary is exactly the predefined value \(\small{p\_i}\)p
i. The probability density for any \(\small{ b\_i \le x < b\_{i+1} }\)b.
iโคx<b
i+1 is \(\small{p\_i\frac{b\_{i+1}-x}{b\_{i+1}-b\_i} + p\_{i+1}\frac{x-b\_i}{b\_{i+1}-b\_i} }\)bi+1-x/bi+1-bi + x-bi/bi+1-bi , where probability densities at interval boundaries \(\small{p\_k}\)p
k are calculated as \(\small{w\_k/S}\)w
k/S where \(\small{S}\)S is the sum of all \(\small{\frac{1}{2}(w\_k + w\_{k+1})(b\_{k+1} - b\_k)}\)1/2(w
k+w
k+1)(b
k+1โb
k). The set of interval boundaries \(\small{b\_i}\)b
i and the set of weights at boundaries \(\small{w\_i}\)w
i are the parameters of this distribution.
`std::piecewise_linear_distribution` satisfies all requirements of [RandomNumberDistribution](../../named_req/randomnumberdistribution "cpp/named req/RandomNumberDistribution").
### Template parameters
| | | |
| --- | --- | --- |
| RealType | - | The result type generated by the generator. The effect is undefined if this is not one of `float`, `double`, or `long double`. |
### Member types
| Member type | Definition |
| --- | --- |
| `result_type`(C++11) | `RealType` |
| `param_type`(C++11) | the type of the parameter set, see [RandomNumberDistribution](../../named_req/randomnumberdistribution "cpp/named req/RandomNumberDistribution"). |
### Member functions
| | |
| --- | --- |
| [(constructor)](piecewise_linear_distribution/piecewise_linear_distribution "cpp/numeric/random/piecewise linear distribution/piecewise linear distribution")
(C++11) | constructs new distribution (public member function) |
| [reset](piecewise_linear_distribution/reset "cpp/numeric/random/piecewise linear distribution/reset")
(C++11) | resets the internal state of the distribution (public member function) |
| Generation |
| [operator()](piecewise_linear_distribution/operator() "cpp/numeric/random/piecewise linear distribution/operator()")
(C++11) | generates the next random number in the distribution (public member function) |
| Characteristics |
| [intervalsdensities](piecewise_linear_distribution/params "cpp/numeric/random/piecewise linear distribution/params") | returns the distribution parameters (public member function) |
| [param](piecewise_linear_distribution/param "cpp/numeric/random/piecewise linear distribution/param")
(C++11) | gets or sets the distribution parameter object (public member function) |
| [min](piecewise_linear_distribution/min "cpp/numeric/random/piecewise linear distribution/min")
(C++11) | returns the minimum potentially generated value (public member function) |
| [max](piecewise_linear_distribution/max "cpp/numeric/random/piecewise linear distribution/max")
(C++11) | returns the maximum potentially generated value (public member function) |
### Non-member functions
| | |
| --- | --- |
| [operator==operator!=](piecewise_linear_distribution/operator_cmp "cpp/numeric/random/piecewise linear distribution/operator cmp")
(C++11)(C++11)(removed in C++20) | compares two distribution objects (function) |
| [operator<<operator>>](piecewise_linear_distribution/operator_ltltgtgt "cpp/numeric/random/piecewise linear distribution/operator ltltgtgt")
(C++11) | performs stream input and output on pseudo-random number distribution (function template) |
### Example
```
#include <iostream>
#include <iomanip>
#include <string>
#include <map>
#include <random>
int main()
{
std::random_device rd;
std::mt19937 gen{rd()};
// increase the probability from 0 to 5
// remain flat from 5 to 10
// decrease from 10 to 15 at the same rate
std::vector<double> i{0, 5, 10, 15};
std::vector<double> w{0, 1, 1, 0};
std::piecewise_linear_distribution<> d{i.begin(), i.end(), w.begin()};
std::map<int, int> hist;
for(int n=0; n<10000; ++n) {
++hist[d(gen)];
}
for(auto p : hist) {
std::cout << std::setw(2) << std::setfill('0') << p.first << ' '
<< std::string(p.second/100,'*') << '\n';
}
}
```
Possible output:
```
00 *
01 ***
02 ****
03 ******
04 *********
05 *********
06 *********
07 **********
08 *********
09 **********
10 *********
11 *******
12 ****
13 ***
14 *
```
cpp std::bernoulli_distribution std::bernoulli\_distribution
============================
| Defined in header `[<random>](../../header/random "cpp/header/random")` | | |
| --- | --- | --- |
|
```
class bernoulli_distribution;
```
| | (since C++11) |
Produces random boolean values, according to the discrete probability function. The probability of `true` is P(b|p) =
โง
โจ
โฉp if `b == true`
1 โ p if `b == false` `std::bernoulli_distribution` satisfies [RandomNumberDistribution](../../named_req/randomnumberdistribution "cpp/named req/RandomNumberDistribution").
### Member types
| Member type | Definition |
| --- | --- |
| `result_type` | `bool` |
| `param_type`(C++11) | the type of the parameter set, see [RandomNumberDistribution](../../named_req/randomnumberdistribution "cpp/named req/RandomNumberDistribution"). |
### Member functions
| | |
| --- | --- |
| [(constructor)](bernoulli_distribution/bernoulli_distribution "cpp/numeric/random/bernoulli distribution/bernoulli distribution")
(C++11) | constructs new distribution (public member function) |
| [reset](bernoulli_distribution/reset "cpp/numeric/random/bernoulli distribution/reset")
(C++11) | resets the internal state of the distribution (public member function) |
| Generation |
| [operator()](bernoulli_distribution/operator() "cpp/numeric/random/bernoulli distribution/operator()")
(C++11) | generates the next random number in the distribution (public member function) |
| Characteristics |
| [p](bernoulli_distribution/p "cpp/numeric/random/bernoulli distribution/p") | returns the *p* distribution parameter (probability of generating `true`) (public member function) |
| [param](bernoulli_distribution/param "cpp/numeric/random/bernoulli distribution/param")
(C++11) | gets or sets the distribution parameter object (public member function) |
| [min](bernoulli_distribution/min "cpp/numeric/random/bernoulli distribution/min")
(C++11) | returns the minimum potentially generated value (public member function) |
| [max](bernoulli_distribution/max "cpp/numeric/random/bernoulli distribution/max")
(C++11) | returns the maximum potentially generated value (public member function) |
### Non-member functions
| | |
| --- | --- |
| [operator==operator!=](bernoulli_distribution/operator_cmp "cpp/numeric/random/bernoulli distribution/operator cmp")
(C++11)(C++11)(removed in C++20) | compares two distribution objects (function) |
| [operator<<operator>>](bernoulli_distribution/operator_ltltgtgt "cpp/numeric/random/bernoulli distribution/operator ltltgtgt")
(C++11) | performs stream input and output on pseudo-random number distribution (function template) |
### Example
```
#include <iostream>
#include <iomanip>
#include <string>
#include <map>
#include <random>
int main()
{
std::random_device rd;
std::mt19937 gen(rd());
// give "true" 1/4 of the time
// give "false" 3/4 of the time
std::bernoulli_distribution d(0.25);
std::map<bool, int> hist;
for(int n=0; n<10000; ++n) {
++hist[d(gen)];
}
for(auto p : hist) {
std::cout << std::boolalpha << std::setw(5) << p.first
<< ' ' << std::string(p.second/500, '*') << '\n';
}
}
```
Possible output:
```
false ***************
true ****
```
### External links
[Weisstein, Eric W. "Bernoulli Distribution."](http://mathworld.wolfram.com/BernoulliDistribution.html) From MathWorld--A Wolfram Web Resource.
cpp RAND_MAX RAND\_MAX
=========
| Defined in header `[<cstdlib>](../../header/cstdlib "cpp/header/cstdlib")` | | |
| --- | --- | --- |
|
```
#define RAND_MAX /*implementation defined*/
```
| | |
Expands to an integer constant expression equal to the maximum value returned by the function `[std::rand](rand "cpp/numeric/random/rand")`. This value is implementation dependent. It's guaranteed that this value is at least `32767`.
### Example
```
#include <climits>
#include <cstdlib>
#include <ctime>
#include <iostream>
int main()
{
// use current time as seed for random generator
std::srand(std::time(NULL));
std::cout << "RAND_MAX: " << RAND_MAX << '\n'
<< "INT_MAX: " << INT_MAX << '\n'
<< "Random value on [0,1]: "
<< static_cast<double>(std::rand()) / RAND_MAX << '\n';
}
```
Possible output:
```
RAND_MAX: 2147483647
INT_MAX: 2147483647
Random value on [0,1]: 0.618608
```
### See also
| | |
| --- | --- |
| [rand](rand "cpp/numeric/random/rand") | generates a pseudo-random number (function) |
| [srand](srand "cpp/numeric/random/srand") | seeds pseudo-random number generator (function) |
| [C documentation](https://en.cppreference.com/w/c/numeric/random/RAND_MAX "c/numeric/random/RAND MAX") for `RAND_MAX` |
cpp std::fisher_f_distribution std::fisher\_f\_distribution
============================
| Defined in header `[<random>](../../header/random "cpp/header/random")` | | |
| --- | --- | --- |
|
```
template< class RealType = double >
class fisher_f_distribution;
```
| | (since C++11) |
Produces random numbers according to the [f-distribution](https://en.wikipedia.org/wiki/F-distribution "enwiki:F-distribution"): \(P(x;m,n)=\frac{\Gamma{(\frac{m+n}{2})} }{\Gamma{(\frac{m}{2})}\Gamma{(\frac{n}{2})} }{(\frac{m}{n})}^{\frac{m}{2} }x^{\frac{m}{2}-1}{(1+\frac{m}{n}x)}^{-\frac{m+n}{2} }\)P(x;m,n) =
ฮ((m+n)/2) / ฮ(m/2) ฮ(n/2) (m/n)m/2
x(m/2)-1
(1+mx/n)-(m+n)/2
\(\small m\)m and \(\small n\)n are the [degrees of freedom](https://en.wikipedia.org/wiki/degrees_of_freedom_(statistics) "enwiki:degrees of freedom (statistics)").
`std::fisher_f_distribution` satisfies all requirements of [RandomNumberDistribution](../../named_req/randomnumberdistribution "cpp/named req/RandomNumberDistribution").
### Template parameters
| | | |
| --- | --- | --- |
| RealType | - | The result type generated by the generator. The effect is undefined if this is not one of `float`, `double`, or `long double`. |
### Member types
| Member type | Definition |
| --- | --- |
| `result_type`(C++11) | `RealType` |
| `param_type`(C++11) | the type of the parameter set, see [RandomNumberDistribution](../../named_req/randomnumberdistribution "cpp/named req/RandomNumberDistribution"). |
### Member functions
| | |
| --- | --- |
| [(constructor)](fisher_f_distribution/fisher_f_distribution "cpp/numeric/random/fisher f distribution/fisher f distribution")
(C++11) | constructs new distribution (public member function) |
| [reset](fisher_f_distribution/reset "cpp/numeric/random/fisher f distribution/reset")
(C++11) | resets the internal state of the distribution (public member function) |
| Generation |
| [operator()](fisher_f_distribution/operator() "cpp/numeric/random/fisher f distribution/operator()")
(C++11) | generates the next random number in the distribution (public member function) |
| Characteristics |
| [mn](fisher_f_distribution/params "cpp/numeric/random/fisher f distribution/params") | returns the distribution parameters (public member function) |
| [param](fisher_f_distribution/param "cpp/numeric/random/fisher f distribution/param")
(C++11) | gets or sets the distribution parameter object (public member function) |
| [min](fisher_f_distribution/min "cpp/numeric/random/fisher f distribution/min")
(C++11) | returns the minimum potentially generated value (public member function) |
| [max](fisher_f_distribution/max "cpp/numeric/random/fisher f distribution/max")
(C++11) | returns the maximum potentially generated value (public member function) |
### Non-member functions
| | |
| --- | --- |
| [operator==operator!=](fisher_f_distribution/operator_cmp "cpp/numeric/random/fisher f distribution/operator cmp")
(C++11)(C++11)(removed in C++20) | compares two distribution objects (function) |
| [operator<<operator>>](fisher_f_distribution/operator_ltltgtgt "cpp/numeric/random/fisher f distribution/operator ltltgtgt")
(C++11) | performs stream input and output on pseudo-random number distribution (function template) |
### Example
```
#include <random>
#include <iomanip>
#include <map>
#include <algorithm>
#include <iostream>
#include <vector>
#include <cmath>
template <int Height = 5, int BarWidth = 1, int Padding = 1, int Offset = 0, class Seq>
void draw_vbars(Seq&& s, const bool DrawMinMax = true) {
static_assert((Height > 0) && (BarWidth > 0) && (Padding >= 0) && (Offset >= 0));
auto cout_n = [](auto&& v, int n = 1) { while (n-- > 0) std::cout << v; };
const auto [min, max] = std::minmax_element(std::cbegin(s), std::cend(s));
std::vector<std::div_t> qr;
for (typedef decltype(*cbegin(s)) V; V e : s)
qr.push_back(std::div(std::lerp(V(0), Height*8, (e - *min)/(*max - *min)), 8));
for (auto h{Height}; h-- > 0; cout_n('\n')) {
cout_n(' ', Offset);
for (auto dv : qr) {
const auto q{dv.quot}, r{dv.rem};
unsigned char d[] { 0xe2, 0x96, 0x88, 0 }; // Full Block: 'โ'
q < h ? d[0] = ' ', d[1] = 0 : q == h ? d[2] -= (7 - r) : 0;
cout_n(d, BarWidth), cout_n(' ', Padding);
}
if (DrawMinMax && Height > 1)
Height - 1 == h ? std::cout << "โฌ " << *max:
h ? std::cout << "โ "
: std::cout << "โด " << *min;
}
}
int main() {
std::random_device rd{};
std::mt19937 gen{rd()};
auto fisher = [&gen](const float d1, const float d2) {
std::fisher_f_distribution<float> d{ d1 /* m */, d2 /* n */};
const int norm = 1'00'00;
const float cutoff = 0.002f;
std::map<int, int> hist{};
for (int n=0; n!=norm; ++n) { ++hist[std::round(d(gen))]; }
std::vector<float> bars;
std::vector<int> indices;
for (auto const& [n, p] : hist) {
if (float x = p * (1.0/norm); cutoff < x) {
bars.push_back(x);
indices.push_back(n);
}
}
std::cout << "dโ = " << d1 << ", dโ = " << d2 << ":\n";
draw_vbars<4,3>(bars);
for (int n : indices) { std::cout << "" << std::setw(2) << n << " "; }
std::cout << "\n\n";
};
fisher(/* dโ = */ 1.0f, /* dโ = */ 5.0f);
fisher(/* dโ = */ 15.0f, /* dโ = */ 10.f);
fisher(/* dโ = */ 100.0f, /* dโ = */ 3.0f);
}
```
Possible output:
```
dโ = 1, dโ = 5:
โโโ โฌ 0.4956
โโโ โ
โโโ โโโ โ
โโโ โโโ โโโ โโโ โโโ โโโ โโโ โโโ โโโ โโโ โโโ โโโ โโโ โโโ โด 0.0021
0 1 2 3 4 5 6 7 8 9 10 11 12 14
dโ = 15, dโ = 10:
โโโ โฌ 0.6252
โโโ โ
โโโ โโโ โ
โโโ โโโ โโโ โโโ โโโ โโโ โโโ โด 0.0023
0 1 2 3 4 5 6
dโ = 100, dโ = 3:
โโโ โฌ 0.4589
โโโ โ
โโโ โโโ โ
โ
โ
โ
โโโ โโโ โโโ โโโ โโโ โโโ โโโ โโโ โโโ โโโ โโโ โโโ โโโ โโโ โโโ โโโ โโโ โด 0.0021
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
```
### External links
[Weisstein, Eric W. "F-Distribution."](http://mathworld.wolfram.com/F-Distribution.html) From MathWorld--A Wolfram Web Resource.
| programming_docs |
cpp std::rand std::rand
=========
| Defined in header `[<cstdlib>](../../header/cstdlib "cpp/header/cstdlib")` | | |
| --- | --- | --- |
|
```
int rand();
```
| | |
Returns a pseudo-random integral value between `โ0โ` and `[RAND\_MAX](rand_max "cpp/numeric/random/RAND MAX")` (`โ0โ` and `RAND_MAX` included).
`[std::srand()](srand "cpp/numeric/random/srand")` seeds the pseudo-random number generator used by `rand()`. If `rand()` is used before any calls to `[std::srand()](srand "cpp/numeric/random/srand")`, `rand()` behaves as if it was seeded with `[std::srand](http://en.cppreference.com/w/cpp/numeric/random/srand)(1)`.
Each time `rand()` is seeded with `[std::srand()](srand "cpp/numeric/random/srand")`, it must produce the same sequence of values on successive calls.
Other functions in the standard library may call `rand`. It is implementation-defined which functions do so.
It is implementation-defined whether `rand()` is thread-safe.
### Parameters
(none).
### Return value
Pseudo-random integral value between `โ0โ` and `[RAND\_MAX](rand_max "cpp/numeric/random/RAND MAX")`.
### Notes
There are no guarantees as to the quality of the random sequence produced. In the past, some implementations of `rand()` have had serious shortcomings in the randomness, distribution and period of the sequence produced (in one well-known example, the low-order bit simply alternated between `1` and `0` between calls).
`rand()` is not recommended for serious random-number generation needs. It is recommended to use C++11's [random number generation](../random "cpp/numeric/random") facilities to replace rand(). (since C++11).
### Example
```
#include <cstdlib>
#include <iostream>
#include <ctime>
int main()
{
std::srand(std::time(nullptr)); // use current time as seed for random generator
int random_variable = std::rand();
std::cout << "Random value on [0 " << RAND_MAX << "]: "
<< random_variable << '\n';
// roll 6-sided dice 20 times
for (int n=0; n != 20; ++n) {
int x = 7;
while(x > 6)
x = 1 + std::rand()/((RAND_MAX + 1u)/6); // Note: 1+rand()%6 is biased
std::cout << x << ' ';
}
}
```
Possible output:
```
Random value on [0 2147483647]: 726295113
6 3 6 2 6 5 6 3 1 1 1 6 6 6 4 1 3 6 4 2
```
### See also
| | |
| --- | --- |
| [uniform\_int\_distribution](uniform_int_distribution "cpp/numeric/random/uniform int distribution")
(C++11) | produces integer values evenly distributed across a range (class template) |
| [srand](srand "cpp/numeric/random/srand") | seeds pseudo-random number generator (function) |
| [RAND\_MAX](rand_max "cpp/numeric/random/RAND MAX") | maximum possible value generated by `std::rand` (macro constant) |
| [randint](https://en.cppreference.com/w/cpp/experimental/randint "cpp/experimental/randint") | generates a random integer in the specified range (function template) |
| [C documentation](https://en.cppreference.com/w/c/numeric/random/rand "c/numeric/random/rand") for `rand` |
cpp std::discrete_distribution std::discrete\_distribution
===========================
| Defined in header `[<random>](../../header/random "cpp/header/random")` | | |
| --- | --- | --- |
|
```
template< class IntType = int >
class discrete_distribution;
```
| | (since C++11) |
`std::discrete_distribution` produces random integers on the interval `[0, n)`, where the probability of each individual integer `i` is defined as w
i/S, that is the *weight* of the `i`th integer divided by the sum of all `n` weights.
`std::discrete_distribution` satisfies all requirements of [RandomNumberDistribution](../../named_req/randomnumberdistribution "cpp/named req/RandomNumberDistribution").
### Template parameters
| | | |
| --- | --- | --- |
| IntType | - | The result type generated by the generator. The effect is undefined if this is not one of `short`, `int`, `long`, `long long`, `unsigned short`, `unsigned int`, `unsigned long`, or `unsigned long long`. |
### Member types
| Member type | Definition |
| --- | --- |
| `result_type` | `IntType` |
| `param_type`(C++11) | the type of the parameter set, see [RandomNumberDistribution](../../named_req/randomnumberdistribution "cpp/named req/RandomNumberDistribution"). |
### Member functions
| | |
| --- | --- |
| [(constructor)](discrete_distribution/discrete_distribution "cpp/numeric/random/discrete distribution/discrete distribution")
(C++11) | constructs new distribution (public member function) |
| [reset](discrete_distribution/reset "cpp/numeric/random/discrete distribution/reset")
(C++11) | resets the internal state of the distribution (public member function) |
| Generation |
| [operator()](discrete_distribution/operator() "cpp/numeric/random/discrete distribution/operator()")
(C++11) | generates the next random number in the distribution (public member function) |
| Characteristics |
| [probabilities](discrete_distribution/probabilities "cpp/numeric/random/discrete distribution/probabilities") | obtains the list of probabilities (public member function) |
| [param](discrete_distribution/param "cpp/numeric/random/discrete distribution/param")
(C++11) | gets or sets the distribution parameter object (public member function) |
| [min](discrete_distribution/min "cpp/numeric/random/discrete distribution/min")
(C++11) | returns the minimum potentially generated value (public member function) |
| [max](discrete_distribution/max "cpp/numeric/random/discrete distribution/max")
(C++11) | returns the maximum potentially generated value (public member function) |
### Non-member functions
| | |
| --- | --- |
| [operator==operator!=](discrete_distribution/operator_cmp "cpp/numeric/random/discrete distribution/operator cmp")
(C++11)(C++11)(removed in C++20) | compares two distribution objects (function) |
| [operator<<operator>>](discrete_distribution/operator_ltltgtgt "cpp/numeric/random/discrete distribution/operator ltltgtgt")
(C++11) | performs stream input and output on pseudo-random number distribution (function template) |
### Example
```
#include <iostream>
#include <iomanip>
#include <map>
#include <random>
int main()
{
std::random_device rd;
std::mt19937 gen(rd());
std::discrete_distribution<> d({40, 10, 10, 40});
std::map<int, int> map;
for(int n=0; n<10000; ++n) {
++map[d(gen)];
}
for(const auto& [num, count] : map) {
std::cout << num << " generated " << std::setw(4) << count << " times\n";
}
}
```
Possible output:
```
0 generated 4037 times
1 generated 962 times
2 generated 1030 times
3 generated 3971 times
```
cpp std::student_t_distribution std::student\_t\_distribution
=============================
| Defined in header `[<random>](../../header/random "cpp/header/random")` | | |
| --- | --- | --- |
|
```
template< class RealType = double >
class student_t_distribution;
```
| | (since C++11) |
Produces random floating-point values x, distributed according to probability density function: \(p(x|n) = \frac{1}{\sqrt{n\pi} } \cdot \frac{\Gamma(\frac{n+1}{2})}{\Gamma(\frac{n}{2})} \cdot (1+\frac{x^2}{n})^{-\frac{n+1}{2} } \)p(x|n) =
1/โnฯ ยท ฮ(n+12)n+12ฮ(n2)n/2 ยท โ
โ
โ1+x2/nโ
โ
โ -n+1/2
where n is known as the number of *degrees of freedom*. This distribution is used when estimating the *mean* of an unknown normally distributed value given n+1 independent measurements, each with additive errors of unknown standard deviation, as in physical measurements. Or, alternatively, when estimating the unknown mean of a normal distribution with unknown standard deviation, given n+1 samples.
`std::student_t_distribution` satisfies all requirements of [RandomNumberDistribution](../../named_req/randomnumberdistribution "cpp/named req/RandomNumberDistribution").
### Template parameters
| | | |
| --- | --- | --- |
| RealType | - | The result type generated by the generator. The effect is undefined if this is not one of `float`, `double`, or `long double`. |
### Member types
| Member type | Definition |
| --- | --- |
| `result_type` | `RealType` |
| `param_type`(C++11) | the type of the parameter set, see [RandomNumberDistribution](../../named_req/randomnumberdistribution "cpp/named req/RandomNumberDistribution"). |
### Member functions
| | |
| --- | --- |
| [(constructor)](student_t_distribution/student_t_distribution "cpp/numeric/random/student t distribution/student t distribution")
(C++11) | constructs new distribution (public member function) |
| [reset](student_t_distribution/reset "cpp/numeric/random/student t distribution/reset")
(C++11) | resets the internal state of the distribution (public member function) |
| Generation |
| [operator()](student_t_distribution/operator() "cpp/numeric/random/student t distribution/operator()")
(C++11) | generates the next random number in the distribution (public member function) |
| Characteristics |
| [n](student_t_distribution/n "cpp/numeric/random/student t distribution/n") | returns the *n* distribution parameter (degrees of freedom) (public member function) |
| [param](student_t_distribution/param "cpp/numeric/random/student t distribution/param")
(C++11) | gets or sets the distribution parameter object (public member function) |
| [min](student_t_distribution/min "cpp/numeric/random/student t distribution/min")
(C++11) | returns the minimum potentially generated value (public member function) |
| [max](student_t_distribution/max "cpp/numeric/random/student t distribution/max")
(C++11) | returns the maximum potentially generated value (public member function) |
### Non-member functions
| | |
| --- | --- |
| [operator==operator!=](student_t_distribution/operator_cmp "cpp/numeric/random/student t distribution/operator cmp")
(C++11)(C++11)(removed in C++20) | compares two distribution objects (function) |
| [operator<<operator>>](student_t_distribution/operator_ltltgtgt "cpp/numeric/random/student t distribution/operator ltltgtgt")
(C++11) | performs stream input and output on pseudo-random number distribution (function template) |
### Example
```
#include <map>
#include <random>
#include <iomanip>
#include <algorithm>
#include <iostream>
#include <vector>
#include <cmath>
template <int Height = 5, int BarWidth = 1, int Padding = 1, int Offset = 0, class Seq>
void draw_vbars(Seq&& s, const bool DrawMinMax = true) {
static_assert((Height > 0) && (BarWidth > 0) && (Padding >= 0) && (Offset >= 0));
auto cout_n = [](auto&& v, int n = 1) { while (n-- > 0) std::cout << v; };
const auto [min, max] = std::minmax_element(std::cbegin(s), std::cend(s));
std::vector<std::div_t> qr;
for (typedef decltype(*cbegin(s)) V; V e : s)
qr.push_back(std::div(std::lerp(V(0), Height*8, (e - *min)/(*max - *min)), 8));
for (auto h{Height}; h-- > 0; cout_n('\n')) {
cout_n(' ', Offset);
for (auto dv : qr) {
const auto q{dv.quot}, r{dv.rem};
unsigned char d[] { 0xe2, 0x96, 0x88, 0 }; // Full Block: 'โ'
q < h ? d[0] = ' ', d[1] = 0 : q == h ? d[2] -= (7 - r) : 0;
cout_n(d, BarWidth), cout_n(' ', Padding);
}
if (DrawMinMax && Height > 1)
Height - 1 == h ? std::cout << "โฌ " << *max:
h ? std::cout << "โ "
: std::cout << "โด " << *min;
}
}
int main() {
std::random_device rd{};
std::mt19937 gen{rd()};
std::student_t_distribution<> d{10.0f};
const int norm = 10'000;
const float cutoff = 0.000'3f;
std::map<int, int> hist{};
for(int n=0; n<norm; ++n) { ++hist[std::round(d(gen))]; }
std::vector<float> bars;
std::vector<int> indices;
for (const auto& [n, p] : hist) {
if (float x = p * (1.0f / norm); cutoff < x) {
bars.push_back(x);
indices.push_back(n);
}
}
draw_vbars<8,5>(bars);
for (int n : indices) { std::cout << " " << std::setw(2) << n << " "; }
std::cout << '\n';
}
```
Possible output:
```
โโโโโ โฌ 0.3753
โโโโโ โ
โโโโโ โโโโโ โ
โโโโโ โโโโโ โโโโโ โ
โโโโโ โโโโโ โโโโโ โ
โโโโโ โโโโโ โโโโโ โ
โโโโโ โโโโโ โโโโโ โโโโโ โโโโโ โ
โโโโโ โโโโโ โโโโโ โโโโโ โโโโโ โโโโโ โโโโโ โโโโโ โโโโโ โโโโโ โด 0.0049
-4 -3 -2 -1 0 1 2 3 4 5
```
### External links
[Weisstein, Eric W. "Student's t-Distribution."](http://mathworld.wolfram.com/Studentst-Distribution.html) From MathWorld--A Wolfram Web Resource.
cpp std::binomial_distribution std::binomial\_distribution
===========================
| Defined in header `[<random>](../../header/random "cpp/header/random")` | | |
| --- | --- | --- |
|
```
template< class IntType = int >
class binomial_distribution;
```
| | (since C++11) |
Produces random non-negative integer values i, distributed according to discrete probability function: \(P(i|t,p) = \binom{t}{i} \cdot p^i \cdot (1-p)^{t-i}\)P(i|t,p) =
โ
โ
โt
iโ
โ
โ ยท pi
ยท (1 โ p)tโi
The value obtained is the number of successes in a sequence of t yes/no experiments, each of which succeeds with probability p.
`std::binomial_distribution` satisfies [RandomNumberDistribution](../../named_req/randomnumberdistribution "cpp/named req/RandomNumberDistribution").
### Template parameters
| | | |
| --- | --- | --- |
| IntType | - | The result type generated by the generator. The effect is undefined if this is not one of `short`, `int`, `long`, `long long`, `unsigned short`, `unsigned int`, `unsigned long`, or `unsigned long long`. |
### Member types
| Member type | Definition |
| --- | --- |
| `result_type` | `IntType` |
| `param_type`(C++11) | the type of the parameter set, see [RandomNumberDistribution](../../named_req/randomnumberdistribution "cpp/named req/RandomNumberDistribution"). |
### Member functions
| | |
| --- | --- |
| [(constructor)](binomial_distribution/binomial_distribution "cpp/numeric/random/binomial distribution/binomial distribution")
(C++11) | constructs new distribution (public member function) |
| [reset](binomial_distribution/reset "cpp/numeric/random/binomial distribution/reset")
(C++11) | resets the internal state of the distribution (public member function) |
| Generation |
| [operator()](binomial_distribution/operator() "cpp/numeric/random/binomial distribution/operator()")
(C++11) | generates the next random number in the distribution (public member function) |
| Characteristics |
| [pt](binomial_distribution/params "cpp/numeric/random/binomial distribution/params") | returns the distribution parameters (public member function) |
| [param](binomial_distribution/param "cpp/numeric/random/binomial distribution/param")
(C++11) | gets or sets the distribution parameter object (public member function) |
| [min](binomial_distribution/min "cpp/numeric/random/binomial distribution/min")
(C++11) | returns the minimum potentially generated value (public member function) |
| [max](binomial_distribution/max "cpp/numeric/random/binomial distribution/max")
(C++11) | returns the maximum potentially generated value (public member function) |
### Non-member functions
| | |
| --- | --- |
| [operator==operator!=](binomial_distribution/operator_cmp "cpp/numeric/random/binomial distribution/operator cmp")
(C++11)(C++11)(removed in C++20) | compares two distribution objects (function) |
| [operator<<operator>>](binomial_distribution/operator_ltltgtgt "cpp/numeric/random/binomial distribution/operator ltltgtgt")
(C++11) | performs stream input and output on pseudo-random number distribution (function template) |
### Example
Plot of binomial distribution with probability of success of each trial exactly 0.5, illustrating the relationship with the pascal triangle (the probabilities that none, 1, 2, 3, or all four of the 4 trials will be successful in this case are 1:4:6:4:1).
```
#include <iostream>
#include <iomanip>
#include <string>
#include <map>
#include <random>
int main()
{
std::random_device rd;
std::mt19937 gen(rd());
// perform 4 trials, each succeeds 1 in 2 times
std::binomial_distribution<> d(4, 0.5);
std::map<int, int> hist;
for (int n = 0; n < 10000; ++n) {
++hist[d(gen)];
}
for (auto p : hist) {
std::cout << p.first << ' '
<< std::string(p.second/100, '*') << '\n';
}
}
```
Possible output:
```
0 ******
1 ************************
2 *************************************
3 *************************
4 ******
```
### External links
[Weisstein, Eric W. "Binomial Distribution."](http://mathworld.wolfram.com/BinomialDistribution.html) From MathWorld--A Wolfram Web Resource.
cpp operator<<,>>(std::fisher_f_distribution)
operator<<,>>(std::fisher\_f\_distribution)
===========================================
| | | |
| --- | --- | --- |
|
```
template< class CharT, class Traits >
friend std::basic_ostream<CharT,Traits>&
operator<<( std::basic_ostream<CharT,Traits>& ost,
const fisher_f_distribution& d );
```
| (1) | (since C++11) |
|
```
template< class CharT, class Traits >
friend std::basic_istream<CharT,Traits>&
operator>>( std::basic_istream<CharT,Traits>& ist,
fisher_f_distribution& d );
```
| (2) | (since C++11) |
Performs stream input and output operations on pseudo-random number distribution `d`.
1) Writes a textual representation of the distribution parameters and internal state to `ost` as textual representation. The formatting flags and fill character of `ost` are unchanged.
2) Restores the distribution parameters and internal state with data read from `ist`. The formatting flags of `ist` are unchanged. The data must have been written using a stream with the same locale, `CharT` and `Traits` template parameters, otherwise the behavior is undefined. If bad input is encountered, `ist.setstate(std::ios::failbit)` is called, which may throw `[std::ios\_base::failure](../../../io/ios_base/failure "cpp/io/ios base/failure")`. `d` is unchanged in that case. These function templates are not visible to ordinary [unqualified](../../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../../language/adl "cpp/language/adl") when `std::fisher_f_distribution<ResultType>` is an associated class of the arguments.
### Parameters
| | | |
| --- | --- | --- |
| ost | - | output stream to insert the data to |
| ist | - | input stream to extract the data from |
| d | - | pseudo-random number distribution |
### Return value
1) `ost`
2) `ist`
### Exceptions
1) May throw implementation-defined exceptions.
2) May throw `[std::ios\_base::failure](../../../io/ios_base/failure "cpp/io/ios base/failure")` on bad input. ### 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 3519](https://cplusplus.github.io/LWG/issue3519) | C++11 | the form of insertion and extraction operators were unspecified(could be hidden friends or out-of-class function templates) | specified to be hidden friends |
cpp std::fisher_f_distribution<RealType>::reset std::fisher\_f\_distribution<RealType>::reset
=============================================
| | | |
| --- | --- | --- |
|
```
void reset();
```
| | (since C++11) |
Resets the internal state of the distribution object. After a call to this function, the next call to `[operator()](operator() "cpp/numeric/random/fisher f distribution/operator()")` on the distribution object will not be dependent on previous calls to `[operator()](operator() "cpp/numeric/random/fisher f distribution/operator()")`.
### Parameters
(none).
### Return value
(none).
### Complexity
Constant.
| programming_docs |
cpp std::fisher_f_distribution<RealType>::operator() std::fisher\_f\_distribution<RealType>::operator()
==================================================
| | | |
| --- | --- | --- |
|
```
template< class Generator >
result_type operator()( Generator& g );
```
| (1) | (since C++11) |
|
```
template< class Generator >
result_type operator()( Generator& g, const param_type& params );
```
| (2) | (since C++11) |
Generates random numbers that are distributed according to the associated probability function. The entropy is acquired by calling `g.operator()`.
The first version uses the associated parameter set, the second version uses `params`. The associated parameter set is not modified.
### Parameters
| | | |
| --- | --- | --- |
| g | - | an uniform random bit generator object |
| params | - | distribution parameter set to use instead of the associated one |
| Type requirements |
| -`Generator` must meet the requirements of [UniformRandomBitGenerator](../../../named_req/uniformrandombitgenerator "cpp/named req/UniformRandomBitGenerator"). |
### Return value
The generated random number.
### Complexity
Amortized constant number of invocations of `g.operator()`.
cpp std::fisher_f_distribution<RealType>::m, n std::fisher\_f\_distribution<RealType>::m, n
============================================
| | | |
| --- | --- | --- |
|
```
RealType m() const;
```
| (1) | (since C++11) |
|
```
RealType n() const;
```
| (2) | (since C++11) |
Returns the parameters the distribution was constructed with.
1) Returns the m (the first degree of freedom) distribution parameter. The default value is `1.0`.
2) Returns the n (the second degree of freedom) distribution parameter. The default value is `1.0`. ### Parameters
(none).
### Return value
1) The m (the first degree of freedom) distribution parameter.
2) The n (the second degree of freedom) distribution parameter. ### Complexity
Constant.
### See also
| | |
| --- | --- |
| [param](param "cpp/numeric/random/fisher f distribution/param")
(C++11) | gets or sets the distribution parameter object (public member function) |
cpp std::fisher_f_distribution<RealType>::max std::fisher\_f\_distribution<RealType>::max
===========================================
| | | |
| --- | --- | --- |
|
```
result_type max() const;
```
| | (since C++11) |
Returns the maximum value potentially generated by the distribution.
### Parameters
(none).
### Return value
The maximum value potentially generated by the distribution.
### Complexity
Constant.
### See also
| | |
| --- | --- |
| [min](min "cpp/numeric/random/fisher f distribution/min")
(C++11) | returns the minimum potentially generated value (public member function) |
cpp std::fisher_f_distribution<RealType>::min std::fisher\_f\_distribution<RealType>::min
===========================================
| | | |
| --- | --- | --- |
|
```
result_type min() const;
```
| | (since C++11) |
Returns the minimum value potentially generated by the distribution.
### Parameters
(none).
### Return value
The minimum value potentially generated by the distribution.
### Complexity
Constant.
### See also
| | |
| --- | --- |
| [max](max "cpp/numeric/random/fisher f distribution/max")
(C++11) | returns the maximum potentially generated value (public member function) |
cpp std::fisher_f_distribution<RealType>::param std::fisher\_f\_distribution<RealType>::param
=============================================
| | | |
| --- | --- | --- |
|
```
param_type param() const;
```
| (1) | (since C++11) |
|
```
void param( const param_type& params );
```
| (2) | (since C++11) |
Manages the associated distribution parameter set.
1) Returns the associated parameter set.
2) Sets the associated parameter set to `params`.
### Parameters
| | | |
| --- | --- | --- |
| params | - | new contents of the associated parameter set |
### Return value
1) The associated parameter set.
2) (none).
### Complexity
Constant.
cpp std::fisher_f_distribution<RealType>::fisher_f_distribution std::fisher\_f\_distribution<RealType>::fisher\_f\_distribution
===============================================================
| | | |
| --- | --- | --- |
|
```
fisher_f_distribution() : fisher_f_distribution(1.0) {}
```
| (1) | (since C++11) |
|
```
explicit fisher_f_distribution( RealType m, RealType n = 1.0 );
```
| (2) | (since C++11) |
|
```
explicit fisher_f_distribution( const param_type& params );
```
| (3) | (since C++11) |
Constructs a new distribution object. (2) uses `m` and `n` as the distribution parameters. (3) uses `params` as the distribution parameters.
### Parameters
| | | |
| --- | --- | --- |
| m | - | the *m* distribution parameter (degrees of freedom) |
| n | - | the *n* distribution parameter (degrees of freedom) |
| params | - | the distribution parameter set |
### 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 operator==,!=(std::fisher_f_distribution)
operator==,!=(std::fisher\_f\_distribution)
===========================================
| | | |
| --- | --- | --- |
|
```
friend bool operator==( const fisher_f_distribution& lhs,
const fisher_f_distribution& rhs );
```
| (1) | (since C++11) |
|
```
friend bool operator!=( const fisher_f_distribution& lhs,
const fisher_f_distribution& rhs );
```
| (2) | (since C++11) (until C++20) |
Compares two distribution objects. Two distribution objects are equal when parameter values and internal state is the same.
1) Compares two distribution objects for equality.
2) Compares two distribution objects for inequality. These functions are not visible to ordinary [unqualified](../../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../../language/adl "cpp/language/adl") when `std::fisher_f_distribution<ResultType>` is an associated class of the arguments.
| | |
| --- | --- |
| The `!=` operator is [synthesized](../../../language/operators#Relational_operators "cpp/language/operators") from `operator==`. | (since C++20) |
### Parameters
| | | |
| --- | --- | --- |
| lhs, rhs | - | distribution objects to compare |
### Return value
1) `true` if the distribution objects are equal, `false` otherwise.
2) `true` if the distribution objects are not equal, `false` otherwise. ### Complexity
Constant.
### 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 3519](https://cplusplus.github.io/LWG/issue3519) | C++11 | the form of equality operators were unspecified(could be hidden friends or free function templates) | specified to be hidden friends |
cpp operator<<,>>(std::student_t_distribution)
operator<<,>>(std::student\_t\_distribution)
============================================
| | | |
| --- | --- | --- |
|
```
template< class CharT, class Traits >
friend std::basic_ostream<CharT,Traits>&
operator<<( std::basic_ostream<CharT,Traits>& ost,
const student_t_distribution& d );
```
| (1) | (since C++11) |
|
```
template< class CharT, class Traits >
friend std::basic_istream<CharT,Traits>&
operator>>( std::basic_istream<CharT,Traits>& ist,
student_t_distribution& d );
```
| (2) | (since C++11) |
Performs stream input and output operations on pseudo-random number distribution `d`.
1) Writes a textual representation of the distribution parameters and internal state to `ost` as textual representation. The formatting flags and fill character of `ost` are unchanged.
2) Restores the distribution parameters and internal state with data read from `ist`. The formatting flags of `ist` are unchanged. The data must have been written using a stream with the same locale, `CharT` and `Traits` template parameters, otherwise the behavior is undefined. If bad input is encountered, `ist.setstate(std::ios::failbit)` is called, which may throw `[std::ios\_base::failure](../../../io/ios_base/failure "cpp/io/ios base/failure")`. `d` is unchanged in that case. These function templates are not visible to ordinary [unqualified](../../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../../language/adl "cpp/language/adl") when `std::student_t_distribution<ResultType>` is an associated class of the arguments.
### Parameters
| | | |
| --- | --- | --- |
| ost | - | output stream to insert the data to |
| ist | - | input stream to extract the data from |
| d | - | pseudo-random number distribution |
### Return value
1) `ost`
2) `ist`
### Exceptions
1) May throw implementation-defined exceptions.
2) May throw `[std::ios\_base::failure](../../../io/ios_base/failure "cpp/io/ios base/failure")` on bad input. ### 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 3519](https://cplusplus.github.io/LWG/issue3519) | C++11 | the form of insertion and extraction operators were unspecified(could be hidden friends or out-of-class function templates) | specified to be hidden friends |
cpp std::student_t_distribution<RealType>::reset std::student\_t\_distribution<RealType>::reset
==============================================
| | | |
| --- | --- | --- |
|
```
void reset();
```
| | (since C++11) |
Resets the internal state of the distribution object. After a call to this function, the next call to `[operator()](operator() "cpp/numeric/random/student t distribution/operator()")` on the distribution object will not be dependent on previous calls to `[operator()](operator() "cpp/numeric/random/student t distribution/operator()")`.
### Parameters
(none).
### Return value
(none).
### Complexity
Constant.
cpp std::student_t_distribution<RealType>::n std::student\_t\_distribution<RealType>::n
==========================================
| | | |
| --- | --- | --- |
|
```
RealType n() const;
```
| | (since C++11) |
Returns the n distribution parameter (number of the degrees of freedom) the distribution was constructed with. The default value is `1.0`.
### Parameters
(none).
### Return value
Floating point value identifying the degrees of freedom of the distribution.
### See also
| | |
| --- | --- |
| [param](param "cpp/numeric/random/student t distribution/param")
(C++11) | gets or sets the distribution parameter object (public member function) |
cpp std::student_t_distribution<RealType>::operator() std::student\_t\_distribution<RealType>::operator()
===================================================
| | | |
| --- | --- | --- |
|
```
template< class Generator >
result_type operator()( Generator& g );
```
| (1) | (since C++11) |
|
```
template< class Generator >
result_type operator()( Generator& g, const param_type& params );
```
| (2) | (since C++11) |
Generates random numbers that are distributed according to the associated probability function. The entropy is acquired by calling `g.operator()`.
The first version uses the associated parameter set, the second version uses `params`. The associated parameter set is not modified.
### Parameters
| | | |
| --- | --- | --- |
| g | - | an uniform random bit generator object |
| params | - | distribution parameter set to use instead of the associated one |
| Type requirements |
| -`Generator` must meet the requirements of [UniformRandomBitGenerator](../../../named_req/uniformrandombitgenerator "cpp/named req/UniformRandomBitGenerator"). |
### Return value
The generated random number.
### Complexity
Amortized constant number of invocations of `g.operator()`.
cpp std::student_t_distribution<RealType>::max std::student\_t\_distribution<RealType>::max
============================================
| | | |
| --- | --- | --- |
|
```
result_type max() const;
```
| | (since C++11) |
Returns the maximum value potentially generated by the distribution.
### Parameters
(none).
### Return value
The maximum value potentially generated by the distribution.
### Complexity
Constant.
### See also
| | |
| --- | --- |
| [min](min "cpp/numeric/random/student t distribution/min")
(C++11) | returns the minimum potentially generated value (public member function) |
cpp std::student_t_distribution<RealType>::min std::student\_t\_distribution<RealType>::min
============================================
| | | |
| --- | --- | --- |
|
```
result_type min() const;
```
| | (since C++11) |
Returns the minimum value potentially generated by the distribution.
### Parameters
(none).
### Return value
The minimum value potentially generated by the distribution.
### Complexity
Constant.
### See also
| | |
| --- | --- |
| [max](max "cpp/numeric/random/student t distribution/max")
(C++11) | returns the maximum potentially generated value (public member function) |
cpp std::student_t_distribution<RealType>::param std::student\_t\_distribution<RealType>::param
==============================================
| | | |
| --- | --- | --- |
|
```
param_type param() const;
```
| (1) | (since C++11) |
|
```
void param( const param_type& params );
```
| (2) | (since C++11) |
Manages the associated distribution parameter set.
1) Returns the associated parameter set.
2) Sets the associated parameter set to `params`.
### Parameters
| | | |
| --- | --- | --- |
| params | - | new contents of the associated parameter set |
### Return value
1) The associated parameter set.
2) (none).
### Complexity
Constant.
cpp operator==,!=(std::student_t_distribution)
operator==,!=(std::student\_t\_distribution)
============================================
| | | |
| --- | --- | --- |
|
```
friend bool operator==( const student_t_distribution& lhs,
const student_t_distribution& rhs );
```
| (1) | (since C++11) |
|
```
friend bool operator!=( const student_t_distribution& lhs,
const student_t_distribution& rhs );
```
| (2) | (since C++11) (until C++20) |
Compares two distribution objects. Two distribution objects are equal when parameter values and internal state is the same.
1) Compares two distribution objects for equality.
2) Compares two distribution objects for inequality. These functions are not visible to ordinary [unqualified](../../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../../language/adl "cpp/language/adl") when `std::student_t_distribution<ResultType>` is an associated class of the arguments.
| | |
| --- | --- |
| The `!=` operator is [synthesized](../../../language/operators#Relational_operators "cpp/language/operators") from `operator==`. | (since C++20) |
### Parameters
| | | |
| --- | --- | --- |
| lhs, rhs | - | distribution objects to compare |
### Return value
1) `true` if the distribution objects are equal, `false` otherwise.
2) `true` if the distribution objects are not equal, `false` otherwise. ### Complexity
Constant.
### 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 3519](https://cplusplus.github.io/LWG/issue3519) | C++11 | the form of equality operators were unspecified(could be hidden friends or free function templates) | specified to be hidden friends |
cpp std::student_t_distribution<RealType>::student_t_distribution std::student\_t\_distribution<RealType>::student\_t\_distribution
=================================================================
| | | |
| --- | --- | --- |
|
```
student_t_distribution() : student_t_distribution(1) {}
```
| (1) | (since C++11) |
|
```
explicit student_t_distribution( RealType n );
```
| (2) | (since C++11) |
|
```
explicit student_t_distribution( const param_type& params );
```
| (3) | (since C++11) |
Constructs a new distribution object. (2) uses `n` as the distribution parameter. (3) uses `params` as the distribution parameter.
### Parameters
| | | |
| --- | --- | --- |
| n | - | the *n* distribution parameter (degrees of freedom) |
| params | - | the distribution parameter set |
### 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 operator<<,>>(std::lognormal_distribution)
operator<<,>>(std::lognormal\_distribution)
===========================================
| | | |
| --- | --- | --- |
|
```
template< class CharT, class Traits >
friend std::basic_ostream<CharT,Traits>&
operator<<( std::basic_ostream<CharT,Traits>& ost,
const lognormal_distribution& d );
```
| (1) | (since C++11) |
|
```
template< class CharT, class Traits >
friend std::basic_istream<CharT,Traits>&
operator>>( std::basic_istream<CharT,Traits>& ist,
lognormal_distribution& d );
```
| (2) | (since C++11) |
Performs stream input and output operations on pseudo-random number distribution `d`.
1) Writes a textual representation of the distribution parameters and internal state to `ost` as textual representation. The formatting flags and fill character of `ost` are unchanged.
2) Restores the distribution parameters and internal state with data read from `ist`. The formatting flags of `ist` are unchanged. The data must have been written using a stream with the same locale, `CharT` and `Traits` template parameters, otherwise the behavior is undefined. If bad input is encountered, `ist.setstate(std::ios::failbit)` is called, which may throw `[std::ios\_base::failure](../../../io/ios_base/failure "cpp/io/ios base/failure")`. `d` is unchanged in that case. These function templates are not visible to ordinary [unqualified](../../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../../language/adl "cpp/language/adl") when `std::lognormal_distribution<ResultType>` is an associated class of the arguments.
### Parameters
| | | |
| --- | --- | --- |
| ost | - | output stream to insert the data to |
| ist | - | input stream to extract the data from |
| d | - | pseudo-random number distribution |
### Return value
1) `ost`
2) `ist`
### Exceptions
1) May throw implementation-defined exceptions.
2) May throw `[std::ios\_base::failure](../../../io/ios_base/failure "cpp/io/ios base/failure")` on bad input. ### 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 3519](https://cplusplus.github.io/LWG/issue3519) | C++11 | the form of insertion and extraction operators were unspecified(could be hidden friends or out-of-class function templates) | specified to be hidden friends |
| programming_docs |
cpp std::lognormal_distribution<RealType>::reset std::lognormal\_distribution<RealType>::reset
=============================================
| | | |
| --- | --- | --- |
|
```
void reset();
```
| | (since C++11) |
Resets the internal state of the distribution object. After a call to this function, the next call to `[operator()](operator() "cpp/numeric/random/lognormal distribution/operator()")` on the distribution object will not be dependent on previous calls to `[operator()](operator() "cpp/numeric/random/lognormal distribution/operator()")`.
### Parameters
(none).
### Return value
(none).
### Complexity
Constant.
cpp std::lognormal_distribution<RealType>::lognormal_distribution std::lognormal\_distribution<RealType>::lognormal\_distribution
===============================================================
| | | |
| --- | --- | --- |
|
```
lognormal_distribution() : lognormal_distribution(0.0) {}
```
| (1) | (since C++11) |
|
```
explicit lognormal_distribution( RealType m, RealType s = 1.0 );
```
| (2) | (since C++11) |
|
```
explicit lognormal_distribution( const param_type& params );
```
| (3) | (since C++11) |
Constructs a new distribution object. (2) uses `m` and `s` as the distribution parameters. (3) uses `params` as the distribution parameters.
### Parameters
| | | |
| --- | --- | --- |
| m | - | the *m* distribution parameter (log-scale) |
| s | - | the *s* distribution parameter (shape) |
| params | - | the distribution parameter set |
### 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::lognormal_distribution<RealType>::operator() std::lognormal\_distribution<RealType>::operator()
==================================================
| | | |
| --- | --- | --- |
|
```
template< class Generator >
result_type operator()( Generator& g );
```
| (1) | (since C++11) |
|
```
template< class Generator >
result_type operator()( Generator& g, const param_type& params );
```
| (2) | (since C++11) |
Generates random numbers that are distributed according to the associated probability function. The entropy is acquired by calling `g.operator()`.
The first version uses the associated parameter set, the second version uses `params`. The associated parameter set is not modified.
### Parameters
| | | |
| --- | --- | --- |
| g | - | an uniform random bit generator object |
| params | - | distribution parameter set to use instead of the associated one |
| Type requirements |
| -`Generator` must meet the requirements of [UniformRandomBitGenerator](../../../named_req/uniformrandombitgenerator "cpp/named req/UniformRandomBitGenerator"). |
### Return value
The generated random number.
### Complexity
Amortized constant number of invocations of `g.operator()`.
cpp std::lognormal_distribution<RealType>::m, s std::lognormal\_distribution<RealType>::m, s
============================================
| | | |
| --- | --- | --- |
|
```
RealType m() const;
```
| (1) | (since C++11) |
|
```
RealType s() const;
```
| (2) | (since C++11) |
Returns the parameters the distribution was constructed with.
1) Returns the log-mean m distribution parameter. It defines the location of the peak. The default value is `0.0`.
2) Returns the log-deviation s distribution parameter. The default value is `1.0`. ### Parameters
(none).
### Return value
1) The log-mean m distribution parameter.
2) The log-deviation s distribution parameter. ### See also
| | |
| --- | --- |
| [param](param "cpp/numeric/random/lognormal distribution/param")
(C++11) | gets or sets the distribution parameter object (public member function) |
cpp std::lognormal_distribution<RealType>::max std::lognormal\_distribution<RealType>::max
===========================================
| | | |
| --- | --- | --- |
|
```
result_type max() const;
```
| | (since C++11) |
Returns the maximum value potentially generated by the distribution.
### Parameters
(none).
### Return value
The maximum value potentially generated by the distribution.
### Complexity
Constant.
### See also
| | |
| --- | --- |
| [min](min "cpp/numeric/random/lognormal distribution/min")
(C++11) | returns the minimum potentially generated value (public member function) |
cpp std::lognormal_distribution<RealType>::min std::lognormal\_distribution<RealType>::min
===========================================
| | | |
| --- | --- | --- |
|
```
result_type min() const;
```
| | (since C++11) |
Returns the minimum value potentially generated by the distribution.
### Parameters
(none).
### Return value
The minimum value potentially generated by the distribution.
### Complexity
Constant.
### See also
| | |
| --- | --- |
| [max](max "cpp/numeric/random/lognormal distribution/max")
(C++11) | returns the maximum potentially generated value (public member function) |
cpp std::lognormal_distribution<RealType>::param std::lognormal\_distribution<RealType>::param
=============================================
| | | |
| --- | --- | --- |
|
```
param_type param() const;
```
| (1) | (since C++11) |
|
```
void param( const param_type& params );
```
| (2) | (since C++11) |
Manages the associated distribution parameter set.
1) Returns the associated parameter set.
2) Sets the associated parameter set to `params`.
### Parameters
| | | |
| --- | --- | --- |
| params | - | new contents of the associated parameter set |
### Return value
1) The associated parameter set.
2) (none).
### Complexity
Constant.
cpp operator==,!=(std::lognormal_distribution)
operator==,!=(std::lognormal\_distribution)
===========================================
| | | |
| --- | --- | --- |
|
```
friend bool operator==( const lognormal_distribution& lhs,
const lognormal_distribution& rhs );
```
| (1) | (since C++11) |
|
```
friend bool operator!=( const lognormal_distribution& lhs,
const lognormal_distribution& rhs );
```
| (2) | (since C++11) (until C++20) |
Compares two distribution objects. Two distribution objects are equal when parameter values and internal state is the same.
1) Compares two distribution objects for equality.
2) Compares two distribution objects for inequality. These functions are not visible to ordinary [unqualified](../../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../../language/adl "cpp/language/adl") when `std::lognormal_distribution<ResultType>` is an associated class of the arguments.
| | |
| --- | --- |
| The `!=` operator is [synthesized](../../../language/operators#Relational_operators "cpp/language/operators") from `operator==`. | (since C++20) |
### Parameters
| | | |
| --- | --- | --- |
| lhs, rhs | - | distribution objects to compare |
### Return value
1) `true` if the distribution objects are equal, `false` otherwise.
2) `true` if the distribution objects are not equal, `false` otherwise. ### Complexity
Constant.
### 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 3519](https://cplusplus.github.io/LWG/issue3519) | C++11 | the form of equality operators were unspecified(could be hidden friends or free function templates) | specified to be hidden friends |
cpp operator<<,>>(std::negative_binomial_distribution)
operator<<,>>(std::negative\_binomial\_distribution)
====================================================
| | | |
| --- | --- | --- |
|
```
template< class CharT, class Traits >
friend std::basic_ostream<CharT,Traits>&
operator<<( std::basic_ostream<CharT,Traits>& ost,
const negative_binomial_distribution& d );
```
| (1) | (since C++11) |
|
```
template< class CharT, class Traits >
friend std::basic_istream<CharT,Traits>&
operator>>( std::basic_istream<CharT,Traits>& ist,
negative_binomial_distribution& d );
```
| (2) | (since C++11) |
Performs stream input and output operations on pseudo-random number distribution `d`.
1) Writes a textual representation of the distribution parameters and internal state to `ost` as textual representation. The formatting flags and fill character of `ost` are unchanged.
2) Restores the distribution parameters and internal state with data read from `ist`. The formatting flags of `ist` are unchanged. The data must have been written using a stream with the same locale, `CharT` and `Traits` template parameters, otherwise the behavior is undefined. If bad input is encountered, `ist.setstate(std::ios::failbit)` is called, which may throw `[std::ios\_base::failure](../../../io/ios_base/failure "cpp/io/ios base/failure")`. `d` is unchanged in that case. These function templates are not visible to ordinary [unqualified](../../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../../language/adl "cpp/language/adl") when `std::negative_binomial_distribution<ResultType>` is an associated class of the arguments.
### Parameters
| | | |
| --- | --- | --- |
| ost | - | output stream to insert the data to |
| ist | - | input stream to extract the data from |
| d | - | pseudo-random number distribution |
### Return value
1) `ost`
2) `ist`
### Exceptions
1) May throw implementation-defined exceptions.
2) May throw `[std::ios\_base::failure](../../../io/ios_base/failure "cpp/io/ios base/failure")` on bad input. ### 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 3519](https://cplusplus.github.io/LWG/issue3519) | C++11 | the form of insertion and extraction operators were unspecified(could be hidden friends or out-of-class function templates) | specified to be hidden friends |
cpp std::negative_binomial_distribution<IntType>::reset std::negative\_binomial\_distribution<IntType>::reset
=====================================================
| | | |
| --- | --- | --- |
|
```
void reset();
```
| | (since C++11) |
Resets the internal state of the distribution object. After a call to this function, the next call to `operator()` on the distribution object will not be dependent on previous calls to `operator()`.
### Parameters
(none).
### Return value
(none).
### Complexity
Constant.
cpp std::negative_binomial_distribution<IntType>::operator() std::negative\_binomial\_distribution<IntType>::operator()
==========================================================
| | | |
| --- | --- | --- |
|
```
template< class Generator >
result_type operator()( Generator& g );
```
| (1) | (since C++11) |
|
```
template< class Generator >
result_type operator()( Generator& g, const param_type& params );
```
| (2) | (since C++11) |
Generates random numbers that are distributed according to the associated probability function. The entropy is acquired by calling `g.operator()`.
The first version uses the associated parameter set, the second version uses `params`. The associated parameter set is not modified.
### Parameters
| | | |
| --- | --- | --- |
| g | - | an uniform random bit generator object |
| params | - | distribution parameter set to use instead of the associated one |
| Type requirements |
| -`Generator` must meet the requirements of [UniformRandomBitGenerator](../../../named_req/uniformrandombitgenerator "cpp/named req/UniformRandomBitGenerator"). |
### Return value
The generated random number.
### Complexity
Amortized constant number of invocations of `g.operator()`.
cpp std::negative_binomial_distribution<IntType>::p, k std::negative\_binomial\_distribution<IntType>::p, k
====================================================
| | | |
| --- | --- | --- |
|
```
double p() const;
```
| (1) | (since C++11) |
|
```
IntType k() const;
```
| (2) | (since C++11) |
Returns the parameters the distribution was constructed with.
1) Returns the p distribution parameter. It defines the probability of a trial generating `true`. The default value is `0.5`.
2) Returns the k distribution parameter. It defines the number of desired outcomes. The default value is `1`. ### Parameters
(none).
### Return value
1) The p distribution parameter.
2) The k distribution parameter. ### See also
| | |
| --- | --- |
| [param](param "cpp/numeric/random/negative binomial distribution/param")
(C++11) | gets or sets the distribution parameter object (public member function) |
cpp std::negative_binomial_distribution<IntType>::max std::negative\_binomial\_distribution<IntType>::max
===================================================
| | | |
| --- | --- | --- |
|
```
result_type max() const;
```
| | (since C++11) |
Returns the maximum value potentially generated by the distribution.
### Parameters
(none).
### Return value
The maximum value potentially generated by the distribution.
### Complexity
Constant.
### See also
| | |
| --- | --- |
| [min](min "cpp/numeric/random/negative binomial distribution/min")
(C++11) | returns the minimum potentially generated value (public member function) |
cpp std::negative_binomial_distribution<IntType>::min std::negative\_binomial\_distribution<IntType>::min
===================================================
| | | |
| --- | --- | --- |
|
```
result_type min() const;
```
| | (since C++11) |
Returns the minimum value potentially generated by the distribution.
### Parameters
(none).
### Return value
The minimum value potentially generated by the distribution.
### Complexity
Constant.
### See also
| | |
| --- | --- |
| [max](max "cpp/numeric/random/negative binomial distribution/max")
(C++11) | returns the maximum potentially generated value (public member function) |
cpp std::negative_binomial_distribution<IntType>::negative_binomial_distribution std::negative\_binomial\_distribution<IntType>::negative\_binomial\_distribution
================================================================================
| | | |
| --- | --- | --- |
|
```
negative_binomial_distribution() : negative_binomial_distribution(1) {}
```
| (1) | (since C++11) |
|
```
explicit negative_binomial_distribution( IntType k, double p = 0.5 );
```
| (2) | (since C++11) |
|
```
explicit negative_binomial_distribution( const param_type& params );
```
| (3) | (since C++11) |
Constructs a new distribution object. (2) uses `k` and `p` as the distribution parameters. (3) uses `params` as the distribution parameters.
### Parameters
| | | |
| --- | --- | --- |
| k | - | the *k* distribution parameter (number of trial successes) |
| p | - | the *p* distribution parameter (probability of a trial generating `true`) |
| params | - | the distribution parameter set |
### Notes
Requires that 0 < p โค 1 and 0 < k.
If `p == 1`, subsequent calls to the [`operator()`](operator() "cpp/numeric/random/negative binomial distribution/operator()") overload that does not accept a `param_type` object will cause undefined behavior.
The default-constructed `std::negative_binomial_distribution` is equivalent to the default-constructed `[std::geometric\_distribution](../geometric_distribution "cpp/numeric/random/geometric distribution")`.
### 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::negative_binomial_distribution<IntType>::param std::negative\_binomial\_distribution<IntType>::param
=====================================================
| | | |
| --- | --- | --- |
|
```
param_type param() const;
```
| (1) | (since C++11) |
|
```
void param( const param_type& params );
```
| (2) | (since C++11) |
Manages the associated distribution parameter set.
1) Returns the associated parameter set.
2) Sets the associated parameter set to `params`.
### Parameters
| | | |
| --- | --- | --- |
| params | - | new contents of the associated parameter set |
### Return value
1) The associated parameter set.
2) (none).
### Complexity
Constant.
cpp operator==,!=(std::negative_binomial_distribution)
operator==,!=(std::negative\_binomial\_distribution)
====================================================
| | | |
| --- | --- | --- |
|
```
friend bool operator==( const negative_binomial_distribution& lhs,
const negative_binomial_distribution& rhs );
```
| (1) | (since C++11) |
|
```
friend bool operator!=( const negative_binomial_distribution& lhs,
const negative_binomial_distribution& rhs );
```
| (2) | (since C++11) (until C++20) |
Compares two distribution objects. Two distribution objects are equal when parameter values and internal state is the same.
1) Compares two distribution objects for equality.
2) Compares two distribution objects for inequality. These functions are not visible to ordinary [unqualified](../../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../../language/adl "cpp/language/adl") when `std::negative_binomial_distribution<ResultType>` is an associated class of the arguments.
| | |
| --- | --- |
| The `!=` operator is [synthesized](../../../language/operators#Relational_operators "cpp/language/operators") from `operator==`. | (since C++20) |
### Parameters
| | | |
| --- | --- | --- |
| lhs, rhs | - | distribution objects to compare |
### Return value
1) `true` if the distribution objects are equal, `false` otherwise.
2) `true` if the distribution objects are not equal, `false` otherwise. ### Complexity
Constant.
### 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 3519](https://cplusplus.github.io/LWG/issue3519) | C++11 | the form of equality operators were unspecified(could be hidden friends or free function templates) | specified to be hidden friends |
cpp operator<<,>>(std::normal_distribution)
operator<<,>>(std::normal\_distribution)
========================================
| | | |
| --- | --- | --- |
|
```
template< class CharT, class Traits >
friend std::basic_ostream<CharT,Traits>&
operator<<( std::basic_ostream<CharT,Traits>& ost,
const normal_distribution& d );
```
| (1) | (since C++11) |
|
```
template< class CharT, class Traits >
friend std::basic_istream<CharT,Traits>&
operator>>( std::basic_istream<CharT,Traits>& ist,
normal_distribution& d );
```
| (2) | (since C++11) |
Performs stream input and output operations on pseudo-random number distribution `d`.
1) Writes a textual representation of the distribution parameters and internal state to `ost` as textual representation. The formatting flags and fill character of `ost` are unchanged.
2) Restores the distribution parameters and internal state with data read from `ist`. The formatting flags of `ist` are unchanged. The data must have been written using a stream with the same locale, `CharT` and `Traits` template parameters, otherwise the behavior is undefined. If bad input is encountered, `ist.setstate(std::ios::failbit)` is called, which may throw `[std::ios\_base::failure](../../../io/ios_base/failure "cpp/io/ios base/failure")`. `d` is unchanged in that case. These function templates are not visible to ordinary [unqualified](../../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../../language/adl "cpp/language/adl") when `std::normal_distribution<ResultType>` is an associated class of the arguments.
### Parameters
| | | |
| --- | --- | --- |
| ost | - | output stream to insert the data to |
| ist | - | input stream to extract the data from |
| d | - | pseudo-random number distribution |
### Return value
1) `ost`
2) `ist`
### Exceptions
1) May throw implementation-defined exceptions.
2) May throw `[std::ios\_base::failure](../../../io/ios_base/failure "cpp/io/ios base/failure")` on bad input. ### 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 3519](https://cplusplus.github.io/LWG/issue3519) | C++11 | the form of insertion and extraction operators were unspecified(could be hidden friends or out-of-class function templates) | specified to be hidden friends |
| programming_docs |
cpp std::normal_distribution<RealType>::reset std::normal\_distribution<RealType>::reset
==========================================
| | | |
| --- | --- | --- |
|
```
void reset();
```
| | (since C++11) |
Resets the internal state of the distribution object. After a call to this function, the next call to `[operator()](operator() "cpp/numeric/random/normal distribution/operator()")` on the distribution object will not be dependent on previous calls to `[operator()](operator() "cpp/numeric/random/normal distribution/operator()")`.
### Parameters
(none).
### Return value
(none).
### Complexity
Constant.
cpp std::normal_distribution<RealType>::operator() std::normal\_distribution<RealType>::operator()
===============================================
| | | |
| --- | --- | --- |
|
```
template< class Generator >
result_type operator()( Generator& g );
```
| (1) | (since C++11) |
|
```
template< class Generator >
result_type operator()( Generator& g, const param_type& params );
```
| (2) | (since C++11) |
Generates random numbers that are distributed according to the associated probability function. The entropy is acquired by calling `g.operator()`.
The first version uses the associated parameter set, the second version uses `params`. The associated parameter set is not modified.
### Parameters
| | | |
| --- | --- | --- |
| g | - | an uniform random bit generator object |
| params | - | distribution parameter set to use instead of the associated one |
| Type requirements |
| -`Generator` must meet the requirements of [UniformRandomBitGenerator](../../../named_req/uniformrandombitgenerator "cpp/named req/UniformRandomBitGenerator"). |
### Return value
The generated random number.
### Complexity
Amortized constant number of invocations of `g.operator()`.
cpp std::normal_distribution<RealType>::mean, stddev std::normal\_distribution<RealType>::mean, stddev
=================================================
| | | |
| --- | --- | --- |
|
```
RealType mean() const;
```
| (1) | (since C++11) |
|
```
RealType stddev() const;
```
| (2) | (since C++11) |
Returns the parameters the distribution was constructed with.
1) Returns the mean ฮผ distribution parameter. The mean specifies the location of the peak. The default value is `0.0`.
2) Returns the deviation ฯ distribution parameter. The default value is `1.0`. ### Parameters
(none).
### Return value
1) The mean ฮผ distribution parameter.
2) The deviation ฯ distribution parameter. ### See also
| | |
| --- | --- |
| [param](param "cpp/numeric/random/normal distribution/param")
(C++11) | gets or sets the distribution parameter object (public member function) |
cpp std::normal_distribution<RealType>::max std::normal\_distribution<RealType>::max
========================================
| | | |
| --- | --- | --- |
|
```
result_type max() const;
```
| | (since C++11) |
Returns the maximum value potentially generated by the distribution.
### Parameters
(none).
### Return value
The maximum value potentially generated by the distribution.
### Complexity
Constant.
### See also
| | |
| --- | --- |
| [min](min "cpp/numeric/random/normal distribution/min")
(C++11) | returns the minimum potentially generated value (public member function) |
cpp std::normal_distribution<RealType>::min std::normal\_distribution<RealType>::min
========================================
| | | |
| --- | --- | --- |
|
```
result_type min() const;
```
| | (since C++11) |
Returns the minimum value potentially generated by the distribution.
### Parameters
(none).
### Return value
The minimum value potentially generated by the distribution.
### Complexity
Constant.
### See also
| | |
| --- | --- |
| [max](max "cpp/numeric/random/normal distribution/max")
(C++11) | returns the maximum potentially generated value (public member function) |
cpp std::normal_distribution<RealType>::normal_distribution std::normal\_distribution<RealType>::normal\_distribution
=========================================================
| | | |
| --- | --- | --- |
|
```
normal_distribution() : normal_distribution(0.0) {}
```
| (1) | (since C++11) |
|
```
explicit normal_distribution( RealType mean, RealType stddev = 1.0 );
```
| (2) | (since C++11) |
|
```
explicit normal_distribution( const param_type& params );
```
| (3) | (since C++11) |
Constructs a new distribution object. (2) uses `mean` and `stddev` as the distribution parameters. (3) uses `params` as the distribution parameters.
The behavior is undefined if stddev is not greater than zero.
### Parameters
| | | |
| --- | --- | --- |
| mean | - | the *ฮผ* distribution parameter (mean) |
| stddev | - | the *ฯ* distribution parameter (standard deviation) |
| params | - | the distribution parameter set |
### 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::normal_distribution<RealType>::param std::normal\_distribution<RealType>::param
==========================================
| | | |
| --- | --- | --- |
|
```
param_type param() const;
```
| (1) | (since C++11) |
|
```
void param( const param_type& params );
```
| (2) | (since C++11) |
Manages the associated distribution parameter set.
1) Returns the associated parameter set.
2) Sets the associated parameter set to `params`.
### Parameters
| | | |
| --- | --- | --- |
| params | - | new contents of the associated parameter set |
### Return value
1) The associated parameter set.
2) (none).
### Complexity
Constant.
cpp operator==,!=(std::normal_distribution)
operator==,!=(std::normal\_distribution)
========================================
| | | |
| --- | --- | --- |
|
```
friend bool operator==( const normal_distribution& lhs,
const normal_distribution& rhs );
```
| (1) | (since C++11) |
|
```
friend bool operator!=( const normal_distribution& lhs,
const normal_distribution& rhs );
```
| (2) | (since C++11) (until C++20) |
Compares two distribution objects. Two distribution objects are equal when parameter values and internal state is the same.
1) Compares two distribution objects for equality.
2) Compares two distribution objects for inequality. These functions are not visible to ordinary [unqualified](../../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../../language/adl "cpp/language/adl") when `std::normal_distribution<ResultType>` is an associated class of the arguments.
| | |
| --- | --- |
| The `!=` operator is [synthesized](../../../language/operators#Relational_operators "cpp/language/operators") from `operator==`. | (since C++20) |
### Parameters
| | | |
| --- | --- | --- |
| lhs, rhs | - | distribution objects to compare |
### Return value
1) `true` if the distribution objects are equal, `false` otherwise.
2) `true` if the distribution objects are not equal, `false` otherwise. ### Complexity
Constant.
### 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 3519](https://cplusplus.github.io/LWG/issue3519) | C++11 | the form of equality operators were unspecified(could be hidden friends or free function templates) | specified to be hidden friends |
cpp operator<<,>>(std::gamma_distribution)
operator<<,>>(std::gamma\_distribution)
=======================================
| | | |
| --- | --- | --- |
|
```
template< class CharT, class Traits >
friend std::basic_ostream<CharT,Traits>&
operator<<( std::basic_ostream<CharT,Traits>& ost,
const gamma_distribution& d );
```
| (1) | (since C++11) |
|
```
template< class CharT, class Traits >
friend std::basic_istream<CharT,Traits>&
operator>>( std::basic_istream<CharT,Traits>& ist,
gamma_distribution& d );
```
| (2) | (since C++11) |
Performs stream input and output operations on pseudo-random number distribution `d`.
1) Writes a textual representation of the distribution parameters and internal state to `ost` as textual representation. The formatting flags and fill character of `ost` are unchanged.
2) Restores the distribution parameters and internal state with data read from `ist`. The formatting flags of `ist` are unchanged. The data must have been written using a stream with the same locale, `CharT` and `Traits` template parameters, otherwise the behavior is undefined. If bad input is encountered, `ist.setstate(std::ios::failbit)` is called, which may throw `[std::ios\_base::failure](../../../io/ios_base/failure "cpp/io/ios base/failure")`. `d` is unchanged in that case. These function templates are not visible to ordinary [unqualified](../../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../../language/adl "cpp/language/adl") when `std::gamma_distribution<ResultType>` is an associated class of the arguments.
### Parameters
| | | |
| --- | --- | --- |
| ost | - | output stream to insert the data to |
| ist | - | input stream to extract the data from |
| d | - | pseudo-random number distribution |
### Return value
1) `ost`
2) `ist`
### Exceptions
1) May throw implementation-defined exceptions.
2) May throw `[std::ios\_base::failure](../../../io/ios_base/failure "cpp/io/ios base/failure")` on bad input. ### 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 3519](https://cplusplus.github.io/LWG/issue3519) | C++11 | the form of insertion and extraction operators were unspecified(could be hidden friends or out-of-class function templates) | specified to be hidden friends |
cpp std::gamma_distribution<RealType>::reset std::gamma\_distribution<RealType>::reset
=========================================
| | | |
| --- | --- | --- |
|
```
void reset();
```
| | (since C++11) |
Resets the internal state of the distribution object. After a call to this function, the next call to `[operator()](operator() "cpp/numeric/random/gamma distribution/operator()")` on the distribution object will not be dependent on previous calls to `[operator()](operator() "cpp/numeric/random/gamma distribution/operator()")`.
### Parameters
(none).
### Return value
(none).
### Complexity
Constant.
cpp std::gamma_distribution<RealType>::operator() std::gamma\_distribution<RealType>::operator()
==============================================
| | | |
| --- | --- | --- |
|
```
template< class Generator >
result_type operator()( Generator& g );
```
| (1) | (since C++11) |
|
```
template< class Generator >
result_type operator()( Generator& g, const param_type& params );
```
| (2) | (since C++11) |
Generates random numbers that are distributed according to the associated probability function. The entropy is acquired by calling `g.operator()`.
The first version uses the associated parameter set, the second version uses `params`. The associated parameter set is not modified.
### Parameters
| | | |
| --- | --- | --- |
| g | - | an uniform random bit generator object |
| params | - | distribution parameter set to use instead of the associated one |
| Type requirements |
| -`Generator` must meet the requirements of [UniformRandomBitGenerator](../../../named_req/uniformrandombitgenerator "cpp/named req/UniformRandomBitGenerator"). |
### Return value
The generated random number.
### Complexity
Amortized constant number of invocations of `g.operator()`.
cpp std::gamma_distribution<RealType>::alpha, beta std::gamma\_distribution<RealType>::alpha, beta
===============================================
| | | |
| --- | --- | --- |
|
```
RealType alpha() const;
```
| (1) | (since C++11) |
|
```
RealType beta() const;
```
| (2) | (since C++11) |
Returns the distribution parameters the distribution has been constructed with.
1) Returns the ฮฑ distribution parameter. It is also known as the shape parameter. The default value is `1.0`.
2) Returns the ฮฒ distribution parameter. It is also known as the scale parameter. The default value is `1.0`. ### Parameters
(none).
### Return value
1) Floating point value identifying the ฮฑ parameter
2) Floating point value identifying the ฮฒ parameter ### See also
| | |
| --- | --- |
| [param](param "cpp/numeric/random/gamma distribution/param")
(C++11) | gets or sets the distribution parameter object (public member function) |
cpp std::gamma_distribution<RealType>::max std::gamma\_distribution<RealType>::max
=======================================
| | | |
| --- | --- | --- |
|
```
result_type max() const;
```
| | (since C++11) |
Returns the maximum value potentially generated by the distribution.
### Parameters
(none).
### Return value
The maximum value potentially generated by the distribution.
### Complexity
Constant.
### See also
| | |
| --- | --- |
| [min](min "cpp/numeric/random/gamma distribution/min")
(C++11) | returns the minimum potentially generated value (public member function) |
cpp std::gamma_distribution<RealType>::min std::gamma\_distribution<RealType>::min
=======================================
| | | |
| --- | --- | --- |
|
```
result_type min() const;
```
| | (since C++11) |
Returns the minimum value potentially generated by the distribution.
### Parameters
(none).
### Return value
The minimum value potentially generated by the distribution.
### Complexity
Constant.
### See also
| | |
| --- | --- |
| [max](max "cpp/numeric/random/gamma distribution/max")
(C++11) | returns the maximum potentially generated value (public member function) |
cpp std::gamma_distribution<RealType>::gamma_distribution std::gamma\_distribution<RealType>::gamma\_distribution
=======================================================
| | | |
| --- | --- | --- |
|
```
gamma_distribution() : gamma_distribution(1.0) {}
```
| (1) | (since C++11) |
|
```
explicit gamma_distribution( RealType alpha, RealType beta = 1.0 );
```
| (2) | (since C++11) |
|
```
explicit gamma_distribution( const param_type& params );
```
| (3) | (since C++11) |
Constructs a new distribution object. (2) uses `alpha` and `beta` as the distribution parameters. (3) uses `params` as the distribution parameters.
### Parameters
| | | |
| --- | --- | --- |
| alpha | - | the *ฮฑ* distribution parameter (shape) |
| beta | - | the *ฮฒ* distribution parameter (scale) |
| params | - | the distribution parameter set |
### 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::gamma_distribution<RealType>::param std::gamma\_distribution<RealType>::param
=========================================
| | | |
| --- | --- | --- |
|
```
param_type param() const;
```
| (1) | (since C++11) |
|
```
void param( const param_type& params );
```
| (2) | (since C++11) |
Manages the associated distribution parameter set.
1) Returns the associated parameter set.
2) Sets the associated parameter set to `params`.
### Parameters
| | | |
| --- | --- | --- |
| params | - | new contents of the associated parameter set |
### Return value
1) The associated parameter set.
2) (none).
### Complexity
Constant.
cpp operator==,!=(std::gamma_distribution)
operator==,!=(std::gamma\_distribution)
=======================================
| | | |
| --- | --- | --- |
|
```
friend bool operator==( const gamma_distribution& lhs,
const gamma_distribution& rhs );
```
| (1) | (since C++11) |
|
```
friend bool operator!=( const gamma_distribution& lhs,
const gamma_distribution& rhs );
```
| (2) | (since C++11) (until C++20) |
Compares two distribution objects. Two distribution objects are equal when parameter values and internal state is the same.
1) Compares two distribution objects for equality.
2) Compares two distribution objects for inequality. These functions are not visible to ordinary [unqualified](../../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../../language/adl "cpp/language/adl") when `std::gamma_distribution<ResultType>` is an associated class of the arguments.
| | |
| --- | --- |
| The `!=` operator is [synthesized](../../../language/operators#Relational_operators "cpp/language/operators") from `operator==`. | (since C++20) |
### Parameters
| | | |
| --- | --- | --- |
| lhs, rhs | - | distribution objects to compare |
### Return value
1) `true` if the distribution objects are equal, `false` otherwise.
2) `true` if the distribution objects are not equal, `false` otherwise. ### Complexity
Constant.
### 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 3519](https://cplusplus.github.io/LWG/issue3519) | C++11 | the form of equality operators were unspecified(could be hidden friends or free function templates) | specified to be hidden friends |
cpp operator<<,>>(std::chi_squared_distribution)
operator<<,>>(std::chi\_squared\_distribution)
==============================================
| | | |
| --- | --- | --- |
|
```
template< class CharT, class Traits >
friend std::basic_ostream<CharT,Traits>&
operator<<( std::basic_ostream<CharT,Traits>& ost,
const chi_squared_distribution& d );
```
| (1) | (since C++11) |
|
```
template< class CharT, class Traits >
friend std::basic_istream<CharT,Traits>&
operator>>( std::basic_istream<CharT,Traits>& ist,
chi_squared_distribution& d );
```
| (2) | (since C++11) |
Performs stream input and output operations on pseudo-random number distribution `d`.
1) Writes a textual representation of the distribution parameters and internal state to `ost` as textual representation. The formatting flags and fill character of `ost` are unchanged.
2) Restores the distribution parameters and internal state with data read from `ist`. The formatting flags of `ist` are unchanged. The data must have been written using a stream with the same locale, `CharT` and `Traits` template parameters, otherwise the behavior is undefined. If bad input is encountered, `ist.setstate(std::ios::failbit)` is called, which may throw `[std::ios\_base::failure](../../../io/ios_base/failure "cpp/io/ios base/failure")`. `d` is unchanged in that case. These function templates are not visible to ordinary [unqualified](../../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../../language/adl "cpp/language/adl") when `std::chi_squared_distribution<ResultType>` is an associated class of the arguments.
### Parameters
| | | |
| --- | --- | --- |
| ost | - | output stream to insert the data to |
| ist | - | input stream to extract the data from |
| d | - | pseudo-random number distribution |
### Return value
1) `ost`
2) `ist`
### Exceptions
1) May throw implementation-defined exceptions.
2) May throw `[std::ios\_base::failure](../../../io/ios_base/failure "cpp/io/ios base/failure")` on bad input. ### 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 3519](https://cplusplus.github.io/LWG/issue3519) | C++11 | the form of insertion and extraction operators were unspecified(could be hidden friends or out-of-class function templates) | specified to be hidden friends |
| programming_docs |
cpp std::chi_squared_distribution<RealType>::reset std::chi\_squared\_distribution<RealType>::reset
================================================
| | | |
| --- | --- | --- |
|
```
void reset();
```
| | (since C++11) |
Resets the internal state of the distribution object. After a call to this function, the next call to `[operator()](operator() "cpp/numeric/random/chi squared distribution/operator()")` on the distribution object will not be dependent on previous calls to `[operator()](operator() "cpp/numeric/random/chi squared distribution/operator()")`.
### Parameters
(none).
### Return value
(none).
### Complexity
Constant.
cpp std::chi_squared_distribution<RealType>::n std::chi\_squared\_distribution<RealType>::n
============================================
| | | |
| --- | --- | --- |
|
```
RealType n() const;
```
| | (since C++11) |
Returns the n parameter the distribution was constructed with. It specifies the [degrees of freedom](https://en.wikipedia.org/wiki/Degrees_of_freedom_(statistics) "enwiki:Degrees of freedom (statistics)") of the distribution. The default value is `1.0`.
### Parameters
(none).
### Return value
The n distribution parameter.
### See also
| | |
| --- | --- |
| [param](param "cpp/numeric/random/chi squared distribution/param")
(C++11) | gets or sets the distribution parameter object (public member function) |
cpp std::chi_squared_distribution<RealType>::chi_squared_distribution std::chi\_squared\_distribution<RealType>::chi\_squared\_distribution
=====================================================================
| | | |
| --- | --- | --- |
|
```
chi_squared_distribution() : chi_squared_distribution(1.0) {}
```
| (1) | (since C++11) |
|
```
explicit chi_squared_distribution( RealType n );
```
| (2) | (since C++11) |
|
```
explicit chi_squared_distribution( const param_type& params );
```
| (3) | (since C++11) |
Constructs a new distribution object. (2) uses `n` as the distribution parameter. (3) uses `params` as the distribution parameter.
### Parameters
| | | |
| --- | --- | --- |
| n | - | the *n* distribution parameter (degrees of freedom) |
| params | - | the distribution parameter set |
### 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::chi_squared_distribution<RealType>::operator() std::chi\_squared\_distribution<RealType>::operator()
=====================================================
| | | |
| --- | --- | --- |
|
```
template< class Generator >
result_type operator()( Generator& g );
```
| (1) | (since C++11) |
|
```
template< class Generator >
result_type operator()( Generator& g, const param_type& params );
```
| (2) | (since C++11) |
Generates random numbers that are distributed according to the associated probability function. The entropy is acquired by calling `g.operator()`.
The first version uses the associated parameter set, the second version uses `params`. The associated parameter set is not modified.
### Parameters
| | | |
| --- | --- | --- |
| g | - | an uniform random bit generator object |
| params | - | distribution parameter set to use instead of the associated one |
| Type requirements |
| -`Generator` must meet the requirements of [UniformRandomBitGenerator](../../../named_req/uniformrandombitgenerator "cpp/named req/UniformRandomBitGenerator"). |
### Return value
The generated random number.
### Complexity
Amortized constant number of invocations of `g.operator()`.
cpp std::chi_squared_distribution<RealType>::max std::chi\_squared\_distribution<RealType>::max
==============================================
| | | |
| --- | --- | --- |
|
```
result_type max() const;
```
| | (since C++11) |
Returns the maximum value potentially generated by the distribution.
### Parameters
(none).
### Return value
The maximum value potentially generated by the distribution.
### Complexity
Constant.
### See also
| | |
| --- | --- |
| [min](min "cpp/numeric/random/chi squared distribution/min")
(C++11) | returns the minimum potentially generated value (public member function) |
cpp std::chi_squared_distribution<RealType>::min std::chi\_squared\_distribution<RealType>::min
==============================================
| | | |
| --- | --- | --- |
|
```
result_type min() const;
```
| | (since C++11) |
Returns the minimum value potentially generated by the distribution.
### Parameters
(none).
### Return value
The minimum value potentially generated by the distribution.
### Complexity
Constant.
### See also
| | |
| --- | --- |
| [max](max "cpp/numeric/random/chi squared distribution/max")
(C++11) | returns the maximum potentially generated value (public member function) |
cpp std::chi_squared_distribution<RealType>::param std::chi\_squared\_distribution<RealType>::param
================================================
| | | |
| --- | --- | --- |
|
```
param_type param() const;
```
| (1) | (since C++11) |
|
```
void param( const param_type& params );
```
| (2) | (since C++11) |
Manages the associated distribution parameter set.
1) Returns the associated parameter set.
2) Sets the associated parameter set to `params`.
### Parameters
| | | |
| --- | --- | --- |
| params | - | new contents of the associated parameter set |
### Return value
1) The associated parameter set.
2) (none).
### Complexity
Constant.
cpp operator==,!=(std::chi_squared_distribution)
operator==,!=(std::chi\_squared\_distribution)
==============================================
| | | |
| --- | --- | --- |
|
```
friend bool operator==( const chi_squared_distribution& lhs,
const chi_squared_distribution& rhs );
```
| (1) | (since C++11) |
|
```
friend bool operator!=( const chi_squared_distribution& lhs,
const chi_squared_distribution& rhs );
```
| (2) | (since C++11) (until C++20) |
Compares two distribution objects. Two distribution objects are equal when parameter values and internal state is the same.
1) Compares two distribution objects for equality.
2) Compares two distribution objects for inequality. These functions are not visible to ordinary [unqualified](../../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../../language/adl "cpp/language/adl") when `std::chi_squared_distribution<ResultType>` is an associated class of the arguments.
| | |
| --- | --- |
| The `!=` operator is [synthesized](../../../language/operators#Relational_operators "cpp/language/operators") from `operator==`. | (since C++20) |
### Parameters
| | | |
| --- | --- | --- |
| lhs, rhs | - | distribution objects to compare |
### Return value
1) `true` if the distribution objects are equal, `false` otherwise.
2) `true` if the distribution objects are not equal, `false` otherwise. ### Complexity
Constant.
### 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 3519](https://cplusplus.github.io/LWG/issue3519) | C++11 | the form of equality operators were unspecified(could be hidden friends or free function templates) | specified to be hidden friends |
cpp operator<<,>>(std::subtract_with_carry_engine)
operator<<,>>(std::subtract\_with\_carry\_engine)
=================================================
| | | |
| --- | --- | --- |
|
```
template< class CharT, class Traits >
friend std::basic_ostream<CharT,Traits>&
operator<<( std::basic_ostream<CharT,Traits>& ost,
const subtract_with_carry_engine& e );
```
| (1) | (since C++11) |
|
```
template< class CharT, class Traits >
friend std::basic_istream<CharT,Traits>&
operator>>( std::basic_istream<CharT,Traits>& ist,
subtract_with_carry_engine& e );
```
| (2) | (since C++11) |
1) Serializes the internal state of the pseudo-random number engine `e` as a sequence of decimal numbers separated by one or more spaces, and inserts it to the stream `ost`. The fill character and the formatting flags of the stream are ignored and unaffected.
2) Restores the internal state of the pseudo-random number engine `e` from the serialized representation, which was created by an earlier call to `operator<<` using a stream with the same imbued locale and the same `CharT` and `Traits`. If the input cannot be deserialized, `e` is left unchanged and `failbit` is raised on `ist`. These function templates are not visible to ordinary [unqualified](../../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../../language/adl "cpp/language/adl") when `std::subtract_with_carry_engine<UIntType,w,s,r>` is an associated class of the arguments.
If a textual representation is written using `os << x` and that representation is restored into the same or a different object `y` of the same type using `is >> y`, then `x==y`.
The textual representation is written with `os.fmtflags` set to `ios_base::dec`|`ios_base::left` and the fill character set to the space character. The textual representation of the engine's internal state is a set of decimal numbers separated by spaces.
### Parameters
| | | |
| --- | --- | --- |
| ost | - | output stream to insert the data to |
| ist | - | input stream to extract the data from |
| e | - | pseudo-random number engine |
### Return value
1) `ost`
2) `ist`
### Complexity
### Exceptions
1) May throw implementation-defined exceptions.
2) May throw `[std::ios\_base::failure](../../../io/ios_base/failure "cpp/io/ios base/failure")` when setting `failbit`. ### 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 3519](https://cplusplus.github.io/LWG/issue3519) | C++11 | the form of insertion and extraction operators were unspecified | specified to be hidden friends |
cpp std::subtract_with_carry_engine<UIntType,w,s,r>::seed std::subtract\_with\_carry\_engine<UIntType,w,s,r>::seed
========================================================
| | | |
| --- | --- | --- |
|
```
void seed( result_type value = default_seed );
```
| (1) | (since C++11) |
|
```
template< class Sseq >
void seed( Sseq& seq );
```
| (2) | (since C++11) |
Reinitializes the internal state of the random-number engine using new seed value.
### Parameters
| | | |
| --- | --- | --- |
| value | - | seed value to use in the initialization of the internal state |
| seq | - | seed sequence to use in the initialization of the internal state |
### Exceptions
Throws nothing.
### Complexity
cpp std::subtract_with_carry_engine<UIntType,w,s,r>::subtract_with_carry_engine std::subtract\_with\_carry\_engine<UIntType,w,s,r>::subtract\_with\_carry\_engine
=================================================================================
| | | |
| --- | --- | --- |
|
```
subtract_with_carry_engine() : subtract_with_carry_engine(default_seed) {}
```
| (1) | (since C++11) |
|
```
explicit subtract_with_carry_engine( result_type value );
```
| (2) | (since C++11) |
|
```
template< class Sseq >
explicit subtract_with_carry_engine( Sseq& s );
```
| (3) | (since C++11) |
|
```
subtract_with_carry_engine( const subtract_with_carry_engine& );
```
| (4) | (since C++11) (implicitly declared) |
Constructs the pseudo-random number engine.
1) Default constructor. Seeds the engine with `default_seed`. The overload (3) only participates in overload resolution if `Sseq` qualifies as a [SeedSequence](../../../named_req/seedsequence "cpp/named req/SeedSequence"). In particular, it is excluded from the set of candidate functions if `Sseq` is convertible to `result_type`.
### Parameters
| | | |
| --- | --- | --- |
| value | - | seed value to use in the initialization of the internal state |
| s | - | seed sequence to use in the initialization of the internal state |
### Complexity
### 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 |
### See also
| | |
| --- | --- |
| [seed](seed "cpp/numeric/random/subtract with carry engine/seed")
(C++11) | sets the current state of the engine (public member function) |
cpp std::subtract_with_carry_engine<UIntType,w,s,r>::operator() std::subtract\_with\_carry\_engine<UIntType,w,s,r>::operator()
==============================================================
| | | |
| --- | --- | --- |
|
```
result_type operator()();
```
| | (since C++11) |
Generates a pseudo-random value. The state of the engine is advanced by one position.
### Parameters
(none).
### Return value
A pseudo-random number in [`min()`, `max()`].
### Complexity
Amortized constant.
### See also
| | |
| --- | --- |
| [discard](discard "cpp/numeric/random/subtract with carry engine/discard")
(C++11) | advances the engine's state by a specified amount (public member function) |
cpp std::subtract_with_carry_engine<UIntType,w,s,r>::max std::subtract\_with\_carry\_engine<UIntType,w,s,r>::max
=======================================================
| | | |
| --- | --- | --- |
|
```
static constexpr result_type max();
```
| | (since C++11) |
Returns the maximum value potentially generated by the random-number engine. This value is equal to 2w
- 1, where `w` is the template parameter also accessible as static member `word_size`.
### Parameters
(none).
### Return value
The maximum potentially generated value.
### Complexity
Constant.
### See also
| | |
| --- | --- |
| [min](min "cpp/numeric/random/subtract with carry engine/min")
[static] (C++11) | gets the smallest possible value in the output range (public static member function) |
cpp std::subtract_with_carry_engine<UIntType,w,s,r>::min std::subtract\_with\_carry\_engine<UIntType,w,s,r>::min
=======================================================
| | | |
| --- | --- | --- |
|
```
static constexpr result_type min();
```
| | (since C++11) |
Returns the minimum value potentially generated by the random-number engine. This value is equal to `0u`.
### Parameters
(none).
### Return value
The minimum potentially generated value.
### Complexity
Constant.
### See also
| | |
| --- | --- |
| [max](max "cpp/numeric/random/subtract with carry engine/max")
[static] (C++11) | gets the largest possible value in the output range (public static member function) |
cpp operator==,!=(std::subtract_with_carry_engine)
operator==,!=(std::subtract\_with\_carry\_engine)
=================================================
| | | |
| --- | --- | --- |
|
```
friend bool operator==( const subtract_with_carry_engine& lhs,
const subtract_with_carry_engine& rhs );
```
| (1) | (since C++11) |
|
```
friend bool operator!=( const subtract_with_carry_engine& lhs,
const subtract_with_carry_engine& rhs );
```
| (2) | (since C++11) (until C++20) |
Compares two pseudo-random number engines. Two engines are equal, if their internal states are equivalent, that is, if they would generate equivalent values for any number of calls of `operator()`.
These functions are not visible to ordinary [unqualified](../../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../../language/adl "cpp/language/adl") when `std::subtract_with_carry_engine<UIntType,w,s,r>` is an associated class of the arguments.
| | |
| --- | --- |
| The `!=` operator is [synthesized](../../../language/operators#Relational_operators "cpp/language/operators") from `operator==`. | (since C++20) |
### Parameters
| | | |
| --- | --- | --- |
| lhs, rhs | - | engines to compare |
### Return value
1) `true` if the engines are equivalent, `false` otherwise.
2) `true` if the engines are not equivalent, `false` otherwise. ### Exceptions
Throws nothing.
### 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 3519](https://cplusplus.github.io/LWG/issue3519) | C++11 | the form of equality operators were unspecified | specified to be hidden friends |
cpp std::subtract_with_carry_engine<UIntType,w,s,r>::discard std::subtract\_with\_carry\_engine<UIntType,w,s,r>::discard
===========================================================
| | | |
| --- | --- | --- |
|
```
void discard( unsigned long long z );
```
| | (since C++11) |
Advances the internal state by `z` times. Equivalent to calling `[operator()](operator() "cpp/numeric/random/subtract with carry engine/operator()")` `z` times and discarding the result.
### Parameters
| | | |
| --- | --- | --- |
| z | - | integer value specifying the number of times to advance the state by |
### Return value
(none).
### Complexity
### Notes
For some engines, "fast jump" algorithms are known, which advance the state by many steps (order of millions) without calculating intermediate state transitions, although not necessarily in constant time.
### See also
| | |
| --- | --- |
| [operator()](operator() "cpp/numeric/random/subtract with carry engine/operator()")
(C++11) | advances the engine's state and returns the generated value (public member function) |
cpp operator<<,>>(std::discard_block_engine)
operator<<,>>(std::discard\_block\_engine)
==========================================
| | | |
| --- | --- | --- |
|
```
template< class CharT, class Traits >
friend std::basic_ostream<CharT,Traits>&
operator<<( std::basic_ostream<CharT,Traits>& ost,
discard_block_engine<>& e );
```
| (1) | (since C++11) |
|
```
template< class CharT, class Traits >
friend std::basic_istream<CharT,Traits>&
operator>>( std::basic_istream<CharT,Traits>& ist,
discard_block_engine& e );
```
| (2) | (since C++11) |
1) Serializes the internal state of the pseudo-random number engine adaptor as a sequence of decimal numbers separated by one or more spaces, and inserts it to the stream `ost`. The fill character and the formatting flags of the stream are ignored and unaffected.
2) Restores the internal state of the pseudo-random number engine adaptor `e` from the serialized representation, which was created by an earlier call to `operator<<` using a stream with the same imbued locale and the same `CharT` and `Traits`. If the input cannot be deserialized, `e` is left unchanged and `failbit` is raised on `ist`. These function templates are not visible to ordinary [unqualified](../../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../../language/adl "cpp/language/adl") when `std::discard_block_engine<Engine,p,r>` is an associated class of the arguments.
If a textual representation is written using `os << x` and that representation is restored into the same or a different object `y` of the same type using `is >> y`, then `x==y`.
### Parameters
| | | |
| --- | --- | --- |
| ost | - | output stream to insert the data to |
| ist | - | input stream to extract the data from |
| e | - | engine adaptor to serialize or restore |
### Return value
1) `ost`
2) `ist`
### Complexity
### Exceptions
1) May throw implementation-defined exceptions.
2) May throw `[std::ios\_base::failure](../../../io/ios_base/failure "cpp/io/ios base/failure")` when setting `failbit`. ### 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 3519](https://cplusplus.github.io/LWG/issue3519) | C++11 | the form of insertion and extraction operators were unspecified | specified to be hidden friends |
| programming_docs |
cpp std::discard_block_engine<Engine,P,R>::seed std::discard\_block\_engine<Engine,P,R>::seed
=============================================
| | | |
| --- | --- | --- |
|
```
void seed();
```
| (1) | (since C++11) |
|
```
void seed( result_type value );
```
| (2) | (since C++11) |
|
```
template< class Sseq >
void seed( Sseq& seq );
```
| (3) | (since C++11) |
Reinitializes the internal state of the underlying engine using a new seed value.
1) Seeds the underlying engine with the default seed value. Effectively calls `e.seed()`, where `e` is the underlying engine.
2) Seeds the underlying engine with the seed value `s`. Effectively calls `e.seed(value)`, where `e` is the underlying engine.
3) Seeds the underlying engine with the seed sequence `seq`. Effectively calls `e.seed(seq)`, where `e` is the underlying engine. This template only participate in overload resolution if `Sseq` qualifies as a [SeedSequence](../../../named_req/seedsequence "cpp/named req/SeedSequence"). In particular, this template does not participate in overload resolution if `Sseq` is implicitly convertible to `result_type`. ### Parameters
| | | |
| --- | --- | --- |
| value | - | seed value to use in the initialization of the internal state of the underlying engine |
| seq | - | seed sequence to use in the initialization of the internal state of the underlying engine |
### Return value
(none).
### Exceptions
Throws nothing.
cpp std::discard_block_engine<Engine,P,R>::base std::discard\_block\_engine<Engine,P,R>::base
=============================================
| | | |
| --- | --- | --- |
|
```
const Engine& base() const noexcept;
```
| | (since C++11) |
Returns the underlying engine.
### Parameters
(none).
### Return value
The underlying engine.
cpp std::discard_block_engine<Engine,P,R>::discard_block_engine std::discard\_block\_engine<Engine,P,R>::discard\_block\_engine
===============================================================
| | | |
| --- | --- | --- |
|
```
discard_block_engine();
```
| (1) | (since C++11) |
|
```
explicit discard_block_engine( result_type s );
```
| (2) | (since C++11) |
|
```
template< class Sseq >
explicit discard_block_engine( Sseq& seq );
```
| (3) | (since C++11) |
|
```
explicit discard_block_engine( const Engine& e );
```
| (4) | (since C++11) |
|
```
explicit discard_block_engine( Engine&& e );
```
| (5) | (since C++11) |
Constructs new pseudo-random engine adaptor.
1) Default constructor. The underlying engine is also default-constructed.
2) Constructs the underlying engine with `s`.
3) Constructs the underlying engine with seed sequence `seq`. This constructor only participate in overload resolution if `Sseq` qualifies as a [SeedSequence](../../../named_req/seedsequence "cpp/named req/SeedSequence"). In particular, this constructor does not participate in overload resolution if `Sseq` is implicitly convertible to `result_type`.
4) Constructs the underlying engine with a copy of `e`.
5) Move-constructs the underlying engine with `e`. `e` holds unspecified, but valid state afterwards. ### Parameters
| | | |
| --- | --- | --- |
| s | - | integer value to construct the underlying engine with |
| seq | - | seed sequence to construct the underlying engine with |
| e | - | pseudo-random number engine to initialize with |
### Example
cpp std::discard_block_engine<Engine,P,R>::operator() std::discard\_block\_engine<Engine,P,R>::operator()
===================================================
| | | |
| --- | --- | --- |
|
```
result_type operator()();
```
| | (since C++11) |
Generates a random value. The state of the underlying engine is advanced one or more times.
### Parameters
(none).
### Return value
A pseudo-random number in [`min()`, `max()`].
### Exceptions
Throws nothing.
### See also
| | |
| --- | --- |
| [discard](discard "cpp/numeric/random/discard block engine/discard")
(C++11) | advances the adaptor's state by a specified amount (public member function) |
cpp std::discard_block_engine<Engine,P,R>::max std::discard\_block\_engine<Engine,P,R>::max
============================================
| | | |
| --- | --- | --- |
|
```
static constexpr result_type max();
```
| | (since C++11) |
Returns the maximum value potentially generated by the engine adaptor. This value is equal to `e.max()` where `e` is the underlying engine.
### Parameters
(none).
### Return value
The maximum potentially generated value.
### Complexity
Constant.
### See also
| | |
| --- | --- |
| [min](min "cpp/numeric/random/discard block engine/min")
[static] (C++11) | gets the smallest possible value in the output range (public static member function) |
cpp std::discard_block_engine<Engine,P,R>::min std::discard\_block\_engine<Engine,P,R>::min
============================================
| | | |
| --- | --- | --- |
|
```
static constexpr result_type min();
```
| | (since C++11) |
Returns the minimum value potentially generated by the engine adaptor. This value is equal to `e.min()` where `e` is the underlying engine.
### Parameters
(none).
### Return value
The minimum potentially generated value.
### Complexity
Constant.
### See also
| | |
| --- | --- |
| [max](max "cpp/numeric/random/discard block engine/max")
[static] (C++11) | gets the largest possible value in the output range (public static member function) |
cpp operator==,!=(std::discard_block_engine)
operator==,!=(std::discard\_block\_engine)
==========================================
| | | |
| --- | --- | --- |
|
```
friend bool operator==( const discard_block_engine& lhs,
const discard_block_engine& rhs );
```
| (1) | (since C++11) |
|
```
friend bool operator!=( const discard_block_engine& lhs,
const discard_block_engine& rhs );
```
| (2) | (since C++11) (until C++20) |
Compares two pseudo-random number engine adaptors. Two engine adaptors are equal, if their underlying engines are equal and their internal state (if any) is equal, that is, if they would generate equivalent values for any number of calls of `operator()`.
These functions are not visible to ordinary [unqualified](../../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../../language/adl "cpp/language/adl") when `std::discard_block_engine<Engine,p,r>` is an associated class of the arguments.
| | |
| --- | --- |
| The `!=` operator is [synthesized](../../../language/operators#Relational_operators "cpp/language/operators") from `operator==`. | (since C++20) |
### Parameters
| | | |
| --- | --- | --- |
| lhs, rhs | - | engine adaptors to compare |
### Return value
1) `true` if the engine adaptors are equivalent, `false` otherwise.
2) `true` if the engine adaptors are not equivalent, `false` otherwise. ### Exceptions
Throws nothing.
### 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 3519](https://cplusplus.github.io/LWG/issue3519) | C++11 | the form of equality operators were unspecified | specified to be hidden friends |
cpp std::discard_block_engine<Engine,P,R>::discard std::discard\_block\_engine<Engine,P,R>::discard
================================================
| | | |
| --- | --- | --- |
|
```
void discard( unsigned long long z );
```
| | (since C++11) |
Advances the internal state by `z` times. Equivalent to calling `[operator()](operator() "cpp/numeric/random/discard block engine/operator()")` `z` times and discarding the result. The state of the underlying engine may be advanced by more than `z` times.
### Parameters
| | | |
| --- | --- | --- |
| z | - | integer value specifying the number of times to advance the state by |
### Return value
(none).
### Exceptions
Throws nothing.
### See also
| | |
| --- | --- |
| [operator()](operator() "cpp/numeric/random/discard block engine/operator()")
(C++11) | advances the state of the underlying engine and returns the generated value (public member function) |
cpp std::seed_seq::seed_seq std::seed\_seq::seed\_seq
=========================
| | | |
| --- | --- | --- |
|
```
seed_seq() noexcept;
```
| (1) | (since C++11) |
|
```
seed_seq( const seed_seq& ) = delete;
```
| (2) | (since C++11) |
|
```
template< class InputIt >
seed_seq( InputIt begin, InputIt end );
```
| (3) | (since C++11) |
|
```
template< class T >
seed_seq( std::initializer_list<T> il );
```
| (4) | (since C++11) |
1) The default constructor creates a `std::seed_seq` object with an initial seed sequence of length zero.
2) The copy constructor is deleted: `std::seed_seq` is not copyable.
3) Constructs a `std::seed_seq` with the initial seed sequence obtained by iterating over the range `[begin, end)` and copying the values obtained by dereferencing the iterator, modulo 232
(that is, the lower 32 bits are copied)
4) Equivalent to `seed_seq(il.begin(), il.end())`. This constructor enables [list-initialization](../../../language/list_initialization "cpp/language/list initialization") from the list of seed values. This overload participates in overload resolution only if `T` is an integer type. ### Parameters
| | | |
| --- | --- | --- |
| begin, end | - | the initial seed sequence represented as a pair of input iterators whose `[std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<>::value\_type` is an integer type |
| il | - | `[std::initializer\_list](../../../utility/initializer_list "cpp/utility/initializer list")` of objects of integer type, providing the initial seed sequence |
| Type requirements |
| -`InputIt` must meet the requirements of [LegacyInputIterator](../../../named_req/inputiterator "cpp/named req/InputIterator"). |
### Exceptions
3-4) Throws `[std::bad\_alloc](../../../memory/new/bad_alloc "cpp/memory/new/bad alloc")` on allocation failure. ### Example
```
#include <random>
#include <sstream>
#include <iterator>
int main()
{
std::seed_seq s1; // default-constructible
std::seed_seq s2{1, 2, 3}; // can use list-initialization
std::seed_seq s3 = {-1, 0, 1}; // another form of list-initialization
int a[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
std::seed_seq s4(a, a + 10); // can use iterators
std::istringstream buf("1 2 3 4 5");
std::istream_iterator<int> beg(buf), end;
std::seed_seq s5(beg, end); // even stream input iterators
}
```
### 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 3422](https://cplusplus.github.io/LWG/issue3422) | C++11 | the default constructor never fails but might be not noexcept;the initializer list constructor disabled list-initialization from iterator pairs | made noexcept;constrained |
cpp std::seed_seq::size std::seed\_seq::size
====================
| | | |
| --- | --- | --- |
|
```
std::size_t size() const noexcept;
```
| | (since C++11) |
Returns the size of the stored initial seed sequence.
### Parameters
(none).
### Return value
The size of the private container that was populated at construction time.
### Complexity
Constant time.
### Example
```
#include <random>
#include <iostream>
int main()
{
std::seed_seq s1 = {-1, 0, 1};
std::cout << s1.size() << '\n';
}
```
Output:
```
3
```
### Defect report
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [LWG 2440](https://cplusplus.github.io/LWG/issue2440) | C++11 | `seed_seq::size` was not required to be noexcept | required |
cpp std::seed_seq::generate std::seed\_seq::generate
========================
| | | |
| --- | --- | --- |
|
```
template< class RandomIt >
void generate( RandomIt begin, RandomIt end );
```
| | (since C++11) |
Fills the range `[begin, end)` with unsigned integer values `i`, 0 โค i < 232
, based on the data originally provided in the constructor of this `seed_seq`. The produced values are distributed over the entire 32-bit range even if the initial values were strongly biased.
The following algorithm is used (adapted from the initialization sequence of the Mersenne Twister generator by [Makoto Matsumoto and Takuji Nishimura](http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html), incorporating the improvements made by [Mutsuo Saito in 2007](http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/SFMT/M062821.pdf)).
* If `begin == end`, do nothing. Otherwise,
* First, set each element of the output range to the value `0x8b8b8b8b`
* Transform the elements of the output range according to the following algorithm:
For `k = 0,..., m-1`
.
where `m=max(s+1, n)`
and `n=end-begin`
and `s=v.size()`
and `v` is the private container holding the values originally provided by the constructor of this `seed_seq` object,
1. `begin[k+p] += r1`
2. `begin[k+q] += r2`
3. `begin[k] = r2`,
where `p=(n-t)/2`
and `q=p+t`
and `t=(n >= 623) ? 11 : (n >= 68) ? 7 : (n >= 39) ? 5 : (n >= 7) ? 3 : (n - 1) / 2`
and `r1=1664525 * T(begin[k]^begin[k+p]^begin[kโ1])`
and `T(x) = x ^ (x >> 27)`
and `r2=r1+s` if `k==0`, `r2=r1 + k%n + v[k-1]` if `0<k<=s`, `r2=r1 + k%n` if `k>s`.
For `k = m,..., m+n-1`,
1. `begin[k+p] ^= r3`
2. `begin[k+q] ^= r4`
3. `begin[k]=r4`
where `r3 = 1566083941 * T(begin[k]+begin[k+p]+begin[k-1])`
and `r4=r3 - k%n`.
where all calculations are performed modulo 232
and where the indexing of the output range (`begin[x]`) is taken modulo n.
### Parameters
| | | |
| --- | --- | --- |
| begin, end | - | mutable random-access iterators whose `[std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<>::value\_type` is an unsigned integer type suitable for storing 32-bit values |
| Type requirements |
| -`RandomIt` must meet the requirements of [LegacyRandomAccessIterator](../../../named_req/randomaccessiterator "cpp/named req/RandomAccessIterator"). |
### Return value
none, the results are written to the `[begin, end)` range.
### Exceptions
Only throws if the operations on `begin` and `end` throw.
### Example
```
#include <algorithm>
#include <cassert>
#include <cstdint>
#include <iostream>
#include <random>
// Prototyping the main part of std::seed_seq...
struct seed_seq {
std::vector<std::uint32_t> v;
seed_seq(std::initializer_list<std::uint32_t> const il) : v{il} {}
template <typename RandomIt>
void generate(RandomIt first, RandomIt last) {
if (first == last)
return;
//
// Assuming v = {1,2,3,4,5} and distance(first, last) == 10.
//
// Step 1: fill with 0x8b8b8b8b
// seeds = {2341178251, 2341178251, 2341178251, 2341178251, 2341178251,
// 2341178251, 2341178251, 2341178251, 2341178251, 2341178251 }
//
std::fill(first, last, 0x8b8b8b8b);
//
// Step 2:
// n = 10, s = 5, t = 3, p = 3, q = 6, m = 10
//
const std::uint32_t n = last - first;
const std::uint32_t s = v.size();
const std::uint32_t t = (n < 7) ? (n - 1) / 2
: (n < 39) ? 3
: (n < 68) ? 5
: (n < 623) ? 7
: 11;
const std::uint32_t p = (n - t) / 2;
const std::uint32_t q = p + t;
const std::uint32_t m = std::max(s + 1, n);
//
// First iteration, k = 0; r1 = 1371501266, r2 = 1371501271
//
// seeds = {1371501271, 2341178251, 2341178251, 3712679517, 2341178251,
// 2341178251, 3712679522, 2341178251, 2341178251, 2341178251 }
//
// Iterations from k = 1 to k = 5 (r2 = r1 + k%n + v[k-1])
//
// r1 = 2786190137, 3204727651, 4173325571, 1979226628, 401983366
// r2 = 2786190139, 3204727655, 4173325577, 1979226636, 401983376
//
// seeds = {3350727907, 3188173515, 3204727655, 4173325577, 1979226636,
// 401983376, 3591037797, 2811627722, 1652921976, 2219536532 }
//
// Iterations from k = 6 to k = 9 (r2 = r1 + k%n)
//
// r1 = 2718637909, 1378394210, 2297813071, 1608643617
// r2 = 2718637915, 1378394217, 2297813079, 1608643626
//
// seeds = { 434154821, 1191019290, 3237041891, 1256752498, 4277039715,
// 2010627002, 2718637915, 1378394217, 2297813079, 1608643626 }
//
auto begin_mod = [first, n](std::uint32_t u) -> decltype(*first)& {
return first[u % n]; // i.e. begin[x] is taken modulo n
};
auto T = [](std::uint32_t x) { return x ^ (x >> 27); };
for (std::uint32_t k = 0, r1, r2; k < m; ++k) {
r1 = 1664525 * T(begin_mod(k) ^ begin_mod(k + p) ^ begin_mod(k - 1));
r2 = (k == 0) ? r1 + s
: (k <= s) ? r1 + k % n + v[k - 1]
: r1 + k % n;
begin_mod(k + p) += r1;
begin_mod(k + q) += r2;
begin_mod(k) = r2;
}
//
// Step 3
// iterations from k = 10 to k = 19, using ^= to modify the output
//
// r1 = 1615303485, 3210438310, 893477041, 2884072672, 1918321961,
// r2 = 1615303485, 3210438309, 893477039, 2884072669, 1918321957
//
// seeds = { 303093272, 3210438309, 893477039, 2884072669, 1918321957,
// 1117182731, 1772877958, 2669970405, 3182737656, 4094066935 }
//
// r1 = 423054846, 46783064, 3904109085, 1534123446, 1495905687
// r2 = 423054841, 46783058, 3904109078, 1534123438, 1495905678
//
// seeds = { 4204997637, 4246533866, 1856049002, 1129615051, 690460811,
// 1075771511, 46783058, 3904109078, 1534123438, 1495905678 }
//
for (std::uint32_t k = m, r3, r4; k < m + n; ++k) {
r3 = 1566083941 * T(begin_mod(k) + begin_mod(k+p) + begin_mod(k-1));
r4 = r3 - k%n;
begin_mod(k+p) ^= r3;
begin_mod(k+q) ^= r4;
begin_mod(k) = r4;
}
}
};
int main()
{
const auto input = std::initializer_list<std::uint32_t>{1,2,3,4,5};
const auto output_size = 10;
// using std version of seed_seq
std::seed_seq seq(input);
std::vector<std::uint32_t> seeds(output_size);
seq.generate(seeds.begin(), seeds.end());
for(const std::uint32_t n : seeds) {
std::cout << n << '\n';
}
// using custom version of seed_seq
seed_seq seq2(input);
std::vector<std::uint32_t> seeds2(output_size);
seq2.generate(seeds2.begin(), seeds2.end());
assert(seeds == seeds2);
}
```
Output:
```
4204997637
4246533866
1856049002
1129615051
690460811
1075771511
46783058
3904109078
1534123438
1495905678
```
cpp std::seed_seq::param std::seed\_seq::param
=====================
| | | |
| --- | --- | --- |
|
```
template< class OutputIt >
void param( OutputIt dest ) const;
```
| | (since C++11) |
Outputs the initial seed sequence that's stored in the `std::seed_seq` object.
### Parameters
| | | |
| --- | --- | --- |
| dest | - | output iterator such that the expression `*dest=rt` is valid for a value `rt` of `result_type` |
| Type requirements |
| -`OutputIt` must meet the requirements of [LegacyOutputIterator](../../../named_req/outputiterator "cpp/named req/OutputIterator"). |
### Return value
(none).
### Exceptions
Throws only if an operation on `dest` throws.
### Example
```
#include <random>
#include <iostream>
#include <iterator>
int main()
{
std::seed_seq s1 = {-1, 0, 1};
s1.param(std::ostream_iterator<int>(std::cout, " "));
}
```
Output:
```
-1 0 1
```
| programming_docs |
cpp operator<<,>>(std::independent_bits_engine)
operator<<,>>(std::independent\_bits\_engine)
=============================================
| | | |
| --- | --- | --- |
|
```
template< class CharT, class Traits >
friend std::basic_ostream<CharT,Traits>&
operator<<( std::basic_ostream<CharT,Traits>& ost,
independent_bits_engine<>& e );
```
| (1) | (since C++11) |
|
```
template< class CharT, class Traits >
friend std::basic_istream<CharT,Traits>&
operator>>( std::basic_istream<CharT,Traits>& ist,
independent_bits_engine& e );
```
| (2) | (since C++11) |
1) Serializes the internal state of the pseudo-random number engine adaptor as a sequence of decimal numbers separated by one or more spaces, and inserts it to the stream `ost`. The fill character and the formatting flags of the stream are ignored and unaffected.
2) Restores the internal state of the pseudo-random number engine adaptor `e` from the serialized representation, which was created by an earlier call to `operator<<` using a stream with the same imbued locale and the same `CharT` and `Traits`. If the input cannot be deserialized, `e` is left unchanged and `failbit` is raised on `ist`. These function templates are not visible to ordinary [unqualified](../../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../../language/adl "cpp/language/adl") when `std::independent_bits_engine<Engine,w,UIntType>` is an associated class of the arguments.
If a textual representation is written using `os << x` and that representation is restored into the same or a different object `y` of the same type using `is >> y`, then `x==y`.
### Parameters
| | | |
| --- | --- | --- |
| ost | - | output stream to insert the data to |
| ist | - | input stream to extract the data from |
| e | - | engine adaptor to serialize or restore |
### Return value
1) `ost`
2) `ist`
### Complexity
### Exceptions
1) May throw implementation-defined exceptions.
2) May throw `[std::ios\_base::failure](../../../io/ios_base/failure "cpp/io/ios base/failure")` when setting `failbit`. ### 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 3519](https://cplusplus.github.io/LWG/issue3519) | C++11 | the form of insertion and extraction operators were unspecified | specified to be hidden friends |
cpp std::independent_bits_engine<Engine,W,UIntType>::seed std::independent\_bits\_engine<Engine,W,UIntType>::seed
=======================================================
| | | |
| --- | --- | --- |
|
```
void seed();
```
| (1) | (since C++11) |
|
```
void seed( result_type value );
```
| (2) | (since C++11) |
|
```
template< class Sseq >
void seed( Sseq& seq );
```
| (3) | (since C++11) |
Reinitializes the internal state of the underlying engine using a new seed value.
1) Seeds the underlying engine with the default seed value. Effectively calls `e.seed()`, where `e` is the underlying engine.
2) Seeds the underlying engine with the seed value `s`. Effectively calls `e.seed(value)`, where `e` is the underlying engine.
3) Seeds the underlying engine with the seed sequence `seq`. Effectively calls `e.seed(seq)`, where `e` is the underlying engine. This template only participate in overload resolution if `Sseq` qualifies as a [SeedSequence](../../../named_req/seedsequence "cpp/named req/SeedSequence"). In particular, this template does not participate in overload resolution if `Sseq` is implicitly convertible to `result_type`. ### Parameters
| | | |
| --- | --- | --- |
| value | - | seed value to use in the initialization of the internal state of the underlying engine |
| seq | - | seed sequence to use in the initialization of the internal state of the underlying engine |
### Return value
(none).
### Exceptions
Throws nothing.
cpp std::independent_bits_engine<Engine,W,UIntType>::base std::independent\_bits\_engine<Engine,W,UIntType>::base
=======================================================
| | | |
| --- | --- | --- |
|
```
const Engine& base() const noexcept;
```
| | (since C++11) |
Returns the underlying engine.
### Parameters
(none).
### Return value
The underlying engine.
cpp std::independent_bits_engine<Engine,W,UIntType>::independent_bits_engine std::independent\_bits\_engine<Engine,W,UIntType>::independent\_bits\_engine
============================================================================
| | | |
| --- | --- | --- |
|
```
independent_bits_engine();
```
| (1) | (since C++11) |
|
```
explicit independent_bits_engine( result_type s );
```
| (2) | (since C++11) |
|
```
template< class Sseq >
explicit independent_bits_engine( Sseq& seq );
```
| (3) | (since C++11) |
|
```
explicit independent_bits_engine( const Engine& e );
```
| (4) | (since C++11) |
|
```
explicit independent_bits_engine( Engine&& e );
```
| (5) | (since C++11) |
Constructs new pseudo-random engine adaptor.
1) Default constructor. The underlying engine is also default-constructed.
2) Constructs the underlying engine with `s`.
3) Constructs the underlying engine with seed sequence `seq`. This constructor only participate in overload resolution if `Sseq` qualifies as a [SeedSequence](../../../named_req/seedsequence "cpp/named req/SeedSequence"). In particular, this constructor does not participate in overload resolution if `Sseq` is implicitly convertible to `result_type`.
4) Constructs the underlying engine with a copy of `e`.
5) Move-constructs the underlying engine with `e`. `e` holds unspecified, but valid state afterwards. ### Parameters
| | | |
| --- | --- | --- |
| s | - | integer value to construct the underlying engine with |
| seq | - | seed sequence to construct the underlying engine with |
| e | - | pseudo-random number engine to initialize with |
### Example
```
#include <iostream>
#include <random>
int main()
{
auto print = [](auto rem, auto engine, int count) {
std::cout << rem << ": ";
for (int i{}; i != count; ++i)
std::cout << static_cast<unsigned>(engine()) << ' ';
std::cout << '\n';
};
std::independent_bits_engine<std::mt19937, /*bits*/ 1, unsigned short>
e1; // default-constructed
print("e1", e1, 8);
std::independent_bits_engine<std::mt19937, /*bits*/ 1, unsigned int>
e2(1); // constructed with 1
print("e2", e2, 8);
std::random_device rd;
std::independent_bits_engine<std::mt19937, /*bits*/ 3, unsigned long>
e3(rd()); // seeded with rd()
print("e3", e3, 8);
std::seed_seq s{3,1,4,1,5};
std::independent_bits_engine<std::mt19937, /*bits*/ 3, unsigned long long>
e4(s); // seeded with seed-sequence s
print("e4", e4, 8);
}
```
Possible output:
```
e1: 0 0 0 1 0 1 1 1
e2: 1 1 0 0 1 1 1 1
e3: 3 1 5 4 3 2 3 4
e4: 0 2 4 4 4 3 3 6
```
cpp std::independent_bits_engine<Engine,W,UIntType>::operator() std::independent\_bits\_engine<Engine,W,UIntType>::operator()
=============================================================
| | | |
| --- | --- | --- |
|
```
result_type operator()();
```
| | (since C++11) |
Generates a random value. The state of the underlying engine is advanced one or more times.
### Parameters
(none).
### Return value
A pseudo-random number in [`min()`, `max()`].
### Exceptions
Throws nothing.
### See also
| | |
| --- | --- |
| [discard](discard "cpp/numeric/random/independent bits engine/discard")
(C++11) | advances the adaptor's state by a specified amount (public member function) |
cpp std::independent_bits_engine<Engine,W,UIntType>::max std::independent\_bits\_engine<Engine,W,UIntType>::max
======================================================
| | | |
| --- | --- | --- |
|
```
static constexpr result_type max();
```
| | (since C++11) |
Returns the maximum value potentially generated by the engine adaptor. This value is equal to 2w
-1.
### Parameters
(none).
### Return value
The maximum potentially generated value.
### Complexity
Constant.
### See also
| | |
| --- | --- |
| [min](min "cpp/numeric/random/independent bits engine/min")
[static] (C++11) | gets the smallest possible value in the output range (public static member function) |
cpp std::independent_bits_engine<Engine,W,UIntType>::min std::independent\_bits\_engine<Engine,W,UIntType>::min
======================================================
| | | |
| --- | --- | --- |
|
```
static constexpr result_type min();
```
| | (since C++11) |
Returns the minimum value potentially generated by the engine adaptor. This value is equal to 0u.
### Parameters
(none).
### Return value
The minimum potentially generated value.
### Complexity
Constant.
### See also
| | |
| --- | --- |
| [max](max "cpp/numeric/random/independent bits engine/max")
[static] (C++11) | gets the largest possible value in the output range (public static member function) |
cpp operator==,!=(std::independent_bits_engine)
operator==,!=(std::independent\_bits\_engine)
=============================================
| | | |
| --- | --- | --- |
|
```
friend bool operator==( const independent_bits_engine& lhs,
const independent_bits_engine& rhs );
```
| (1) | (since C++11) |
|
```
friend bool operator!=( const independent_bits_engine& lhs,
const independent_bits_engine& rhs );
```
| (2) | (since C++11) (until C++20) |
Compares two pseudo-random number engine adaptors. Two engine adaptors are equal, if their underlying engines are equal and their internal state (if any) is equal, that is, if they would generate equivalent values for any number of calls of `operator()`.
These functions are not visible to ordinary [unqualified](../../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../../language/adl "cpp/language/adl") when `std::independent_bits_engine<Engine,w,UIntType>` is an associated class of the arguments.
| | |
| --- | --- |
| The `!=` operator is [synthesized](../../../language/operators#Relational_operators "cpp/language/operators") from `operator==`. | (since C++20) |
### Parameters
| | | |
| --- | --- | --- |
| lhs, rhs | - | engine adaptors to compare |
### Return value
1) `true` if the engine adaptors are equivalent, `false` otherwise.
2) `true` if the engine adaptors are not equivalent, `false` otherwise. ### Exceptions
Throws nothing.
### 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 3519](https://cplusplus.github.io/LWG/issue3519) | C++11 | the form of equality operators were unspecified | specified to be hidden friends |
cpp std::independent_bits_engine<Engine,W,UIntType>::discard std::independent\_bits\_engine<Engine,W,UIntType>::discard
==========================================================
| | | |
| --- | --- | --- |
|
```
void discard( unsigned long long z );
```
| | (since C++11) |
Advances the internal state by `z` times. Equivalent to calling `[operator()](operator() "cpp/numeric/random/independent bits engine/operator()")` `z` times and discarding the result. The state of the underlying engine may be advanced by more than `z` times.
### Parameters
| | | |
| --- | --- | --- |
| z | - | integer value specifying the number of times to advance the state by |
### Return value
(none).
### Exceptions
Throws nothing.
### See also
| | |
| --- | --- |
| [operator()](operator() "cpp/numeric/random/independent bits engine/operator()")
(C++11) | advances the state of the underlying engine and returns the generated value (public member function) |
cpp operator<<,>>(std::bernoulli_distribution)
operator<<,>>(std::bernoulli\_distribution)
===========================================
| | | |
| --- | --- | --- |
|
```
template< class CharT, class Traits >
friend std::basic_ostream<CharT,Traits>&
operator<<( std::basic_ostream<CharT,Traits>& ost,
const bernoulli_distribution& d );
```
| (1) | (since C++11) |
|
```
template< class CharT, class Traits >
friend std::basic_istream<CharT,Traits>&
operator>>( std::basic_istream<CharT,Traits>& ist,
bernoulli_distribution& d );
```
| (2) | (since C++11) |
Performs stream input and output operations on pseudo-random number distribution `d`.
1) Writes a textual representation of the distribution parameters and internal state to `ost` as textual representation. The formatting flags and fill character of `ost` are unchanged.
2) Restores the distribution parameters and internal state with data read from `ist`. The formatting flags of `ist` are unchanged. The data must have been written using a stream with the same locale, `CharT` and `Traits` template parameters, otherwise the behavior is undefined. If bad input is encountered, `ist.setstate(std::ios::failbit)` is called, which may throw `[std::ios\_base::failure](../../../io/ios_base/failure "cpp/io/ios base/failure")`. `d` is unchanged in that case. These function templates are not visible to ordinary [unqualified](../../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../../language/adl "cpp/language/adl") when `std::bernoulli_distribution` is an associated class of the arguments.
### Parameters
| | | |
| --- | --- | --- |
| ost | - | output stream to insert the data to |
| ist | - | input stream to extract the data from |
| d | - | pseudo-random number distribution |
### Return value
1) `ost`
2) `ist`
### Exceptions
1) May throw implementation-defined exceptions.
2) May throw `[std::ios\_base::failure](../../../io/ios_base/failure "cpp/io/ios base/failure")` on bad input. ### 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 3519](https://cplusplus.github.io/LWG/issue3519) | C++11 | the form of insertion and extraction operators were unspecified(could be hidden friends or out-of-class function templates) | specified to be hidden friends |
cpp std::bernoulli_distribution::reset std::bernoulli\_distribution::reset
===================================
| | | |
| --- | --- | --- |
|
```
void reset();
```
| | (since C++11) |
Resets the internal state of the distribution object. After a call to this function, the next call to `operator()` on the distribution object will not be dependent on previous calls to `operator()`.
### Parameters
(none).
### Return value
(none).
### Complexity
Constant.
cpp std::bernoulli_distribution::p std::bernoulli\_distribution::p
===============================
| | | |
| --- | --- | --- |
|
```
double p() const;
```
| | (since C++11) |
Returns the p parameter the distribution was constructed with. It defines the probability of generating `true`. The default value is `0.5`.
### Parameters
(none).
### Return value
Floating point value identifying the p distribution parameter.
### See also
| | |
| --- | --- |
| [param](param "cpp/numeric/random/bernoulli distribution/param")
(C++11) | gets or sets the distribution parameter object (public member function) |
cpp std::bernoulli_distribution::operator() std::bernoulli\_distribution::operator()
========================================
| | | |
| --- | --- | --- |
|
```
template< class Generator >
result_type operator()( Generator& g );
```
| (1) | (since C++11) |
|
```
template< class Generator >
result_type operator()( Generator& g, const param_type& params );
```
| (2) | (since C++11) |
Generates random numbers that are distributed according to the associated probability function. The entropy is acquired by calling `g.operator()`.
The first version uses the associated parameter set, the second version uses `params`. The associated parameter set is not modified.
### Parameters
| | | |
| --- | --- | --- |
| g | - | an uniform random bit generator object |
| params | - | distribution parameter set to use instead of the associated one |
| Type requirements |
| -`Generator` must meet the requirements of [UniformRandomBitGenerator](../../../named_req/uniformrandombitgenerator "cpp/named req/UniformRandomBitGenerator"). |
### Return value
The generated random number.
### Complexity
Amortized constant number of invocations of `g.operator()`.
cpp std::bernoulli_distribution::max std::bernoulli\_distribution::max
=================================
| | | |
| --- | --- | --- |
|
```
result_type max() const;
```
| | (since C++11) |
Returns the maximum value potentially generated by the distribution.
### Parameters
(none).
### Return value
The maximum value potentially generated by the distribution.
### Complexity
Constant.
### See also
| | |
| --- | --- |
| [min](min "cpp/numeric/random/bernoulli distribution/min")
(C++11) | returns the minimum potentially generated value (public member function) |
cpp std::bernoulli_distribution::min std::bernoulli\_distribution::min
=================================
| | | |
| --- | --- | --- |
|
```
result_type min() const;
```
| | (since C++11) |
Returns the minimum value potentially generated by the distribution.
### Parameters
(none).
### Return value
The minimum value potentially generated by the distribution.
### Complexity
Constant.
### See also
| | |
| --- | --- |
| [max](max "cpp/numeric/random/bernoulli distribution/max")
(C++11) | returns the maximum potentially generated value (public member function) |
cpp std::bernoulli_distribution::bernoulli_distribution std::bernoulli\_distribution::bernoulli\_distribution
=====================================================
| | | |
| --- | --- | --- |
|
```
bernoulli_distribution() : bernoulli_distribution(0.5) { }
```
| (1) | (since C++11) |
|
```
explicit bernoulli_distribution( double p );
```
| (2) | (since C++11) |
|
```
explicit bernoulli_distribution( const param_type& params );
```
| (3) | (since C++11) |
Constructs new distribution object. (2) uses `p` as the distribution parameter. (3) uses `params` as the distribution parameter.
### Parameters
| | | |
| --- | --- | --- |
| p | - | the *p* distribution parameter (probability of generating `true`) |
| params | - | the distribution parameter set |
### 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::bernoulli_distribution::param std::bernoulli\_distribution::param
===================================
| | | |
| --- | --- | --- |
|
```
param_type param() const;
```
| (1) | (since C++11) |
|
```
void param( const param_type& params );
```
| (2) | (since C++11) |
Manages the associated distribution parameter set.
1) Returns the associated parameter set.
2) Sets the associated parameter set to `params`.
### Parameters
| | | |
| --- | --- | --- |
| params | - | new contents of the associated parameter set |
### Return value
1) The associated parameter set.
2) (none).
### Complexity
Constant.
| programming_docs |
cpp operator==,!=(std::bernoulli_distribution)
operator==,!=(std::bernoulli\_distribution)
===========================================
| | | |
| --- | --- | --- |
|
```
friend bool operator==( const bernoulli_distribution& lhs,
const bernoulli_distribution& rhs );
```
| (1) | (since C++11) |
|
```
friend bool operator!=( const bernoulli_distribution& lhs,
const bernoulli_distribution& rhs );
```
| (2) | (since C++11) (until C++20) |
Compares two distribution objects. Two distribution objects are equal when parameter values and internal state is the same.
1) Compares two distribution objects for equality.
2) Compares two distribution objects for inequality. These functions are not visible to ordinary [unqualified](../../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../../language/adl "cpp/language/adl") when `std::bernoulli_distribution` is an associated class of the arguments.
| | |
| --- | --- |
| The `!=` operator is [synthesized](../../../language/operators#Relational_operators "cpp/language/operators") from `operator==`. | (since C++20) |
### Parameters
| | | |
| --- | --- | --- |
| lhs, rhs | - | distribution objects to compare |
### Return value
1) `true` if the distribution objects are equal, `false` otherwise.
2) `true` if the distribution objects are not equal, `false` otherwise. ### Complexity
Constant.
### 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 3519](https://cplusplus.github.io/LWG/issue3519) | C++11 | the form of equality operators were unspecified(could be hidden friends or free function templates) | specified to be hidden friends |
cpp operator<<,>>(std::binomial_distribution)
operator<<,>>(std::binomial\_distribution)
==========================================
| | | |
| --- | --- | --- |
|
```
template< class CharT, class Traits >
friend std::basic_ostream<CharT,Traits>&
operator<<( std::basic_ostream<CharT,Traits>& ost,
const binomial_distribution& d );
```
| (1) | (since C++11) |
|
```
template< class CharT, class Traits >
friend std::basic_istream<CharT,Traits>&
operator>>( std::basic_istream<CharT,Traits>& ist,
binomial_distribution& d );
```
| (2) | (since C++11) |
Performs stream input and output operations on pseudo-random number distribution `d`.
1) Writes a textual representation of the distribution parameters and internal state to `ost` as textual representation. The formatting flags and fill character of `ost` are unchanged.
2) Restores the distribution parameters and internal state with data read from `ist`. The formatting flags of `ist` are unchanged. The data must have been written using a stream with the same locale, `CharT` and `Traits` template parameters, otherwise the behavior is undefined. If bad input is encountered, `ist.setstate(std::ios::failbit)` is called, which may throw `[std::ios\_base::failure](../../../io/ios_base/failure "cpp/io/ios base/failure")`. `d` is unchanged in that case. These function templates are not visible to ordinary [unqualified](../../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../../language/adl "cpp/language/adl") when `std::binomial_distribution<ResultType>` is an associated class of the arguments.
### Parameters
| | | |
| --- | --- | --- |
| ost | - | output stream to insert the data to |
| ist | - | input stream to extract the data from |
| d | - | pseudo-random number distribution |
### Return value
1) `ost`
2) `ist`
### Exceptions
1) May throw implementation-defined exceptions.
2) May throw `[std::ios\_base::failure](../../../io/ios_base/failure "cpp/io/ios base/failure")` on bad input. ### 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 3519](https://cplusplus.github.io/LWG/issue3519) | C++11 | the form of insertion and extraction operators were unspecified(could be hidden friends or out-of-class function templates) | specified to be hidden friends |
cpp std::binomial_distribution<IntType>::reset std::binomial\_distribution<IntType>::reset
===========================================
| | | |
| --- | --- | --- |
|
```
void reset();
```
| | (since C++11) |
Resets the internal state of the distribution object. After a call to this function, the next call to `operator()` on the distribution object will not be dependent on previous calls to `operator()`.
### Parameters
(none).
### Return value
(none).
### Complexity
Constant.
cpp std::binomial_distribution<IntType>::operator() std::binomial\_distribution<IntType>::operator()
================================================
| | | |
| --- | --- | --- |
|
```
template< class Generator >
result_type operator()( Generator& g );
```
| (1) | (since C++11) |
|
```
template< class Generator >
result_type operator()( Generator& g, const param_type& params );
```
| (2) | (since C++11) |
Generates random numbers that are distributed according to the associated probability function. The entropy is acquired by calling `g.operator()`.
The first version uses the associated parameter set, the second version uses `params`. The associated parameter set is not modified.
### Parameters
| | | |
| --- | --- | --- |
| g | - | an uniform random bit generator object |
| params | - | distribution parameter set to use instead of the associated one |
| Type requirements |
| -`Generator` must meet the requirements of [UniformRandomBitGenerator](../../../named_req/uniformrandombitgenerator "cpp/named req/UniformRandomBitGenerator"). |
### Return value
The generated random number.
### Complexity
Amortized constant number of invocations of `g.operator()`.
cpp std::binomial_distribution<IntType>::p, t std::binomial\_distribution<IntType>::p, t
==========================================
| | | |
| --- | --- | --- |
|
```
double p() const;
```
| (1) | (since C++11) |
|
```
IntType t() const;
```
| (2) | (since C++11) |
Returns the parameters the distribution was constructed with.
1) Returns the p distribution parameter. It defines the probability of a trial generating `true`. The default value is `0.5`.
2) Returns the t distribution parameter. It identifies the number of trials. The default value is `1`. ### Parameters
(none).
### Return value
1) The p distribution parameter.
2) The t distribution parameter. ### See also
| | |
| --- | --- |
| [param](param "cpp/numeric/random/binomial distribution/param")
(C++11) | gets or sets the distribution parameter object (public member function) |
cpp std::binomial_distribution<IntType>::max std::binomial\_distribution<IntType>::max
=========================================
| | | |
| --- | --- | --- |
|
```
result_type max() const;
```
| | (since C++11) |
Returns the maximum value potentially generated by the distribution.
### Parameters
(none).
### Return value
The maximum value potentially generated by the distribution.
### Complexity
Constant.
### See also
| | |
| --- | --- |
| [min](min "cpp/numeric/random/binomial distribution/min")
(C++11) | returns the minimum potentially generated value (public member function) |
cpp std::binomial_distribution<IntType>::min std::binomial\_distribution<IntType>::min
=========================================
| | | |
| --- | --- | --- |
|
```
result_type min() const;
```
| | (since C++11) |
Returns the minimum value potentially generated by the distribution.
### Parameters
(none).
### Return value
The minimum value potentially generated by the distribution.
### Complexity
Constant.
### See also
| | |
| --- | --- |
| [max](max "cpp/numeric/random/binomial distribution/max")
(C++11) | returns the maximum potentially generated value (public member function) |
cpp std::binomial_distribution<IntType>::param std::binomial\_distribution<IntType>::param
===========================================
| | | |
| --- | --- | --- |
|
```
param_type param() const;
```
| (1) | (since C++11) |
|
```
void param( const param_type& params );
```
| (2) | (since C++11) |
Manages the associated distribution parameter set.
1) Returns the associated parameter set.
2) Sets the associated parameter set to `params`.
### Parameters
| | | |
| --- | --- | --- |
| params | - | new contents of the associated parameter set |
### Return value
1) The associated parameter set.
2) (none).
### Complexity
Constant.
### Example
```
#include <iostream>
#include <random>
int main()
{
std::random_device rd;
std::mt19937 gen(rd());
using BinomialDist = std::binomial_distribution<>;
BinomialDist bino_dis(1, 0.5);
std::cout << "A sample of Binomial( 1, 0.5): " << bino_dis(gen) << '\n';
// Use another parameter set
bino_dis.param(BinomialDist::param_type(100,0.9));
std::cout << "A sample of Binomial(100, 0.9): " << bino_dis(gen) << '\n';
}
```
Possible output:
```
A sample of Binomial( 1, 0.5): 0
A sample of Binomial(100, 0.9): 94
```
cpp operator==,!=(std::binomial_distribution)
operator==,!=(std::binomial\_distribution)
==========================================
| | | |
| --- | --- | --- |
|
```
friend bool operator==( const binomial_distribution& lhs,
const binomial_distribution& rhs );
```
| (1) | (since C++11) |
|
```
friend bool operator!=( const binomial_distribution& lhs,
const binomial_distribution& rhs );
```
| (2) | (since C++11) (until C++20) |
Compares two distribution objects. Two distribution objects are equal when parameter values and internal state is the same.
1) Compares two distribution objects for equality.
2) Compares two distribution objects for inequality. These functions are not visible to ordinary [unqualified](../../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../../language/adl "cpp/language/adl") when `std::binomial_distribution<ResultType>` is an associated class of the arguments.
| | |
| --- | --- |
| The `!=` operator is [synthesized](../../../language/operators#Relational_operators "cpp/language/operators") from `operator==`. | (since C++20) |
### Parameters
| | | |
| --- | --- | --- |
| lhs, rhs | - | distribution objects to compare |
### Return value
1) `true` if the distribution objects are equal, `false` otherwise.
2) `true` if the distribution objects are not equal, `false` otherwise. ### Complexity
Constant.
### 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 3519](https://cplusplus.github.io/LWG/issue3519) | C++11 | the form of equality operators were unspecified(could be hidden friends or free function templates) | specified to be hidden friends |
cpp std::binomial_distribution<IntType>::binomial_distribution std::binomial\_distribution<IntType>::binomial\_distribution
============================================================
| | | |
| --- | --- | --- |
|
```
binomial_distribution() : binomial_distribution(1) {}
```
| (1) | (since C++11) |
|
```
explicit binomial_distribution( IntType t, double p = 0.5 );
```
| (2) | (since C++11) |
|
```
explicit binomial_distribution( const param_type& params );
```
| (3) | (since C++11) |
Constructs a new distribution object. (2) uses `t` and `p` as the distribution parameters. (3) uses `params` as the distribution parameters.
### Parameters
| | | |
| --- | --- | --- |
| t | - | the *t* distribution parameter (number of trials) |
| p | - | the *p* distribution parameter (probability of a trial generating `true`) |
| params | - | the distribution parameter set |
### Notes
Requires that 0 โค p โค 1 and 0 โค t.
### 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 operator<<,>>(std::piecewise_constant_distribution)
operator<<,>>(std::piecewise\_constant\_distribution)
=====================================================
| | | |
| --- | --- | --- |
|
```
template< class CharT, class Traits >
friend std::basic_ostream<CharT,Traits>&
operator<<( std::basic_ostream<CharT,Traits>& ost,
const piecewise_constant_distribution& d );
```
| (1) | (since C++11) |
|
```
template< class CharT, class Traits >
friend std::basic_istream<CharT,Traits>&
operator>>( std::basic_istream<CharT,Traits>& ist,
piecewise_constant_distribution& d );
```
| (2) | (since C++11) |
Performs stream input and output operations on pseudo-random number distribution `d`.
1) Writes a textual representation of the distribution parameters and internal state to `ost` as textual representation. The formatting flags and fill character of `ost` are unchanged.
2) Restores the distribution parameters and internal state with data read from `ist`. The formatting flags of `ist` are unchanged. The data must have been written using a stream with the same locale, `CharT` and `Traits` template parameters, otherwise the behavior is undefined. If bad input is encountered, `ist.setstate(std::ios::failbit)` is called, which may throw `[std::ios\_base::failure](../../../io/ios_base/failure "cpp/io/ios base/failure")`. `d` is unchanged in that case. These function templates are not visible to ordinary [unqualified](../../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../../language/adl "cpp/language/adl") when `std::piecewise_constant_distribution<ResultType>` is an associated class of the arguments.
### Parameters
| | | |
| --- | --- | --- |
| ost | - | output stream to insert the data to |
| ist | - | input stream to extract the data from |
| d | - | pseudo-random number distribution |
### Return value
1) `ost`
2) `ist`
### Exceptions
1) May throw implementation-defined exceptions.
2) May throw `[std::ios\_base::failure](../../../io/ios_base/failure "cpp/io/ios base/failure")` on bad input. ### 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 3519](https://cplusplus.github.io/LWG/issue3519) | C++11 | the form of insertion and extraction operators were unspecified(could be hidden friends or out-of-class function templates) | specified to be hidden friends |
cpp std::piecewise_constant_distribution<RealType>::reset std::piecewise\_constant\_distribution<RealType>::reset
=======================================================
| | | |
| --- | --- | --- |
|
```
void reset();
```
| | (since C++11) |
Resets the internal state of the distribution object. After a call to this function, the next call to `[operator()](operator() "cpp/numeric/random/piecewise constant distribution/operator()")` on the distribution object will not be dependent on previous calls to `[operator()](operator() "cpp/numeric/random/piecewise constant distribution/operator()")`.
### Parameters
(none).
### Return value
(none).
### Complexity
Constant.
cpp std::piecewise_constant_distribution<RealType>::piecewise_constant_distribution std::piecewise\_constant\_distribution<RealType>::piecewise\_constant\_distribution
===================================================================================
| | | |
| --- | --- | --- |
|
```
piecewise_constant_distribution();
```
| (1) | (since C++11) |
|
```
template< class InputIt1, class InputIt2 >
piecewise_constant_distribution( InputIt1 first_i, InputIt1 last_i,
InputIt2 first_w );
```
| (2) | (since C++11) |
|
```
template< class UnaryOperation >
piecewise_constant_distribution( std::initializer_list<RealType> bl,
UnaryOperation fw );
```
| (3) | (since C++11) |
|
```
template< class UnaryOperation >
piecewise_constant_distribution( std::size_t nw,
RealType xmin, RealType xmax,
UnaryOperation fw );
```
| (4) | (since C++11) |
|
```
explicit piecewise_constant_distribution( const param_type& parm );
```
| (5) | (since C++11) |
Constructs new piecewise constant distribution object.
1) Constructs a distribution object with n = 1, ฯ0 = 1, b0 = 0, and b1 = 1.
2) Constructs a distribution object from iterators over the interval sequence `[first_i, last_i)` and a matching weight sequence starting at `first_w`.
3) Constructs a distribution object where the intervals are taken from the initializer list `bl` and the weights generated by the function `fw`.
4) Constructs a distribution object with the `nw` intervals distributed uniformly over `[xmin, xmax]` and the weights generated by the function `fw`.
5) Constructs a distribution object initialized with the parameters `param`. ### Parameters
| | | |
| --- | --- | --- |
| first\_i | - | iterator initialized to the start of the interval sequence |
| last\_i | - | iterator initialized to one-past-the-end of the interval sequence |
| first\_w | - | iterator initialized to the start of the density (weight) sequence |
| ilist\_i | - | initializer\_list yielding the interval sequence |
| fw | - | double(double) function yielding the densities |
| nw | - | the number of densities |
| xmin | - | the lower bound of the interval sequence |
| xmax | - | the upper bound of the interval sequence |
| parm | - | the distribution parameter set |
cpp std::piecewise_constant_distribution<RealType>::operator() std::piecewise\_constant\_distribution<RealType>::operator()
============================================================
| | | |
| --- | --- | --- |
|
```
template< class Generator >
result_type operator()( Generator& g );
```
| (1) | (since C++11) |
|
```
template< class Generator >
result_type operator()( Generator& g, const param_type& params );
```
| (2) | (since C++11) |
Generates random numbers that are distributed according to the associated probability function. The entropy is acquired by calling `g.operator()`.
The first version uses the associated parameter set, the second version uses `params`. The associated parameter set is not modified.
### Parameters
| | | |
| --- | --- | --- |
| g | - | an uniform random bit generator object |
| params | - | distribution parameter set to use instead of the associated one |
| Type requirements |
| -`Generator` must meet the requirements of [UniformRandomBitGenerator](../../../named_req/uniformrandombitgenerator "cpp/named req/UniformRandomBitGenerator"). |
### Return value
The generated random number.
### Complexity
Amortized constant number of invocations of `g.operator()`.
| programming_docs |
cpp std::piecewise_constant_distribution<RealType>::intervals, densities std::piecewise\_constant\_distribution<RealType>::intervals, densities
======================================================================
| | | |
| --- | --- | --- |
|
```
std::vector<RealType> intervals() const;
```
| (1) | (since C++11) |
|
```
std::vector<RealType> densities() const;
```
| (2) | (since C++11) |
Returns the distribution parameters.
1) Returns the list of boundaries of the intervals.
2) Returns the list of probability densities of the intervals. ### Parameters
(none).
### Return value
The distribution parameters:
1) The list of boundaries of the intervals.
2) The list of probability densities of the intervals. ### Complexity
Constant.
cpp std::piecewise_constant_distribution<RealType>::max std::piecewise\_constant\_distribution<RealType>::max
=====================================================
| | | |
| --- | --- | --- |
|
```
result_type max() const;
```
| | (since C++11) |
Returns the maximum value potentially generated by the distribution.
### Parameters
(none).
### Return value
The maximum value potentially generated by the distribution.
### Complexity
Constant.
### See also
| | |
| --- | --- |
| [min](min "cpp/numeric/random/piecewise constant distribution/min")
(C++11) | returns the minimum potentially generated value (public member function) |
cpp std::piecewise_constant_distribution<RealType>::min std::piecewise\_constant\_distribution<RealType>::min
=====================================================
| | | |
| --- | --- | --- |
|
```
result_type min() const;
```
| | (since C++11) |
Returns the minimum value potentially generated by the distribution.
### Parameters
(none).
### Return value
The minimum value potentially generated by the distribution.
### Complexity
Constant.
### See also
| | |
| --- | --- |
| [max](max "cpp/numeric/random/piecewise constant distribution/max")
(C++11) | returns the maximum potentially generated value (public member function) |
cpp std::piecewise_constant_distribution<RealType>::param std::piecewise\_constant\_distribution<RealType>::param
=======================================================
| | | |
| --- | --- | --- |
|
```
param_type param() const;
```
| (1) | (since C++11) |
|
```
void param( const param_type& params );
```
| (2) | (since C++11) |
Manages the associated distribution parameter set.
1) Returns the associated parameter set.
2) Sets the associated parameter set to `params`.
### Parameters
| | | |
| --- | --- | --- |
| params | - | new contents of the associated parameter set |
### Return value
1) The associated parameter set.
2) (none).
### Complexity
Constant.
cpp operator==,!=(std::piecewise_constant_distribution)
operator==,!=(std::piecewise\_constant\_distribution)
=====================================================
| | | |
| --- | --- | --- |
|
```
friend bool operator==( const piecewise_constant_distribution& lhs,
const piecewise_constant_distribution& rhs );
```
| (1) | (since C++11) |
|
```
friend bool operator!=( const piecewise_constant_distribution& lhs,
const piecewise_constant_distribution& rhs );
```
| (2) | (since C++11) (until C++20) |
Compares two distribution objects. Two distribution objects are equal when parameter values and internal state is the same.
1) Compares two distribution objects for equality.
2) Compares two distribution objects for inequality. These functions are not visible to ordinary [unqualified](../../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../../language/adl "cpp/language/adl") when `std::piecewise_constant_distribution<ResultType>` is an associated class of the arguments.
| | |
| --- | --- |
| The `!=` operator is [synthesized](../../../language/operators#Relational_operators "cpp/language/operators") from `operator==`. | (since C++20) |
### Parameters
| | | |
| --- | --- | --- |
| lhs, rhs | - | distribution objects to compare |
### Return value
1) `true` if the distribution objects are equal, `false` otherwise.
2) `true` if the distribution objects are not equal, `false` otherwise. ### Complexity
Constant.
### 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 3519](https://cplusplus.github.io/LWG/issue3519) | C++11 | the form of equality operators were unspecified(could be hidden friends or free function templates) | specified to be hidden friends |
cpp operator<<,>>(std::shuffle_order_engine)
operator<<,>>(std::shuffle\_order\_engine)
==========================================
| | | |
| --- | --- | --- |
|
```
template< class CharT, class Traits >
friend std::basic_ostream<CharT,Traits>&
operator<<( std::basic_ostream<CharT,Traits>& ost,
shuffle_order_engine<>& e );
```
| (1) | (since C++11) |
|
```
template< class CharT, class Traits >
friend std::basic_istream<CharT,Traits>&
operator>>( std::basic_istream<CharT,Traits>& ist,
shuffle_order_engine& e );
```
| (2) | (since C++11) |
1) Serializes the internal state of the pseudo-random number engine adaptor as a sequence of decimal numbers separated by one or more spaces, and inserts it to the stream `ost`. The fill character and the formatting flags of the stream are ignored and unaffected.
2) Restores the internal state of the pseudo-random number engine adaptor `e` from the serialized representation, which was created by an earlier call to `operator<<` using a stream with the same imbued locale and the same `CharT` and `Traits`. If the input cannot be deserialized, `e` is left unchanged and `failbit` is raised on `ist`. These function templates are not visible to ordinary [unqualified](../../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../../language/adl "cpp/language/adl") when `std::shuffle_order_engine<Engine,k>` is an associated class of the arguments.
If a textual representation is written using `os << x` and that representation is restored into the same or a different object `y` of the same type using `is >> y`, then `x==y`.
### Parameters
| | | |
| --- | --- | --- |
| ost | - | output stream to insert the data to |
| ist | - | input stream to extract the data from |
| e | - | engine adaptor to serialize or restore |
### Return value
1) `ost`
2) `ist`
### Complexity
### Exceptions
1) May throw implementation-defined exceptions.
2) May throw `[std::ios\_base::failure](../../../io/ios_base/failure "cpp/io/ios base/failure")` when setting `failbit`. ### 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 3519](https://cplusplus.github.io/LWG/issue3519) | C++11 | the form of insertion and extraction operators were unspecified | specified to be hidden friends |
cpp std::shuffle_order_engine<Engine,K>::seed std::shuffle\_order\_engine<Engine,K>::seed
===========================================
| | | |
| --- | --- | --- |
|
```
void seed();
```
| (1) | (since C++11) |
|
```
void seed( result_type value );
```
| (2) | (since C++11) |
|
```
template< class Sseq >
void seed( Sseq& seq );
```
| (3) | (since C++11) |
Reinitializes the internal state of the underlying engine using a new seed value.
1) Seeds the underlying engine with the default seed value. Effectively calls `e.seed()`, where `e` is the underlying engine.
2) Seeds the underlying engine with the seed value `s`. Effectively calls `e.seed(value)`, where `e` is the underlying engine.
3) Seeds the underlying engine with the seed sequence `seq`. Effectively calls `e.seed(seq)`, where `e` is the underlying engine. This template only participate in overload resolution if `Sseq` qualifies as a [SeedSequence](../../../named_req/seedsequence "cpp/named req/SeedSequence"). In particular, this template does not participate in overload resolution if `Sseq` is implicitly convertible to `result_type`. ### Parameters
| | | |
| --- | --- | --- |
| value | - | seed value to use in the initialization of the internal state of the underlying engine |
| seq | - | seed sequence to use in the initialization of the internal state of the underlying engine |
### Return value
(none).
### Exceptions
Throws nothing.
cpp std::shuffle_order_engine<Engine,K>::base std::shuffle\_order\_engine<Engine,K>::base
===========================================
| | | |
| --- | --- | --- |
|
```
const Engine& base() const noexcept;
```
| | (since C++11) |
Returns the underlying engine.
### Parameters
(none).
### Return value
The underlying engine.
cpp std::shuffle_order_engine<Engine,K>::operator() std::shuffle\_order\_engine<Engine,K>::operator()
=================================================
| | | |
| --- | --- | --- |
|
```
result_type operator()();
```
| | (since C++11) |
Generates a random value. The state of the underlying engine is advanced one or more times.
### Parameters
(none).
### Return value
A pseudo-random number in [`min()`, `max()`].
### Exceptions
Throws nothing.
### See also
| | |
| --- | --- |
| [discard](discard "cpp/numeric/random/shuffle order engine/discard")
(C++11) | advances the adaptor's state by a specified amount (public member function) |
cpp std::shuffle_order_engine<Engine,K>::shuffle_order_engine std::shuffle\_order\_engine<Engine,K>::shuffle\_order\_engine
=============================================================
| | | |
| --- | --- | --- |
|
```
shuffle_order_engine();
```
| (1) | (since C++11) |
|
```
explicit shuffle_order_engine( result_type s );
```
| (2) | (since C++11) |
|
```
template< class Sseq >
explicit shuffle_order_engine( Sseq& seq );
```
| (3) | (since C++11) |
|
```
explicit shuffle_order_engine( const Engine& e );
```
| (4) | (since C++11) |
|
```
explicit shuffle_order_engine( Engine&& e );
```
| (5) | (since C++11) |
Constructs new pseudo-random engine adaptor.
1) Default constructor. The underlying engine is also default-constructed.
2) Constructs the underlying engine with `s`.
3) Constructs the underlying engine with seed sequence `seq`. This constructor only participate in overload resolution if `Sseq` qualifies as a [SeedSequence](../../../named_req/seedsequence "cpp/named req/SeedSequence"). In particular, this constructor does not participate in overload resolution if `Sseq` is implicitly convertible to `result_type`.
4) Constructs the underlying engine with a copy of `e`.
5) Move-constructs the underlying engine with `e`. `e` holds unspecified, but valid state afterwards. ### Parameters
| | | |
| --- | --- | --- |
| s | - | integer value to construct the underlying engine with |
| seq | - | seed sequence to construct the underlying engine with |
| e | - | pseudo-random number engine to initialize with |
### Example
cpp std::shuffle_order_engine<Engine,K>::max std::shuffle\_order\_engine<Engine,K>::max
==========================================
| | | |
| --- | --- | --- |
|
```
static constexpr result_type max();
```
| | (since C++11) |
Returns the maximum value potentially generated by the engine adaptor. This value is equal to `e.max()` where `e` is the underlying engine.
### Parameters
(none).
### Return value
The maximum potentially generated value.
### Complexity
Constant.
### See also
| | |
| --- | --- |
| [min](min "cpp/numeric/random/shuffle order engine/min")
[static] (C++11) | gets the smallest possible value in the output range (public static member function) |
cpp std::shuffle_order_engine<Engine,K>::min std::shuffle\_order\_engine<Engine,K>::min
==========================================
| | | |
| --- | --- | --- |
|
```
static constexpr result_type min();
```
| | (since C++11) |
Returns the minimum value potentially generated by the engine adaptor. This value is equal to `e.min()` where `e` is the underlying engine.
### Parameters
(none).
### Return value
The minimum potentially generated value.
### Complexity
Constant.
### See also
| | |
| --- | --- |
| [max](max "cpp/numeric/random/shuffle order engine/max")
[static] (C++11) | gets the largest possible value in the output range (public static member function) |
cpp operator==,!=(std::shuffle_order_engine)
operator==,!=(std::shuffle\_order\_engine)
==========================================
| | | |
| --- | --- | --- |
|
```
friend bool operator==( const shuffle_order_engine& lhs,
const shuffle_order_engine& rhs );
```
| (1) | (since C++11) |
|
```
friend bool operator!=( const shuffle_order_engine& lhs,
const shuffle_order_engine& rhs );
```
| (2) | (since C++11) (until C++20) |
Compares two pseudo-random number engine adaptors. Two engine adaptors are equal, if their underlying engines are equal and their internal state (if any) is equal, that is, if they would generate equivalent values for any number of calls of `operator()`.
These functions are not visible to ordinary [unqualified](../../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../../language/adl "cpp/language/adl") when `std::shuffle_order_engine<Engine,k>` is an associated class of the arguments.
| | |
| --- | --- |
| The `!=` operator is [synthesized](../../../language/operators#Relational_operators "cpp/language/operators") from `operator==`. | (since C++20) |
### Parameters
| | | |
| --- | --- | --- |
| lhs, rhs | - | engine adaptors to compare |
### Return value
1) `true` if the engine adaptors are equivalent, `false` otherwise.
2) `true` if the engine adaptors are not equivalent, `false` otherwise. ### Exceptions
Throws nothing.
### 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 3519](https://cplusplus.github.io/LWG/issue3519) | C++11 | the form of equality operators were unspecified | specified to be hidden friends |
cpp std::shuffle_order_engine<Engine,K>::discard std::shuffle\_order\_engine<Engine,K>::discard
==============================================
| | | |
| --- | --- | --- |
|
```
void discard( unsigned long long z );
```
| | (since C++11) |
Advances the internal state by `z` times. Equivalent to calling `[operator()](operator() "cpp/numeric/random/shuffle order engine/operator()")` `z` times and discarding the result. The state of the underlying engine may be advanced by more than `z` times.
### Parameters
| | | |
| --- | --- | --- |
| z | - | integer value specifying the number of times to advance the state by |
### Return value
(none).
### Exceptions
Throws nothing.
### See also
| | |
| --- | --- |
| [operator()](operator() "cpp/numeric/random/shuffle order engine/operator()")
(C++11) | advances the state of the underlying engine and returns the generated value (public member function) |
cpp std::cauchy_distribution<RealType>::cauchy_distribution std::cauchy\_distribution<RealType>::cauchy\_distribution
=========================================================
| | | |
| --- | --- | --- |
|
```
cauchy_distribution() : cauchy_distribution(0.0) {}
```
| (1) | (since C++11) |
|
```
explicit cauchy_distribution( RealType a, RealType b = 1.0 );
```
| (2) | (since C++11) |
|
```
explicit cauchy_distribution( const param_type& params );
```
| (3) | (since C++11) |
Constructs a new distribution object. (2) uses `a` and `b` as the distribution parameters. (3) uses `params` as the distribution parameters.
### Parameters
| | | |
| --- | --- | --- |
| a | - | the *a* distribution parameter (location) |
| b | - | the *b* distribution parameter (scale) |
| params | - | the distribution parameter set |
### 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 operator<<,>>(std::cauchy_distribution)
operator<<,>>(std::cauchy\_distribution)
========================================
| | | |
| --- | --- | --- |
|
```
template< class CharT, class Traits >
friend std::basic_ostream<CharT,Traits>&
operator<<( std::basic_ostream<CharT,Traits>& ost,
const cauchy_distribution& d );
```
| (1) | (since C++11) |
|
```
template< class CharT, class Traits >
friend std::basic_istream<CharT,Traits>&
operator>>( std::basic_istream<CharT,Traits>& ist,
cauchy_distribution& d );
```
| (2) | (since C++11) |
Performs stream input and output operations on pseudo-random number distribution `d`.
1) Writes a textual representation of the distribution parameters and internal state to `ost` as textual representation. The formatting flags and fill character of `ost` are unchanged.
2) Restores the distribution parameters and internal state with data read from `ist`. The formatting flags of `ist` are unchanged. The data must have been written using a stream with the same locale, `CharT` and `Traits` template parameters, otherwise the behavior is undefined. If bad input is encountered, `ist.setstate(std::ios::failbit)` is called, which may throw `[std::ios\_base::failure](../../../io/ios_base/failure "cpp/io/ios base/failure")`. `d` is unchanged in that case. These function templates are not visible to ordinary [unqualified](../../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../../language/adl "cpp/language/adl") when `std::cauchy_distribution<ResultType>` is an associated class of the arguments.
### Parameters
| | | |
| --- | --- | --- |
| ost | - | output stream to insert the data to |
| ist | - | input stream to extract the data from |
| d | - | pseudo-random number distribution |
### Return value
1) `ost`
2) `ist`
### Exceptions
1) May throw implementation-defined exceptions.
2) May throw `[std::ios\_base::failure](../../../io/ios_base/failure "cpp/io/ios base/failure")` on bad input. ### 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 3519](https://cplusplus.github.io/LWG/issue3519) | C++11 | the form of insertion and extraction operators were unspecified(could be hidden friends or out-of-class function templates) | specified to be hidden friends |
| programming_docs |
cpp std::cauchy_distribution<RealType>::reset std::cauchy\_distribution<RealType>::reset
==========================================
| | | |
| --- | --- | --- |
|
```
void reset();
```
| | (since C++11) |
Resets the internal state of the distribution object. After a call to this function, the next call to `[operator()](operator() "cpp/numeric/random/cauchy distribution/operator()")` on the distribution object will not be dependent on previous calls to `[operator()](operator() "cpp/numeric/random/cauchy distribution/operator()")`.
### Parameters
(none).
### Return value
(none).
### Complexity
Constant.
cpp std::cauchy_distribution<RealType>::operator() std::cauchy\_distribution<RealType>::operator()
===============================================
| | | |
| --- | --- | --- |
|
```
template< class Generator >
result_type operator()( Generator& g );
```
| (1) | (since C++11) |
|
```
template< class Generator >
result_type operator()( Generator& g, const param_type& params );
```
| (2) | (since C++11) |
Generates random numbers that are distributed according to the associated probability function. The entropy is acquired by calling `g.operator()`.
The first version uses the associated parameter set, the second version uses `params`. The associated parameter set is not modified.
### Parameters
| | | |
| --- | --- | --- |
| g | - | an uniform random bit generator object |
| params | - | distribution parameter set to use instead of the associated one |
| Type requirements |
| -`Generator` must meet the requirements of [UniformRandomBitGenerator](../../../named_req/uniformrandombitgenerator "cpp/named req/UniformRandomBitGenerator"). |
### Return value
The generated random number.
### Complexity
Amortized constant number of invocations of `g.operator()`.
cpp std::cauchy_distribution<RealType>::a, b std::cauchy\_distribution<RealType>::a, b
=========================================
| | | |
| --- | --- | --- |
|
```
RealType a() const;
```
| (1) | (since C++11) |
|
```
RealType b() const;
```
| (2) | (since C++11) |
Returns the distribution parameters with which the distribution was constructed.
1) Returns the *a* parameter. It specifies the location of the peak and is also called location parameter. The default value is `0.0`.
2) Returns the *b* parameter. It represents the half-width at half-maximum (HWHM) and is also called scale parameter. The default value is `1.0`. ### Parameters
(none).
### Return value
1) The value of the *a* parameter.
2) The value of the *b* parameter. ### See also
| | |
| --- | --- |
| [param](param "cpp/numeric/random/cauchy distribution/param")
(C++11) | gets or sets the distribution parameter object (public member function) |
### External links
* [Scale parameter.](https://en.wikipedia.org/wiki/Scale_parameter) From Wikipedia.
* [Location parameter.](https://en.wikipedia.org/wiki/Location_parameter) From Wikipedia.
cpp std::cauchy_distribution<RealType>::max std::cauchy\_distribution<RealType>::max
========================================
| | | |
| --- | --- | --- |
|
```
result_type max() const;
```
| | (since C++11) |
Returns the maximum value potentially generated by the distribution.
### Parameters
(none).
### Return value
The maximum value potentially generated by the distribution.
### Complexity
Constant.
### See also
| | |
| --- | --- |
| [min](min "cpp/numeric/random/cauchy distribution/min")
(C++11) | returns the minimum potentially generated value (public member function) |
cpp std::cauchy_distribution<RealType>::min std::cauchy\_distribution<RealType>::min
========================================
| | | |
| --- | --- | --- |
|
```
result_type min() const;
```
| | (since C++11) |
Returns the minimum value potentially generated by the distribution.
### Parameters
(none).
### Return value
The minimum value potentially generated by the distribution.
### Complexity
Constant.
### See also
| | |
| --- | --- |
| [max](max "cpp/numeric/random/cauchy distribution/max")
(C++11) | returns the maximum potentially generated value (public member function) |
cpp std::cauchy_distribution<RealType>::param std::cauchy\_distribution<RealType>::param
==========================================
| | | |
| --- | --- | --- |
|
```
param_type param() const;
```
| (1) | (since C++11) |
|
```
void param( const param_type& params );
```
| (2) | (since C++11) |
Manages the associated distribution parameter set.
1) Returns the associated parameter set.
2) Sets the associated parameter set to `params`.
### Parameters
| | | |
| --- | --- | --- |
| params | - | new contents of the associated parameter set |
### Return value
1) The associated parameter set.
2) (none).
### Complexity
Constant.
cpp operator==,!=(std::cauchy_distribution)
operator==,!=(std::cauchy\_distribution)
========================================
| | | |
| --- | --- | --- |
|
```
friend bool operator==( const cauchy_distribution& lhs,
const cauchy_distribution& rhs );
```
| (1) | (since C++11) |
|
```
friend bool operator!=( const cauchy_distribution& lhs,
const cauchy_distribution& rhs );
```
| (2) | (since C++11) (until C++20) |
Compares two distribution objects. Two distribution objects are equal when parameter values and internal state is the same.
1) Compares two distribution objects for equality.
2) Compares two distribution objects for inequality. These functions are not visible to ordinary [unqualified](../../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../../language/adl "cpp/language/adl") when `std::cauchy_distribution<ResultType>` is an associated class of the arguments.
| | |
| --- | --- |
| The `!=` operator is [synthesized](../../../language/operators#Relational_operators "cpp/language/operators") from `operator==`. | (since C++20) |
### Parameters
| | | |
| --- | --- | --- |
| lhs, rhs | - | distribution objects to compare |
### Return value
1) `true` if the distribution objects are equal, `false` otherwise.
2) `true` if the distribution objects are not equal, `false` otherwise. ### Complexity
Constant.
### 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 3519](https://cplusplus.github.io/LWG/issue3519) | C++11 | the form of equality operators were unspecified(could be hidden friends or free function templates) | specified to be hidden friends |
cpp operator<<,>>(std::piecewise_linear_distribution)
operator<<,>>(std::piecewise\_linear\_distribution)
===================================================
| | | |
| --- | --- | --- |
|
```
template< class CharT, class Traits >
friend std::basic_ostream<CharT,Traits>&
operator<<( std::basic_ostream<CharT,Traits>& ost,
const piecewise_linear_distribution& d );
```
| (1) | (since C++11) |
|
```
template< class CharT, class Traits >
friend std::basic_istream<CharT,Traits>&
operator>>( std::basic_istream<CharT,Traits>& ist,
piecewise_linear_distribution& d );
```
| (2) | (since C++11) |
Performs stream input and output operations on pseudo-random number distribution `d`.
1) Writes a textual representation of the distribution parameters and internal state to `ost` as textual representation. The formatting flags and fill character of `ost` are unchanged.
2) Restores the distribution parameters and internal state with data read from `ist`. The formatting flags of `ist` are unchanged. The data must have been written using a stream with the same locale, `CharT` and `Traits` template parameters, otherwise the behavior is undefined. If bad input is encountered, `ist.setstate(std::ios::failbit)` is called, which may throw `[std::ios\_base::failure](../../../io/ios_base/failure "cpp/io/ios base/failure")`. `d` is unchanged in that case. These function templates are not visible to ordinary [unqualified](../../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../../language/adl "cpp/language/adl") when `std::piecewise_linear_distribution<ResultType>` is an associated class of the arguments.
### Parameters
| | | |
| --- | --- | --- |
| ost | - | output stream to insert the data to |
| ist | - | input stream to extract the data from |
| d | - | pseudo-random number distribution |
### Return value
1) `ost`
2) `ist`
### Exceptions
1) May throw implementation-defined exceptions.
2) May throw `[std::ios\_base::failure](../../../io/ios_base/failure "cpp/io/ios base/failure")` on bad input. ### 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 3519](https://cplusplus.github.io/LWG/issue3519) | C++11 | the form of insertion and extraction operators were unspecified(could be hidden friends or out-of-class function templates) | specified to be hidden friends |
cpp std::piecewise_linear_distribution<RealType>::reset std::piecewise\_linear\_distribution<RealType>::reset
=====================================================
| | | |
| --- | --- | --- |
|
```
void reset();
```
| | (since C++11) |
Resets the internal state of the distribution object. After a call to this function, the next call to `[operator()](operator() "cpp/numeric/random/piecewise linear distribution/operator()")` on the distribution object will not be dependent on previous calls to `[operator()](operator() "cpp/numeric/random/piecewise linear distribution/operator()")`.
### Parameters
(none).
### Return value
(none).
### Complexity
Constant.
cpp std::piecewise_linear_distribution<RealType>::operator() std::piecewise\_linear\_distribution<RealType>::operator()
==========================================================
| | | |
| --- | --- | --- |
|
```
template< class Generator >
result_type operator()( Generator& g );
```
| (1) | (since C++11) |
|
```
template< class Generator >
result_type operator()( Generator& g, const param_type& params );
```
| (2) | (since C++11) |
Generates random numbers that are distributed according to the associated probability function. The entropy is acquired by calling `g.operator()`.
The first version uses the associated parameter set, the second version uses `params`. The associated parameter set is not modified.
### Parameters
| | | |
| --- | --- | --- |
| g | - | an uniform random bit generator object |
| params | - | distribution parameter set to use instead of the associated one |
| Type requirements |
| -`Generator` must meet the requirements of [UniformRandomBitGenerator](../../../named_req/uniformrandombitgenerator "cpp/named req/UniformRandomBitGenerator"). |
### Return value
The generated random number.
### Complexity
Amortized constant number of invocations of `g.operator()`.
cpp std::piecewise_linear_distribution<RealType>::intervals, densities std::piecewise\_linear\_distribution<RealType>::intervals, densities
====================================================================
| | | |
| --- | --- | --- |
|
```
std::vector<RealType> intervals() const;
```
| (1) | (since C++11) |
|
```
std::vector<RealType> densities() const;
```
| (2) | (since C++11) |
Returns the distribution parameters.
1) Returns the list of boundaries of the intervals.
2) Returns the list of probability densities at the boundaries of the intervals. ### Parameters
(none).
### Return value
The distribution parameters:
1) The list of boundaries of the intervals.
2) The list of probability densities at the boundaries of the intervals. ### Complexity
Linear in the number of intervals in this object.
cpp std::piecewise_linear_distribution<RealType>::max std::piecewise\_linear\_distribution<RealType>::max
===================================================
| | | |
| --- | --- | --- |
|
```
result_type max() const;
```
| | (since C++11) |
Returns the maximum value potentially generated by the distribution.
### Parameters
(none).
### Return value
The maximum value potentially generated by the distribution.
### Complexity
Constant.
### See also
| | |
| --- | --- |
| [min](min "cpp/numeric/random/piecewise linear distribution/min")
(C++11) | returns the minimum potentially generated value (public member function) |
cpp std::piecewise_linear_distribution<RealType>::min std::piecewise\_linear\_distribution<RealType>::min
===================================================
| | | |
| --- | --- | --- |
|
```
result_type min() const;
```
| | (since C++11) |
Returns the minimum value potentially generated by the distribution.
### Parameters
(none).
### Return value
The minimum value potentially generated by the distribution.
### Complexity
Constant.
### See also
| | |
| --- | --- |
| [max](max "cpp/numeric/random/piecewise linear distribution/max")
(C++11) | returns the maximum potentially generated value (public member function) |
cpp std::piecewise_linear_distribution<RealType>::piecewise_linear_distribution std::piecewise\_linear\_distribution<RealType>::piecewise\_linear\_distribution
===============================================================================
| | | |
| --- | --- | --- |
|
```
piecewise_linear_distribution();
```
| (1) | (since C++11) |
|
```
template< class InputIt1, class InputIt2 >
piecewise_linear_distribution( InputIt1 first_i, InputIt1 last_i,
InputIt2 first_w );
```
| (2) | (since C++11) |
|
```
template< class UnaryOperation >
piecewise_linear_distribution( std::initializer_list<RealType> ilist,
UnaryOperation fw );
```
| (3) | (since C++11) |
|
```
template< class UnaryOperation >
piecewise_linear_distribution( std::size_t nw,
RealType xmin, RealType xmax,
UnaryOperation fw );
```
| (4) | (since C++11) |
|
```
explicit piecewise_linear_distribution( const param_type& parm );
```
| (5) | (since C++11) |
Constructs new piecewise linear distribution object.
1) Constructs a distribution object with *n* = 1, *ฯ0* = 1, *b0* = 0, and *b1* = 1.
2) Constructs a distribution object from iterators over the interval sequence `[first_i, last_i)` and a matching weight sequence starting at `first_w`.
3) Constructs a distribution object where the intervals are taken from the initializer list `ilist` and the weights generated by the function `fw`.
4) Constructs a distribution object with the `fw` intervals distributed uniformly over `[xmin, xmax]`
5) Constructs a distribution object initialized with the parameters `param`. ### Parameters
| | | |
| --- | --- | --- |
| first\_i | - | iterator initialized to the start of the interval sequence |
| last\_i | - | iterator initialized to one-past-the-end of the interval sequence |
| first\_w | - | iterator initialized to the start of the density (weight) sequence |
| ilist\_i | - | initializer\_list yielding the interval sequence |
| fw | - | double(double) function yielding the densities |
| nw | - | the number of densities |
| xmin | - | the lower bound of the interval sequence |
| xmax | - | the upper bound of the interval sequence |
| parm | - | the distribution parameter set |
cpp std::piecewise_linear_distribution<RealType>::param std::piecewise\_linear\_distribution<RealType>::param
=====================================================
| | | |
| --- | --- | --- |
|
```
param_type param() const;
```
| (1) | (since C++11) |
|
```
void param( const param_type& params );
```
| (2) | (since C++11) |
Manages the associated distribution parameter set.
1) Returns the associated parameter set.
2) Sets the associated parameter set to `params`.
### Parameters
| | | |
| --- | --- | --- |
| params | - | new contents of the associated parameter set |
### Return value
1) The associated parameter set.
2) (none).
### Complexity
Constant.
cpp operator==,!=(std::piecewise_linear_distribution)
operator==,!=(std::piecewise\_linear\_distribution)
===================================================
| | | |
| --- | --- | --- |
|
```
friend bool operator==( const piecewise_linear_distribution& lhs,
const piecewise_linear_distribution& rhs );
```
| (1) | (since C++11) |
|
```
friend bool operator!=( const piecewise_linear_distribution& lhs,
const piecewise_linear_distribution& rhs );
```
| (2) | (since C++11) (until C++20) |
Compares two distribution objects. Two distribution objects are equal when parameter values and internal state is the same.
1) Compares two distribution objects for equality.
2) Compares two distribution objects for inequality. These functions are not visible to ordinary [unqualified](../../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../../language/adl "cpp/language/adl") when `std::piecewise_linear_distribution<ResultType>` is an associated class of the arguments.
| | |
| --- | --- |
| The `!=` operator is [synthesized](../../../language/operators#Relational_operators "cpp/language/operators") from `operator==`. | (since C++20) |
### Parameters
| | | |
| --- | --- | --- |
| lhs, rhs | - | distribution objects to compare |
### Return value
1) `true` if the distribution objects are equal, `false` otherwise.
2) `true` if the distribution objects are not equal, `false` otherwise. ### Complexity
Constant.
### 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 3519](https://cplusplus.github.io/LWG/issue3519) | C++11 | the form of equality operators were unspecified(could be hidden friends or free function templates) | specified to be hidden friends |
cpp std::random_device::random_device std::random\_device::random\_device
===================================
| | | |
| --- | --- | --- |
|
```
random_device() : random_device(/*implementation-defined*/) {}
```
| (1) | (since C++11) |
|
```
explicit random_device(const std::string& token);
```
| (2) | (since C++11) |
|
```
random_device(const random_device& ) = delete;
```
| (3) | (since C++11) |
1) Default constructs a new `[std::random\_device](../random_device "cpp/numeric/random/random device")` object with an implementation-defined `token`.
2) Constructs a new `[std::random\_device](../random_device "cpp/numeric/random/random device")` object, making use of the argument `token` in an implementation-defined manner.
3) The copy constructor is deleted: `std::random_device` is not copyable nor movable. ### Exceptions
Throws an implementation-defined exceptions derived from `[std::exception](../../../error/exception "cpp/error/exception")` on failure.
### Notes
The implementation in [libstdc++](https://github.com/gcc-mirror/gcc/blob/master/libstdc%2B%2B-v3/src/c%2B%2B11/random.cc) expects `token` to name the source of random bytes. Possible token values include `"default"`, `"rand_s"`, `"rdseed"`, `"rdrand"`, `"rdrnd"`, `"/dev/urandom"`, `"/dev/random"`, `"mt19937"`, and integer string specifying the seed of the mt19937 engine. (Token values other than `"default"` are only valid for certain targets.).
The implementation in [libc++](http://llvm.org/viewvc/llvm-project/libcxx/trunk/src/random.cpp?view=markup), when configured to use character device as the source, expects `token` to be the name of a character device that produces random numbers when read from; otherwise it expects `token` to be `"/dev/urandom"`.
Both libstdc++ and libc++ throw an exception if provided an unsupported token. [Microsoft's stdlib](https://github.com/microsoft/STL/blob/c10ae01b4d9508eed9d5f059a120ee7223b6ac12/stl/inc/random#L5026) ignores the token entirely.
### Example
Demonstrates the two commonly available types of `std::random_device` on Linux.
```
#include <iostream>
#include <random>
int main()
{
std::uniform_int_distribution<int> d(0, 10);
std::random_device rd1; // uses RDRND or /dev/urandom
for(int n = 0; n < 10; ++n)
std::cout << d(rd1) << ' ';
std::cout << '\n';
std::random_device rd2("/dev/random"); // much slower on Linux
for(int n = 0; n < 10; ++n)
std::cout << d(rd2) << ' ';
std::cout << '\n';
}
```
Possible output:
```
7 10 7 0 4 4 6 9 4 7
2 4 10 6 3 2 0 6 3 7
```
### 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 |
| programming_docs |
cpp std::random_device::entropy std::random\_device::entropy
============================
| | | |
| --- | --- | --- |
|
```
double entropy() const noexcept;
```
| | (since C++11) |
Obtains an estimate of the random number device entropy, which is a floating-point value between 0 and log
2(max()+1) (which is equal to `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<unsigned int>::digits`). If the device has n states whose individual probabilities are P
0,...,P
n-1, the device entropy S is defined as.
S = -ฮฃn-1
i=0 P
ilog(P
i).
A deterministic random number generator (e.g. a pseudo-random engine) has entropy zero.
### Return value
The value of the device entropy, or zero if not applicable.
### Notes
This function is not fully implemented in some standard libraries. For example, [LLVM libc++](https://github.com/llvm-mirror/libcxx/blob/master/src/random.cpp#L174) prior to version 12 always returns zero even though the device is non-deterministic. In comparison, Microsoft Visual C++ implementation always returns 32, and [boost.random](https://github.com/boostorg/random/blob/master/src/random_device.cpp#L242) returns 10.
The entropy of the Linux kernel device /dev/urandom may be obtained using [ioctl RNDGETENTCNT](http://man7.org/linux/man-pages/man4/random.4.html) - that's what `std::random_device::entropy()` in [GNU libstdc++](https://github.com/gcc-mirror/gcc/blob/master/libstdc%2B%2B-v3/src/c%2B%2B11/random.cc#L188) uses as of version 8.1.
### Example
Example output on one of the implementations.
```
#include <iostream>
#include <random>
int main()
{
std::random_device rd;
std::cout << rd.entropy() << '\n';
}
```
Possible output:
```
32
```
cpp std::random_device::operator() std::random\_device::operator()
===============================
| | | |
| --- | --- | --- |
|
```
result_type operator()();
```
| | (since C++11) |
Generates a non-deterministic uniformly-distributed random value.
### Parameters
(none).
### Return value
A random number uniformly distributed in [`min()`, `max()`].
### Exceptions
Throws an implementation-defined exception derived from `[std::exception](../../../error/exception "cpp/error/exception")` if a random number could not be generated.
### See also
| | |
| --- | --- |
| [min](min "cpp/numeric/random/random device/min")
[static] (C++11) | gets the smallest possible value in the output range (public static member function) |
| [max](max "cpp/numeric/random/random device/max")
[static] (C++11) | gets the largest possible value in the output range (public static member function) |
cpp std::random_device::max std::random\_device::max
========================
| | | |
| --- | --- | --- |
|
```
static constexpr result_type max();
```
| | (since C++11) |
Returns the maximum value potentially generated by the random-number engine. This value is equal to `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<unsigned int>::max()`.
### Parameters
(none).
### Return value
The maximum potentially generated value.
### Complexity
Constant.
### See also
| | |
| --- | --- |
| [min](min "cpp/numeric/random/random device/min")
[static] (C++11) | gets the smallest possible value in the output range (public static member function) |
cpp std::random_device::min std::random\_device::min
========================
| | | |
| --- | --- | --- |
|
```
static constexpr result_type min();
```
| | (since C++11) |
Returns the minimum value potentially generated by the random-number engine. This value is equal to `0u`.
### Parameters
(none).
### Return value
The minimum potentially generated value.
### Complexity
Constant.
### See also
| | |
| --- | --- |
| [max](max "cpp/numeric/random/random device/max")
[static] (C++11) | gets the largest possible value in the output range (public static member function) |
cpp operator<<,>>(std::weibull_distribution)
operator<<,>>(std::weibull\_distribution)
=========================================
| | | |
| --- | --- | --- |
|
```
template< class CharT, class Traits >
friend std::basic_ostream<CharT,Traits>&
operator<<( std::basic_ostream<CharT,Traits>& ost,
const weibull_distribution& d );
```
| (1) | (since C++11) |
|
```
template< class CharT, class Traits >
friend std::basic_istream<CharT,Traits>&
operator>>( std::basic_istream<CharT,Traits>& ist,
weibull_distribution& d );
```
| (2) | (since C++11) |
Performs stream input and output operations on pseudo-random number distribution `d`.
1) Writes a textual representation of the distribution parameters and internal state to `ost` as textual representation. The formatting flags and fill character of `ost` are unchanged.
2) Restores the distribution parameters and internal state with data read from `ist`. The formatting flags of `ist` are unchanged. The data must have been written using a stream with the same locale, `CharT` and `Traits` template parameters, otherwise the behavior is undefined. If bad input is encountered, `ist.setstate(std::ios::failbit)` is called, which may throw `[std::ios\_base::failure](../../../io/ios_base/failure "cpp/io/ios base/failure")`. `d` is unchanged in that case. These function templates are not visible to ordinary [unqualified](../../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../../language/adl "cpp/language/adl") when `std::weibull_distribution<ResultType>` is an associated class of the arguments.
### Parameters
| | | |
| --- | --- | --- |
| ost | - | output stream to insert the data to |
| ist | - | input stream to extract the data from |
| d | - | pseudo-random number distribution |
### Return value
1) `ost`
2) `ist`
### Exceptions
1) May throw implementation-defined exceptions.
2) May throw `[std::ios\_base::failure](../../../io/ios_base/failure "cpp/io/ios base/failure")` on bad input. ### 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 3519](https://cplusplus.github.io/LWG/issue3519) | C++11 | the form of insertion and extraction operators were unspecified(could be hidden friends or out-of-class function templates) | specified to be hidden friends |
cpp std::weibull_distribution<RealType>::reset std::weibull\_distribution<RealType>::reset
===========================================
| | | |
| --- | --- | --- |
|
```
void reset();
```
| | (since C++11) |
Resets the internal state of the distribution object. After a call to this function, the next call to `[operator()](operator() "cpp/numeric/random/weibull distribution/operator()")` on the distribution object will not be dependent on previous calls to `[operator()](operator() "cpp/numeric/random/weibull distribution/operator()")`.
### Parameters
(none).
### Return value
(none).
### Complexity
Constant.
cpp std::weibull_distribution<RealType>::operator() std::weibull\_distribution<RealType>::operator()
================================================
| | | |
| --- | --- | --- |
|
```
template< class Generator >
result_type operator()( Generator& g );
```
| (1) | (since C++11) |
|
```
template< class Generator >
result_type operator()( Generator& g, const param_type& params );
```
| (2) | (since C++11) |
Generates random numbers that are distributed according to the associated probability function. The entropy is acquired by calling `g.operator()`.
The first version uses the associated parameter set, the second version uses `params`. The associated parameter set is not modified.
### Parameters
| | | |
| --- | --- | --- |
| g | - | an uniform random bit generator object |
| params | - | distribution parameter set to use instead of the associated one |
| Type requirements |
| -`Generator` must meet the requirements of [UniformRandomBitGenerator](../../../named_req/uniformrandombitgenerator "cpp/named req/UniformRandomBitGenerator"). |
### Return value
The generated random number.
### Complexity
Amortized constant number of invocations of `g.operator()`.
cpp std::weibull_distribution<RealType>::a, b std::weibull\_distribution<RealType>::a, b
==========================================
| | | |
| --- | --- | --- |
|
```
RealType a() const;
```
| (1) | (since C++11) |
|
```
RealType b() const;
```
| (2) | (since C++11) |
Returns the parameters the distribution was constructed with.
1) Returns the a parameter. It defines the shape of the distribution. The default value is `1.0`.
2) Returns the b parameter. It defines the scale of the distribution. The default value is `1.0`. ### Parameters
(none).
### Return value
1) The value of the a parameter.
2) The value of the b parameter. ### Complexity
Constant.
### See also
| | |
| --- | --- |
| [param](param "cpp/numeric/random/weibull distribution/param")
(C++11) | gets or sets the distribution parameter object (public member function) |
cpp std::weibull_distribution<RealType>::max std::weibull\_distribution<RealType>::max
=========================================
| | | |
| --- | --- | --- |
|
```
result_type max() const;
```
| | (since C++11) |
Returns the maximum value potentially generated by the distribution.
### Parameters
(none).
### Return value
The maximum value potentially generated by the distribution.
### Complexity
Constant.
### See also
| | |
| --- | --- |
| [min](min "cpp/numeric/random/weibull distribution/min")
(C++11) | returns the minimum potentially generated value (public member function) |
cpp std::weibull_distribution<RealType>::min std::weibull\_distribution<RealType>::min
=========================================
| | | |
| --- | --- | --- |
|
```
result_type min() const;
```
| | (since C++11) |
Returns the minimum value potentially generated by the distribution.
### Parameters
(none).
### Return value
The minimum value potentially generated by the distribution.
### Complexity
Constant.
### See also
| | |
| --- | --- |
| [max](max "cpp/numeric/random/weibull distribution/max")
(C++11) | returns the maximum potentially generated value (public member function) |
cpp std::weibull_distribution<RealType>::weibull_distribution std::weibull\_distribution<RealType>::weibull\_distribution
===========================================================
| | | |
| --- | --- | --- |
|
```
weibull_distribution() : weibull_distribution(1.0) {}
```
| (1) | (since C++11) |
|
```
explicit weibull_distribution( RealType a, RealType b = 1.0 );
```
| (2) | (since C++11) |
|
```
explicit weibull_distribution( const param_type& params );
```
| (3) | (since C++11) |
Constructs a new distribution object. (2) uses `a` and `b` as the distribution parameters. (3) uses `params` as the distribution parameters.
### Parameters
| | | |
| --- | --- | --- |
| a | - | the *a* distribution parameter (shape) |
| b | - | the *b* distribution parameter (scale) |
| params | - | the distribution parameter set |
### 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::weibull_distribution<RealType>::param std::weibull\_distribution<RealType>::param
===========================================
| | | |
| --- | --- | --- |
|
```
param_type param() const;
```
| (1) | (since C++11) |
|
```
void param( const param_type& params );
```
| (2) | (since C++11) |
Manages the associated distribution parameter set.
1) Returns the associated parameter set.
2) Sets the associated parameter set to `params`.
### Parameters
| | | |
| --- | --- | --- |
| params | - | new contents of the associated parameter set |
### Return value
1) The associated parameter set.
2) (none).
### Complexity
Constant.
cpp operator==,!=(std::weibull_distribution)
operator==,!=(std::weibull\_distribution)
=========================================
| | | |
| --- | --- | --- |
|
```
friend bool operator==( const weibull_distribution& lhs,
const weibull_distribution& rhs );
```
| (1) | (since C++11) |
|
```
friend bool operator!=( const weibull_distribution& lhs,
const weibull_distribution& rhs );
```
| (2) | (since C++11) (until C++20) |
Compares two distribution objects. Two distribution objects are equal when parameter values and internal state is the same.
1) Compares two distribution objects for equality.
2) Compares two distribution objects for inequality. These functions are not visible to ordinary [unqualified](../../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../../language/adl "cpp/language/adl") when `std::weibull_distribution<ResultType>` is an associated class of the arguments.
| | |
| --- | --- |
| The `!=` operator is [synthesized](../../../language/operators#Relational_operators "cpp/language/operators") from `operator==`. | (since C++20) |
### Parameters
| | | |
| --- | --- | --- |
| lhs, rhs | - | distribution objects to compare |
### Return value
1) `true` if the distribution objects are equal, `false` otherwise.
2) `true` if the distribution objects are not equal, `false` otherwise. ### Complexity
Constant.
### 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 3519](https://cplusplus.github.io/LWG/issue3519) | C++11 | the form of equality operators were unspecified(could be hidden friends or free function templates) | specified to be hidden friends |
cpp operator<<,>>(std::extreme_value_distribution)
operator<<,>>(std::extreme\_value\_distribution)
================================================
| | | |
| --- | --- | --- |
|
```
template< class CharT, class Traits >
friend std::basic_ostream<CharT,Traits>&
operator<<( std::basic_ostream<CharT,Traits>& ost,
const extreme_value_distribution& d );
```
| (1) | (since C++11) |
|
```
template< class CharT, class Traits >
friend std::basic_istream<CharT,Traits>&
operator>>( std::basic_istream<CharT,Traits>& ist,
extreme_value_distribution& d );
```
| (2) | (since C++11) |
Performs stream input and output operations on pseudo-random number distribution `d`.
1) Writes a textual representation of the distribution parameters and internal state to `ost` as textual representation. The formatting flags and fill character of `ost` are unchanged.
2) Restores the distribution parameters and internal state with data read from `ist`. The formatting flags of `ist` are unchanged. The data must have been written using a stream with the same locale, `CharT` and `Traits` template parameters, otherwise the behavior is undefined. If bad input is encountered, `ist.setstate(std::ios::failbit)` is called, which may throw `[std::ios\_base::failure](../../../io/ios_base/failure "cpp/io/ios base/failure")`. `d` is unchanged in that case. These function templates are not visible to ordinary [unqualified](../../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../../language/adl "cpp/language/adl") when `std::extreme_value_distribution<ResultType>` is an associated class of the arguments.
### Parameters
| | | |
| --- | --- | --- |
| ost | - | output stream to insert the data to |
| ist | - | input stream to extract the data from |
| d | - | pseudo-random number distribution |
### Return value
1) `ost`
2) `ist`
### Exceptions
1) May throw implementation-defined exceptions.
2) May throw `[std::ios\_base::failure](../../../io/ios_base/failure "cpp/io/ios base/failure")` on bad input. ### 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 3519](https://cplusplus.github.io/LWG/issue3519) | C++11 | the form of insertion and extraction operators were unspecified(could be hidden friends or out-of-class function templates) | specified to be hidden friends |
cpp std::extreme_value_distribution<RealType>::reset std::extreme\_value\_distribution<RealType>::reset
==================================================
| | | |
| --- | --- | --- |
|
```
void reset();
```
| | (since C++11) |
Resets the internal state of the distribution object. After a call to this function, the next call to `[operator()](operator() "cpp/numeric/random/extreme value distribution/operator()")` on the distribution object will not be dependent on previous calls to `[operator()](operator() "cpp/numeric/random/extreme value distribution/operator()")`.
### Parameters
(none).
### Return value
(none).
### Complexity
Constant.
cpp std::extreme_value_distribution<RealType>::operator() std::extreme\_value\_distribution<RealType>::operator()
=======================================================
| | | |
| --- | --- | --- |
|
```
template< class Generator >
result_type operator()( Generator& g );
```
| (1) | (since C++11) |
|
```
template< class Generator >
result_type operator()( Generator& g, const param_type& params );
```
| (2) | (since C++11) |
Generates random numbers that are distributed according to the associated probability function. The entropy is acquired by calling `g.operator()`.
The first version uses the associated parameter set, the second version uses `params`. The associated parameter set is not modified.
### Parameters
| | | |
| --- | --- | --- |
| g | - | an uniform random bit generator object |
| params | - | distribution parameter set to use instead of the associated one |
| Type requirements |
| -`Generator` must meet the requirements of [UniformRandomBitGenerator](../../../named_req/uniformrandombitgenerator "cpp/named req/UniformRandomBitGenerator"). |
### Return value
The generated random number.
### Complexity
Amortized constant number of invocations of `g.operator()`.
cpp std::extreme_value_distribution<RealType>::a, b std::extreme\_value\_distribution<RealType>::a, b
=================================================
| | | |
| --- | --- | --- |
|
```
RealType a() const;
```
| (1) | (since C++11) |
|
```
RealType b() const;
```
| (2) | (since C++11) |
Returns the parameters the distribution was constructed with.
1) Returns the a distribution parameter (location). The default value is `1.0`.
2) Returns the b distribution parameter (scale). The default value is `0.0`. ### Parameters
(none).
### Return value
1) The a distribution parameter (location).
2) The b distribution parameter (scale). ### See also
| | |
| --- | --- |
| [param](param "cpp/numeric/random/extreme value distribution/param")
(C++11) | gets or sets the distribution parameter object (public member function) |
| programming_docs |
cpp std::extreme_value_distribution<RealType>::max std::extreme\_value\_distribution<RealType>::max
================================================
| | | |
| --- | --- | --- |
|
```
result_type max() const;
```
| | (since C++11) |
Returns the maximum value potentially generated by the distribution.
### Parameters
(none).
### Return value
The maximum value potentially generated by the distribution.
### Complexity
Constant.
### See also
| | |
| --- | --- |
| [min](min "cpp/numeric/random/extreme value distribution/min")
(C++11) | returns the minimum potentially generated value (public member function) |
cpp std::extreme_value_distribution<RealType>::min std::extreme\_value\_distribution<RealType>::min
================================================
| | | |
| --- | --- | --- |
|
```
result_type min() const;
```
| | (since C++11) |
Returns the minimum value potentially generated by the distribution.
### Parameters
(none).
### Return value
The minimum value potentially generated by the distribution.
### Complexity
Constant.
### See also
| | |
| --- | --- |
| [max](max "cpp/numeric/random/extreme value distribution/max")
(C++11) | returns the maximum potentially generated value (public member function) |
cpp std::extreme_value_distribution<RealType>::extreme_value_distribution std::extreme\_value\_distribution<RealType>::extreme\_value\_distribution
=========================================================================
| | | |
| --- | --- | --- |
|
```
extreme_value_distribution() : extreme_value_distribution(0.0) {}
```
| (1) | (since C++11) |
|
```
explicit extreme_value_distribution( RealType a, RealType b = 1.0 );
```
| (2) | (since C++11) |
|
```
explicit extreme_value_distribution( const param_type& params );
```
| (3) | (since C++11) |
Constructs a new distribution object. (2) uses `a` and `b` as the distribution parameters. (3) uses `params` as the distribution parameters.
### Parameters
| | | |
| --- | --- | --- |
| a | - | the *a* distribution parameter (location) |
| b | - | the *b* distribution parameter (scale) |
| params | - | the distribution parameter set |
### 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::extreme_value_distribution<RealType>::param std::extreme\_value\_distribution<RealType>::param
==================================================
| | | |
| --- | --- | --- |
|
```
param_type param() const;
```
| (1) | (since C++11) |
|
```
void param( const param_type& params );
```
| (2) | (since C++11) |
Manages the associated distribution parameter set.
1) Returns the associated parameter set.
2) Sets the associated parameter set to `params`.
### Parameters
| | | |
| --- | --- | --- |
| params | - | new contents of the associated parameter set |
### Return value
1) The associated parameter set.
2) (none).
### Complexity
Constant.
cpp operator==,!=(std::extreme_value_distribution)
operator==,!=(std::extreme\_value\_distribution)
================================================
| | | |
| --- | --- | --- |
|
```
friend bool operator==( const extreme_value_distribution& lhs,
const extreme_value_distribution& rhs );
```
| (1) | (since C++11) |
|
```
friend bool operator!=( const extreme_value_distribution& lhs,
const extreme_value_distribution& rhs );
```
| (2) | (since C++11) (until C++20) |
Compares two distribution objects. Two distribution objects are equal when parameter values and internal state is the same.
1) Compares two distribution objects for equality.
2) Compares two distribution objects for inequality. These functions are not visible to ordinary [unqualified](../../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../../language/adl "cpp/language/adl") when `std::extreme_value_distribution<ResultType>` is an associated class of the arguments.
| | |
| --- | --- |
| The `!=` operator is [synthesized](../../../language/operators#Relational_operators "cpp/language/operators") from `operator==`. | (since C++20) |
### Parameters
| | | |
| --- | --- | --- |
| lhs, rhs | - | distribution objects to compare |
### Return value
1) `true` if the distribution objects are equal, `false` otherwise.
2) `true` if the distribution objects are not equal, `false` otherwise. ### Complexity
Constant.
### 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 3519](https://cplusplus.github.io/LWG/issue3519) | C++11 | the form of equality operators were unspecified(could be hidden friends or free function templates) | specified to be hidden friends |
cpp operator<<,>>(std::geometric_distribution)
operator<<,>>(std::geometric\_distribution)
===========================================
| | | |
| --- | --- | --- |
|
```
template< class CharT, class Traits >
friend std::basic_ostream<CharT,Traits>&
operator<<( std::basic_ostream<CharT,Traits>& ost,
const geometric_distribution& d );
```
| (1) | (since C++11) |
|
```
template< class CharT, class Traits >
friend std::basic_istream<CharT,Traits>&
operator>>( std::basic_istream<CharT,Traits>& ist,
geometric_distribution& d );
```
| (2) | (since C++11) |
Performs stream input and output operations on pseudo-random number distribution `d`.
1) Writes a textual representation of the distribution parameters and internal state to `ost` as textual representation. The formatting flags and fill character of `ost` are unchanged.
2) Restores the distribution parameters and internal state with data read from `ist`. The formatting flags of `ist` are unchanged. The data must have been written using a stream with the same locale, `CharT` and `Traits` template parameters, otherwise the behavior is undefined. If bad input is encountered, `ist.setstate(std::ios::failbit)` is called, which may throw `[std::ios\_base::failure](../../../io/ios_base/failure "cpp/io/ios base/failure")`. `d` is unchanged in that case. These function templates are not visible to ordinary [unqualified](../../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../../language/adl "cpp/language/adl") when `std::geometric_distribution<ResultType>` is an associated class of the arguments.
### Parameters
| | | |
| --- | --- | --- |
| ost | - | output stream to insert the data to |
| ist | - | input stream to extract the data from |
| d | - | pseudo-random number distribution |
### Return value
1) `ost`
2) `ist`
### Exceptions
1) May throw implementation-defined exceptions.
2) May throw `[std::ios\_base::failure](../../../io/ios_base/failure "cpp/io/ios base/failure")` on bad input. ### 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 3519](https://cplusplus.github.io/LWG/issue3519) | C++11 | the form of insertion and extraction operators were unspecified(could be hidden friends or out-of-class function templates) | specified to be hidden friends |
cpp std::geometric_distribution<IntType>::reset std::geometric\_distribution<IntType>::reset
============================================
| | | |
| --- | --- | --- |
|
```
void reset();
```
| | (since C++11) |
Resets the internal state of the distribution object. After a call to this function, the next call to `operator()` on the distribution object will not be dependent on previous calls to `operator()`.
### Parameters
(none).
### Return value
(none).
### Complexity
Constant.
cpp std::geometric_distribution<IntType>::geometric_distribution std::geometric\_distribution<IntType>::geometric\_distribution
==============================================================
| | | |
| --- | --- | --- |
|
```
geometric_distribution() : geometric_distribution(0.5) {}
```
| (1) | (since C++11) |
|
```
explicit geometric_distribution( double p );
```
| (2) | (since C++11) |
|
```
explicit geometric_distribution( const param_type& params );
```
| (3) | (since C++11) |
Constructs a new distribution object. (2) uses `p` as the distribution parameter. (3) uses `params` as the distribution parameter.
### Parameters
| | | |
| --- | --- | --- |
| p | - | the *p* distribution parameter (probability of a trial generating `true`) |
| params | - | the distribution parameter set |
### Notes
Requires that 0 < p < 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 |
| --- | --- | --- | --- |
| [P0935R0](https://wg21.link/P0935R0) | C++11 | default constructor was explicit | made implicit |
cpp std::geometric_distribution<IntType>::p std::geometric\_distribution<IntType>::p
========================================
| | | |
| --- | --- | --- |
|
```
double p() const;
```
| | (since C++11) |
Returns the p distribution parameter the distribution was constructed with. The parameter defines the probability of a trial generating `true`. The default value is `0.5`.
### Parameters
(none).
### Return value
Floating point value identifying the p distribution parameter.
### See also
| | |
| --- | --- |
| [param](param "cpp/numeric/random/geometric distribution/param")
(C++11) | gets or sets the distribution parameter object (public member function) |
cpp std::geometric_distribution<IntType>::operator() std::geometric\_distribution<IntType>::operator()
=================================================
| | | |
| --- | --- | --- |
|
```
template< class Generator >
result_type operator()( Generator& g );
```
| (1) | (since C++11) |
|
```
template< class Generator >
result_type operator()( Generator& g, const param_type& params );
```
| (2) | (since C++11) |
Generates random numbers that are distributed according to the associated probability function. The entropy is acquired by calling `g.operator()`.
The first version uses the associated parameter set, the second version uses `params`. The associated parameter set is not modified.
### Parameters
| | | |
| --- | --- | --- |
| g | - | an uniform random bit generator object |
| params | - | distribution parameter set to use instead of the associated one |
| Type requirements |
| -`Generator` must meet the requirements of [UniformRandomBitGenerator](../../../named_req/uniformrandombitgenerator "cpp/named req/UniformRandomBitGenerator"). |
### Return value
The generated random number.
### Complexity
Amortized constant number of invocations of `g.operator()`.
cpp std::geometric_distribution<IntType>::max std::geometric\_distribution<IntType>::max
==========================================
| | | |
| --- | --- | --- |
|
```
result_type max() const;
```
| | (since C++11) |
Returns the maximum value potentially generated by the distribution.
### Parameters
(none).
### Return value
The maximum value potentially generated by the distribution.
### Complexity
Constant.
### See also
| | |
| --- | --- |
| [min](min "cpp/numeric/random/geometric distribution/min")
(C++11) | returns the minimum potentially generated value (public member function) |
cpp std::geometric_distribution<IntType>::min std::geometric\_distribution<IntType>::min
==========================================
| | | |
| --- | --- | --- |
|
```
result_type min() const;
```
| | (since C++11) |
Returns the minimum value potentially generated by the distribution.
### Parameters
(none).
### Return value
The minimum value potentially generated by the distribution.
### Complexity
Constant.
### See also
| | |
| --- | --- |
| [max](max "cpp/numeric/random/geometric distribution/max")
(C++11) | returns the maximum potentially generated value (public member function) |
cpp std::geometric_distribution<IntType>::param std::geometric\_distribution<IntType>::param
============================================
| | | |
| --- | --- | --- |
|
```
param_type param() const;
```
| (1) | (since C++11) |
|
```
void param( const param_type& params );
```
| (2) | (since C++11) |
Manages the associated distribution parameter set.
1) Returns the associated parameter set.
2) Sets the associated parameter set to `params`.
### Parameters
| | | |
| --- | --- | --- |
| params | - | new contents of the associated parameter set |
### Return value
1) The associated parameter set.
2) (none).
### Complexity
Constant.
cpp operator==,!=(std::geometric_distribution)
operator==,!=(std::geometric\_distribution)
===========================================
| | | |
| --- | --- | --- |
|
```
friend bool operator==( const geometric_distribution& lhs,
const geometric_distribution& rhs );
```
| (1) | (since C++11) |
|
```
friend bool operator!=( const geometric_distribution& lhs,
const geometric_distribution& rhs );
```
| (2) | (since C++11) (until C++20) |
Compares two distribution objects. Two distribution objects are equal when parameter values and internal state is the same.
1) Compares two distribution objects for equality.
2) Compares two distribution objects for inequality. These functions are not visible to ordinary [unqualified](../../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../../language/adl "cpp/language/adl") when `std::geometric_distribution<ResultType>` is an associated class of the arguments.
| | |
| --- | --- |
| The `!=` operator is [synthesized](../../../language/operators#Relational_operators "cpp/language/operators") from `operator==`. | (since C++20) |
### Parameters
| | | |
| --- | --- | --- |
| lhs, rhs | - | distribution objects to compare |
### Return value
1) `true` if the distribution objects are equal, `false` otherwise.
2) `true` if the distribution objects are not equal, `false` otherwise. ### Complexity
Constant.
### 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 3519](https://cplusplus.github.io/LWG/issue3519) | C++11 | the form of equality operators were unspecified(could be hidden friends or free function templates) | specified to be hidden friends |
cpp operator<<,>>(std::uniform_real_distribution)
operator<<,>>(std::uniform\_real\_distribution)
===============================================
| | | |
| --- | --- | --- |
|
```
template< class CharT, class Traits >
friend std::basic_ostream<CharT,Traits>&
operator<<( std::basic_ostream<CharT,Traits>& ost,
const uniform_real_distribution& d );
```
| (1) | (since C++11) |
|
```
template< class CharT, class Traits >
friend std::basic_istream<CharT,Traits>&
operator>>( std::basic_istream<CharT,Traits>& ist,
uniform_real_distribution& d );
```
| (2) | (since C++11) |
Performs stream input and output operations on pseudo-random number distribution `d`.
1) Writes a textual representation of the distribution parameters and internal state to `ost` as textual representation. The formatting flags and fill character of `ost` are unchanged.
2) Restores the distribution parameters and internal state with data read from `ist`. The formatting flags of `ist` are unchanged. The data must have been written using a stream with the same locale, `CharT` and `Traits` template parameters, otherwise the behavior is undefined. If bad input is encountered, `ist.setstate(std::ios::failbit)` is called, which may throw `[std::ios\_base::failure](../../../io/ios_base/failure "cpp/io/ios base/failure")`. `d` is unchanged in that case. These function templates are not visible to ordinary [unqualified](../../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../../language/adl "cpp/language/adl") when `std::uniform_real_distribution<ResultType>` is an associated class of the arguments.
### Parameters
| | | |
| --- | --- | --- |
| ost | - | output stream to insert the data to |
| ist | - | input stream to extract the data from |
| d | - | pseudo-random number distribution |
### Return value
1) `ost`
2) `ist`
### Exceptions
1) May throw implementation-defined exceptions.
2) May throw `[std::ios\_base::failure](../../../io/ios_base/failure "cpp/io/ios base/failure")` on bad input. ### 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 3519](https://cplusplus.github.io/LWG/issue3519) | C++11 | the form of insertion and extraction operators were unspecified(could be hidden friends or out-of-class function templates) | specified to be hidden friends |
cpp std::uniform_real_distribution<RealType>::reset std::uniform\_real\_distribution<RealType>::reset
=================================================
| | | |
| --- | --- | --- |
|
```
void reset();
```
| | (since C++11) |
Resets the internal state of the distribution object. After a call to this function, the next call to `operator()` on the distribution object will not be dependent on previous calls to `operator()`.
### Parameters
(none).
### Return value
(none).
### Complexity
Constant.
cpp std::uniform_real_distribution<RealType>::uniform_real_distribution std::uniform\_real\_distribution<RealType>::uniform\_real\_distribution
=======================================================================
| | | |
| --- | --- | --- |
|
```
uniform_real_distribution() : uniform_real_distribution(0.0) { }
```
| (1) | (since C++11) |
|
```
explicit uniform_real_distribution( RealType a, RealType b = 1.0 );
```
| (2) | (since C++11) |
|
```
explicit uniform_real_distribution( const param_type& params );
```
| (3) | (since C++11) |
Constructs a new distribution object. (2) uses `a` and `b` as the distribution parameters, (3) uses `params` as the distribution parameters.
### Parameters
| | | |
| --- | --- | --- |
| a | - | the *a* distribution parameter (minimum value) |
| b | - | the *b* distribution parameter (maximum value) |
| params | - | the distribution parameter set |
### Notes
Requires that a โค b and b-a โค std::numeric\_limits<RealType>::max().
If `a == b`, subsequent calls to the [`operator()`](operator() "cpp/numeric/random/uniform real distribution/operator()") overload that does not accept a `param_type` object will cause undefined behavior.
To create a distribution over the closed interval [a,b], `[std::nextafter](http://en.cppreference.com/w/cpp/numeric/math/nextafter)(b, [std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<RealType>::max())` may be used as the second parameter.
### 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 |
| programming_docs |
cpp std::uniform_real_distribution<RealType>::operator() std::uniform\_real\_distribution<RealType>::operator()
======================================================
| | | |
| --- | --- | --- |
|
```
template< class Generator >
result_type operator()( Generator& g );
```
| (1) | (since C++11) |
|
```
template< class Generator >
result_type operator()( Generator& g, const param_type& params );
```
| (2) | (since C++11) |
Generates random numbers that are distributed according to the associated probability function. The entropy is acquired by calling `g.operator()`.
The first version uses the associated parameter set, the second version uses `params`. The associated parameter set is not modified.
### Parameters
| | | |
| --- | --- | --- |
| g | - | an uniform random bit generator object |
| params | - | distribution parameter set to use instead of the associated one |
| Type requirements |
| -`Generator` must meet the requirements of [UniformRandomBitGenerator](../../../named_req/uniformrandombitgenerator "cpp/named req/UniformRandomBitGenerator"). |
### Return value
The generated random number.
### Complexity
Amortized constant number of invocations of `g.operator()`.
cpp std::uniform_real_distribution<RealType>::a, b std::uniform\_real\_distribution<RealType>::a, b
================================================
| | | |
| --- | --- | --- |
|
```
result_type a() const;
```
| (1) | (since C++11) |
|
```
result_type b() const;
```
| (2) | (since C++11) |
Returns the parameters the distribution has been constructed with.
1) Returns the *a* distribution parameter. It defines the minimum possibly generated value. The default value is `0.0`.
2) Returns the *b* distribution parameter. It defines the maximum possibly generated value. The default value is `1.0`
### Parameters
(none).
### Return value
1) The *a* distribution parameter.
2) The *b* distribution parameter. ### See also
| | |
| --- | --- |
| [param](param "cpp/numeric/random/uniform real distribution/param")
(C++11) | gets or sets the distribution parameter object (public member function) |
cpp std::uniform_real_distribution<RealType>::max std::uniform\_real\_distribution<RealType>::max
===============================================
| | | |
| --- | --- | --- |
|
```
result_type max() const;
```
| | (since C++11) |
Returns the maximum value potentially generated by the distribution.
### Parameters
(none).
### Return value
The maximum value potentially generated by the distribution.
### Complexity
Constant.
### See also
| | |
| --- | --- |
| [min](min "cpp/numeric/random/uniform real distribution/min")
(C++11) | returns the minimum potentially generated value (public member function) |
cpp std::uniform_real_distribution<RealType>::min std::uniform\_real\_distribution<RealType>::min
===============================================
| | | |
| --- | --- | --- |
|
```
result_type min() const;
```
| | (since C++11) |
Returns the minimum value potentially generated by the distribution.
### Parameters
(none).
### Return value
The minimum value potentially generated by the distribution.
### Complexity
Constant.
### See also
| | |
| --- | --- |
| [max](max "cpp/numeric/random/uniform real distribution/max")
(C++11) | returns the maximum potentially generated value (public member function) |
cpp std::uniform_real_distribution<RealType>::param std::uniform\_real\_distribution<RealType>::param
=================================================
| | | |
| --- | --- | --- |
|
```
param_type param() const;
```
| (1) | (since C++11) |
|
```
void param( const param_type& params );
```
| (2) | (since C++11) |
Manages the associated distribution parameter set.
1) Returns the associated parameter set.
2) Sets the associated parameter set to `params`.
### Parameters
| | | |
| --- | --- | --- |
| params | - | new contents of the associated parameter set |
### Return value
1) The associated parameter set.
2) (none).
### Complexity
Constant.
cpp operator==,!=(std::uniform_real_distribution)
operator==,!=(std::uniform\_real\_distribution)
===============================================
| | | |
| --- | --- | --- |
|
```
friend bool operator==( const uniform_real_distribution& lhs,
const uniform_real_distribution& rhs );
```
| (1) | (since C++11) |
|
```
friend bool operator!=( const uniform_real_distribution& lhs,
const uniform_real_distribution& rhs );
```
| (2) | (since C++11) (until C++20) |
Compares two distribution objects. Two distribution objects are equal when parameter values and internal state is the same.
1) Compares two distribution objects for equality.
2) Compares two distribution objects for inequality. These functions are not visible to ordinary [unqualified](../../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../../language/adl "cpp/language/adl") when `std::uniform_real_distribution<ResultType>` is an associated class of the arguments.
| | |
| --- | --- |
| The `!=` operator is [synthesized](../../../language/operators#Relational_operators "cpp/language/operators") from `operator==`. | (since C++20) |
### Parameters
| | | |
| --- | --- | --- |
| lhs, rhs | - | distribution objects to compare |
### Return value
1) `true` if the distribution objects are equal, `false` otherwise.
2) `true` if the distribution objects are not equal, `false` otherwise. ### Complexity
Constant.
### 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 3519](https://cplusplus.github.io/LWG/issue3519) | C++11 | the form of equality operators were unspecified(could be hidden friends or free function templates) | specified to be hidden friends |
cpp operator<<,>>(std::exponential_distribution)
operator<<,>>(std::exponential\_distribution)
=============================================
| | | |
| --- | --- | --- |
|
```
template< class CharT, class Traits >
friend std::basic_ostream<CharT,Traits>&
operator<<( std::basic_ostream<CharT,Traits>& ost,
const exponential_distribution& d );
```
| (1) | (since C++11) |
|
```
template< class CharT, class Traits >
friend std::basic_istream<CharT,Traits>&
operator>>( std::basic_istream<CharT,Traits>& ist,
exponential_distribution& d );
```
| (2) | (since C++11) |
Performs stream input and output operations on pseudo-random number distribution `d`.
1) Writes a textual representation of the distribution parameters and internal state to `ost` as textual representation. The formatting flags and fill character of `ost` are unchanged.
2) Restores the distribution parameters and internal state with data read from `ist`. The formatting flags of `ist` are unchanged. The data must have been written using a stream with the same locale, `CharT` and `Traits` template parameters, otherwise the behavior is undefined. If bad input is encountered, `ist.setstate(std::ios::failbit)` is called, which may throw `[std::ios\_base::failure](../../../io/ios_base/failure "cpp/io/ios base/failure")`. `d` is unchanged in that case. These function templates are not visible to ordinary [unqualified](../../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../../language/adl "cpp/language/adl") when `std::exponential_distribution<ResultType>` is an associated class of the arguments.
### Parameters
| | | |
| --- | --- | --- |
| ost | - | output stream to insert the data to |
| ist | - | input stream to extract the data from |
| d | - | pseudo-random number distribution |
### Return value
1) `ost`
2) `ist`
### Exceptions
1) May throw implementation-defined exceptions.
2) May throw `[std::ios\_base::failure](../../../io/ios_base/failure "cpp/io/ios base/failure")` on bad input. ### 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 3519](https://cplusplus.github.io/LWG/issue3519) | C++11 | the form of insertion and extraction operators were unspecified(could be hidden friends or out-of-class function templates) | specified to be hidden friends |
cpp std::exponential_distribution<RealType>::reset std::exponential\_distribution<RealType>::reset
===============================================
| | | |
| --- | --- | --- |
|
```
void reset();
```
| | (since C++11) |
Resets the internal state of the distribution object. After a call to this function, the next call to `[operator()](operator() "cpp/numeric/random/exponential distribution/operator()")` on the distribution object will not be dependent on previous calls to `[operator()](operator() "cpp/numeric/random/exponential distribution/operator()")`.
### Parameters
(none).
### Return value
(none).
### Complexity
Constant.
cpp std::exponential_distribution<RealType>::lambda std::exponential\_distribution<RealType>::lambda
================================================
| | | |
| --- | --- | --- |
|
```
RealType lambda() const;
```
| | (since C++11) |
Returns the ฮป distribution parameter the distribution was constructed with. The parameter defines the rate of events, per unit. The default value is `1.0`.
### Parameters
(none).
### Return value
Floating point value identifying the rate of events per unit.
### See also
| | |
| --- | --- |
| [param](param "cpp/numeric/random/exponential distribution/param")
(C++11) | gets or sets the distribution parameter object (public member function) |
cpp std::exponential_distribution<RealType>::exponential_distribution std::exponential\_distribution<RealType>::exponential\_distribution
===================================================================
| | | |
| --- | --- | --- |
|
```
exponential_distribution() : exponential_distribution(1.0) {}
```
| (1) | (since C++11) |
|
```
explicit exponential_distribution( RealType lambda );
```
| (2) | (since C++11) |
|
```
explicit exponential_distribution( const param_type& params );
```
| (3) | (since C++11) |
Constructs a new distribution object. (2) uses `lambda` as the distribution parameter. (3) uses `params` as the distribution parameter.
### Parameters
| | | |
| --- | --- | --- |
| lambda | - | the *ฮป* distribution parameter (the rate parameter) |
| params | - | the distribution parameter set |
### Notes
Requires that 0 < lambda.
### 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::exponential_distribution<RealType>::operator() std::exponential\_distribution<RealType>::operator()
====================================================
| | | |
| --- | --- | --- |
|
```
template< class Generator >
result_type operator()( Generator& g );
```
| (1) | (since C++11) |
|
```
template< class Generator >
result_type operator()( Generator& g, const param_type& params );
```
| (2) | (since C++11) |
Generates random numbers that are distributed according to the associated probability function. The entropy is acquired by calling `g.operator()`.
The first version uses the associated parameter set, the second version uses `params`. The associated parameter set is not modified.
### Parameters
| | | |
| --- | --- | --- |
| g | - | an uniform random bit generator object |
| params | - | distribution parameter set to use instead of the associated one |
| Type requirements |
| -`Generator` must meet the requirements of [UniformRandomBitGenerator](../../../named_req/uniformrandombitgenerator "cpp/named req/UniformRandomBitGenerator"). |
### Return value
The generated random number.
### Complexity
Amortized constant number of invocations of `g.operator()`.
cpp std::exponential_distribution<RealType>::max std::exponential\_distribution<RealType>::max
=============================================
| | | |
| --- | --- | --- |
|
```
result_type max() const;
```
| | (since C++11) |
Returns the maximum value potentially generated by the distribution.
### Parameters
(none).
### Return value
The maximum value potentially generated by the distribution.
### Complexity
Constant.
### See also
| | |
| --- | --- |
| [min](min "cpp/numeric/random/exponential distribution/min")
(C++11) | returns the minimum potentially generated value (public member function) |
cpp std::exponential_distribution<RealType>::min std::exponential\_distribution<RealType>::min
=============================================
| | | |
| --- | --- | --- |
|
```
result_type min() const;
```
| | (since C++11) |
Returns the minimum value potentially generated by the distribution.
### Parameters
(none).
### Return value
The minimum value potentially generated by the distribution.
### Complexity
Constant.
### See also
| | |
| --- | --- |
| [max](max "cpp/numeric/random/exponential distribution/max")
(C++11) | returns the maximum potentially generated value (public member function) |
cpp std::exponential_distribution<RealType>::param std::exponential\_distribution<RealType>::param
===============================================
| | | |
| --- | --- | --- |
|
```
param_type param() const;
```
| (1) | (since C++11) |
|
```
void param( const param_type& params );
```
| (2) | (since C++11) |
Manages the associated distribution parameter set.
1) Returns the associated parameter set.
2) Sets the associated parameter set to `params`.
### Parameters
| | | |
| --- | --- | --- |
| params | - | new contents of the associated parameter set |
### Return value
1) The associated parameter set.
2) (none).
### Complexity
Constant.
cpp operator==,!=(std::exponential_distribution)
operator==,!=(std::exponential\_distribution)
=============================================
| | | |
| --- | --- | --- |
|
```
friend bool operator==( const exponential_distribution& lhs,
const exponential_distribution& rhs );
```
| (1) | (since C++11) |
|
```
friend bool operator!=( const exponential_distribution& lhs,
const exponential_distribution& rhs );
```
| (2) | (since C++11) (until C++20) |
Compares two distribution objects. Two distribution objects are equal when parameter values and internal state is the same.
1) Compares two distribution objects for equality.
2) Compares two distribution objects for inequality. These functions are not visible to ordinary [unqualified](../../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../../language/adl "cpp/language/adl") when `std::exponential_distribution<ResultType>` is an associated class of the arguments.
| | |
| --- | --- |
| The `!=` operator is [synthesized](../../../language/operators#Relational_operators "cpp/language/operators") from `operator==`. | (since C++20) |
### Parameters
| | | |
| --- | --- | --- |
| lhs, rhs | - | distribution objects to compare |
### Return value
1) `true` if the distribution objects are equal, `false` otherwise.
2) `true` if the distribution objects are not equal, `false` otherwise. ### Complexity
Constant.
### 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 3519](https://cplusplus.github.io/LWG/issue3519) | C++11 | the form of equality operators were unspecified(could be hidden friends or free function templates) | specified to be hidden friends |
cpp operator<<,>>(std::discrete_distribution)
operator<<,>>(std::discrete\_distribution)
==========================================
| | | |
| --- | --- | --- |
|
```
template< class CharT, class Traits >
friend std::basic_ostream<CharT,Traits>&
operator<<( std::basic_ostream<CharT,Traits>& ost,
const discrete_distribution& d );
```
| (1) | (since C++11) |
|
```
template< class CharT, class Traits >
friend std::basic_istream<CharT,Traits>&
operator>>( std::basic_istream<CharT,Traits>& ist,
discrete_distribution& d );
```
| (2) | (since C++11) |
Performs stream input and output operations on pseudo-random number distribution `d`.
1) Writes a textual representation of the distribution parameters and internal state to `ost` as textual representation. The formatting flags and fill character of `ost` are unchanged.
2) Restores the distribution parameters and internal state with data read from `ist`. The formatting flags of `ist` are unchanged. The data must have been written using a stream with the same locale, `CharT` and `Traits` template parameters, otherwise the behavior is undefined. If bad input is encountered, `ist.setstate(std::ios::failbit)` is called, which may throw `[std::ios\_base::failure](../../../io/ios_base/failure "cpp/io/ios base/failure")`. `d` is unchanged in that case. These function templates are not visible to ordinary [unqualified](../../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../../language/adl "cpp/language/adl") when `std::discrete_distribution<ResultType>` is an associated class of the arguments.
### Parameters
| | | |
| --- | --- | --- |
| ost | - | output stream to insert the data to |
| ist | - | input stream to extract the data from |
| d | - | pseudo-random number distribution |
### Return value
1) `ost`
2) `ist`
### Exceptions
1) May throw implementation-defined exceptions.
2) May throw `[std::ios\_base::failure](../../../io/ios_base/failure "cpp/io/ios base/failure")` on bad input. ### 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 3519](https://cplusplus.github.io/LWG/issue3519) | C++11 | the form of insertion and extraction operators were unspecified(could be hidden friends or out-of-class function templates) | specified to be hidden friends |
cpp std::discrete_distribution<IntType>::reset std::discrete\_distribution<IntType>::reset
===========================================
| | | |
| --- | --- | --- |
|
```
void reset();
```
| | (since C++11) |
Resets the internal state of the distribution object. After a call to this function, the next call to `[operator()](operator() "cpp/numeric/random/discrete distribution/operator()")` on the distribution object will not be dependent on previous calls to `[operator()](operator() "cpp/numeric/random/discrete distribution/operator()")`.
### Parameters
(none).
### Return value
(none).
### Complexity
Constant.
| programming_docs |
cpp std::discrete_distribution<IntType>::operator() std::discrete\_distribution<IntType>::operator()
================================================
| | | |
| --- | --- | --- |
|
```
template< class Generator >
result_type operator()( Generator& g );
```
| (1) | (since C++11) |
|
```
template< class Generator >
result_type operator()( Generator& g, const param_type& params );
```
| (2) | (since C++11) |
Generates random numbers that are distributed according to the associated probability function. The entropy is acquired by calling `g.operator()`.
The first version uses the associated parameter set, the second version uses `params`. The associated parameter set is not modified.
### Parameters
| | | |
| --- | --- | --- |
| g | - | an uniform random bit generator object |
| params | - | distribution parameter set to use instead of the associated one |
| Type requirements |
| -`Generator` must meet the requirements of [UniformRandomBitGenerator](../../../named_req/uniformrandombitgenerator "cpp/named req/UniformRandomBitGenerator"). |
### Return value
The generated random number.
### Complexity
Amortized constant number of invocations of `g.operator()`.
cpp std::discrete_distribution<IntType>::probabilities std::discrete\_distribution<IntType>::probabilities
===================================================
| | | |
| --- | --- | --- |
|
```
std::vector<double> probabilities() const;
```
| | (since C++11) |
Obtains a `[std::vector](http://en.cppreference.com/w/cpp/container/vector)<double>` containing the individual probabilities of each integer that is generated by this distribution.
### Parameters
(none).
### Return value
An object of type `[std::vector](http://en.cppreference.com/w/cpp/container/vector)<double>`
### Example
```
#include <iostream>
#include <vector>
#include <random>
int main()
{
std::discrete_distribution<> d({40, 10, 10, 40});
std::vector<double> p = d.probabilities();
for(auto n : p)
std::cout << n << ' ';
std::cout << '\n';
}
```
Output:
```
0.4 0.1 0.1 0.4
```
cpp std::discrete_distribution<IntType>::max std::discrete\_distribution<IntType>::max
=========================================
| | | |
| --- | --- | --- |
|
```
result_type max() const;
```
| | (since C++11) |
Returns the maximum value potentially generated by the distribution.
### Parameters
(none).
### Return value
The maximum value potentially generated by the distribution.
### Complexity
Constant.
### See also
| | |
| --- | --- |
| [min](min "cpp/numeric/random/discrete distribution/min")
(C++11) | returns the minimum potentially generated value (public member function) |
cpp std::discrete_distribution<IntType>::min std::discrete\_distribution<IntType>::min
=========================================
| | | |
| --- | --- | --- |
|
```
result_type min() const;
```
| | (since C++11) |
Returns the minimum value potentially generated by the distribution.
### Parameters
(none).
### Return value
The minimum value potentially generated by the distribution.
### Complexity
Constant.
### See also
| | |
| --- | --- |
| [max](max "cpp/numeric/random/discrete distribution/max")
(C++11) | returns the maximum potentially generated value (public member function) |
cpp std::discrete_distribution<IntType>::param std::discrete\_distribution<IntType>::param
===========================================
| | | |
| --- | --- | --- |
|
```
param_type param() const;
```
| (1) | (since C++11) |
|
```
void param( const param_type& params );
```
| (2) | (since C++11) |
Manages the associated distribution parameter set.
1) Returns the associated parameter set.
2) Sets the associated parameter set to `params`.
### Parameters
| | | |
| --- | --- | --- |
| params | - | new contents of the associated parameter set |
### Return value
1) The associated parameter set.
2) (none).
### Complexity
Constant.
cpp std::discrete_distribution<IntType>::discrete_distribution std::discrete\_distribution<IntType>::discrete\_distribution
============================================================
| | | |
| --- | --- | --- |
|
```
discrete_distribution();
```
| (1) | (since C++11) |
|
```
template< class InputIt >
discrete_distribution( InputIt first, InputIt last );
```
| (2) | (since C++11) |
|
```
discrete_distribution( std::initializer_list<double> weights );
```
| (3) | (since C++11) |
|
```
template< class UnaryOperation >
discrete_distribution( std::size_t count, double xmin, double xmax,
UnaryOperation unary_op );
```
| (4) | (since C++11) |
|
```
explicit discrete_distribution( const param_type& params );
```
| (5) | (since C++11) |
Constructs a new distribution object.
1) Default constructor. Constructs the distribution with a single weight p={1}. This distribution will always generate `โ0โ`.
2) Constructs the distribution with weights in the range `[first, last)`. If `first == last`, the effects are the same as of the default constructor.
3) Constructs the distribution with weights in `weights`. Effectively calls `discrete_distribution(weights.begin(), weights.end())`. 4) Constructs the distribution with `count` weights that are generated using function `unary_op`. Each of the weights is equal to w.
i = unary\_op(xmin + ฮด(i + 0.5)), where ฮด = (xmax โ xmin)/count and i โ {0, ..., countโ1}. `xmin` and `xmax` must be such that ฮด > 0. If `count == 0` the effects are the same as of the default constructor. 5) Constructs the distribution with `params` as the distribution parameters.
### Parameters
| | | |
| --- | --- | --- |
| first, last | - | the range of elements defining the numbers to use as weights. The type of the elements referred by `InputIterator` must be convertible to `double` |
| weights | - | initializer list containing the weights |
| unary\_op | - | unary operation function object that will be applied. The signature of the function should be equivalent to the following:
`Ret fun(const Type &a);`
The signature does not need to have `const &`. The type `Type` must be such that an object of type `double` can be dereferenced and then implicitly converted to `Type`. The type `Ret` must be such that an object of type `double` can be dereferenced and assigned a value of type `Ret`. โ |
| params | - | the distribution parameter set |
| Type requirements |
| -`InputIt` must meet the requirements of [LegacyInputIterator](../../../named_req/inputiterator "cpp/named req/InputIterator"). |
cpp operator==,!=(std::discrete_distribution)
operator==,!=(std::discrete\_distribution)
==========================================
| | | |
| --- | --- | --- |
|
```
friend bool operator==( const discrete_distribution& lhs,
const discrete_distribution& rhs );
```
| (1) | (since C++11) |
|
```
friend bool operator!=( const discrete_distribution& lhs,
const discrete_distribution& rhs );
```
| (2) | (since C++11) (until C++20) |
Compares two distribution objects. Two distribution objects are equal when parameter values and internal state is the same.
1) Compares two distribution objects for equality.
2) Compares two distribution objects for inequality. These functions are not visible to ordinary [unqualified](../../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../../language/adl "cpp/language/adl") when `std::discrete_distribution<ResultType>` is an associated class of the arguments.
| | |
| --- | --- |
| The `!=` operator is [synthesized](../../../language/operators#Relational_operators "cpp/language/operators") from `operator==`. | (since C++20) |
### Parameters
| | | |
| --- | --- | --- |
| lhs, rhs | - | distribution objects to compare |
### Return value
1) `true` if the distribution objects are equal, `false` otherwise.
2) `true` if the distribution objects are not equal, `false` otherwise. ### Complexity
Constant.
### 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 3519](https://cplusplus.github.io/LWG/issue3519) | C++11 | the form of equality operators were unspecified(could be hidden friends or free function templates) | specified to be hidden friends |
cpp operator<<,>>(std::mersenne_twister_engine)
operator<<,>>(std::mersenne\_twister\_engine)
=============================================
| | | |
| --- | --- | --- |
|
```
template< class CharT, class Traits >
friend std::basic_ostream<CharT,Traits>&
operator<<( std::basic_ostream<CharT,Traits>& ost,
const mersenne_twister_engine& e );
```
| (1) | (since C++11) |
|
```
template< class CharT, class Traits >
friend std::basic_istream<CharT,Traits>&
operator>>( std::basic_istream<CharT,Traits>& ist,
mersenne_twister_engine& e );
```
| (2) | (since C++11) |
1) Serializes the internal state of the pseudo-random number engine `e` as a sequence of decimal numbers separated by one or more spaces, and inserts it to the stream `ost`. The fill character and the formatting flags of the stream are ignored and unaffected.
2) Restores the internal state of the pseudo-random number engine `e` from the serialized representation, which was created by an earlier call to `operator<<` using a stream with the same imbued locale and the same `CharT` and `Traits`. If the input cannot be deserialized, `e` is left unchanged and `failbit` is raised on `ist`. These function templates are not visible to ordinary [unqualified](../../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../../language/adl "cpp/language/adl") when `std::mersenne_twister_engine<UIntType,w,n,m,r,a,u,d,s,b,t,c,l,f>` is an associated class of the arguments.
If a textual representation is written using `os << x` and that representation is restored into the same or a different object `y` of the same type using `is >> y`, then `x==y`.
The textual representation is written with `os.fmtflags` set to `ios_base::dec`|`ios_base::left` and the fill character set to the space character. The textual representation of the engine's internal state is a set of decimal numbers separated by spaces.
### Parameters
| | | |
| --- | --- | --- |
| ost | - | output stream to insert the data to |
| ist | - | input stream to extract the data from |
| e | - | pseudo-random number engine |
### Return value
1) `ost`
2) `ist`
### Complexity
### Exceptions
1) May throw implementation-defined exceptions.
2) May throw `[std::ios\_base::failure](../../../io/ios_base/failure "cpp/io/ios base/failure")` when setting `failbit`. ### 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 3519](https://cplusplus.github.io/LWG/issue3519) | C++11 | the form of insertion and extraction operators were unspecified | specified to be hidden friends |
cpp std::mersenne_twister_engine<UIntType,w,n,m,r,a,u,d,s,b,t,c,l,f>::seed std::mersenne\_twister\_engine<UIntType,w,n,m,r,a,u,d,s,b,t,c,l,f>::seed
========================================================================
| | | |
| --- | --- | --- |
|
```
void seed( result_type value = default_seed );
```
| (1) | (since C++11) |
|
```
template< class Sseq >
void seed( Sseq& seq );
```
| (2) | (since C++11) |
Reinitializes the internal state of the random-number engine using new seed value.
### Parameters
| | | |
| --- | --- | --- |
| value | - | seed value to use in the initialization of the internal state |
| seq | - | seed sequence to use in the initialization of the internal state |
### Exceptions
Throws nothing.
### Complexity
### Example
```
#include <iostream>
#include <random>
int main()
{
std::mt19937 gen;
// Seed the engine with an unsigned int
gen.seed(1);
std::cout << "after seed by 1: " << gen() << '\n';
// Seed the engine with two unsigned ints
std::seed_seq sseq{1, 2};
gen.seed(sseq);
std::cout << "after seed by {1,2}: " << gen() << '\n';
}
```
Possible output:
```
after seed by 1: 1791095845
after seed by {1,2}: 3127717181
```
cpp std::mersenne_twister_engine<UIntType,w,n,m,r,a,u,d,s,b,t,c,l,f>::mersenne_twister_engine std::mersenne\_twister\_engine<UIntType,w,n,m,r,a,u,d,s,b,t,c,l,f>::mersenne\_twister\_engine
=============================================================================================
| | | |
| --- | --- | --- |
|
```
mersenne_twister_engine() : mersenne_twister_engine(default_seed) {}
```
| (1) | (since C++11) |
|
```
explicit mersenne_twister_engine( result_type value );
```
| (2) | (since C++11) |
|
```
template< class Sseq >
explicit mersenne_twister_engine( Sseq& s );
```
| (3) | (since C++11) |
|
```
mersenne_twister_engine( const mersenne_twister_engine& );
```
| (4) | (since C++11) (implicitly declared) |
Constructs the pseudo-random number engine.
1) Default constructor. Seeds the engine with `default_seed`.
2) Constructs the engine and initializes the state (`n` values X
i of type `result_type`) as follows: value mod 2w
is used to initialize X
0 and the rest are initialized iteratively, for i=1-n,...,-1, each X
i is initialized to [fยท(X
i-1xor(X
i-1rshift(w-2)))+i mod n] mod 2w
3) Constructs the engine and initializes the state by calling `s.generate(a, a+n*k)` where a is an array of length n\*k and k is ceil(w/32) and then, iteratively for i=-n,...,-1, setting each element of the engine state X
i to (ฮฃk-1
j=0a
k(i+n)+j}ยท232j
) mod 2w
, and finally if the most significant w-r bits of X
0 are zero, and if all other X
i are zero, replacing X
0 with 2w-1
. Note: initialization requirements are based on the 2002 version of Mersenne Twister, [mt19937ar.c](http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/MT2002/CODES/mt19937ar.c).
The overload (3) only participates in overload resolution if `Sseq` qualifies as a [SeedSequence](../../../named_req/seedsequence "cpp/named req/SeedSequence"). In particular, it is excluded from the set of candidate functions if `Sseq` is convertible to `result_type`.
### Parameters
| | | |
| --- | --- | --- |
| value | - | seed value to use in the initialization of the internal state |
| s | - | seed sequence to use in the initialization of the internal state |
### Complexity
linear in `n` (the state size).
### 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 |
### See also
| | |
| --- | --- |
| [seed](seed "cpp/numeric/random/mersenne twister engine/seed")
(C++11) | sets the current state of the engine (public member function) |
cpp std::mersenne_twister_engine<UIntType,w,n,m,r,a,u,d,s,b,t,c,l,f>::operator() std::mersenne\_twister\_engine<UIntType,w,n,m,r,a,u,d,s,b,t,c,l,f>::operator()
==============================================================================
| | | |
| --- | --- | --- |
|
```
result_type operator()();
```
| | (since C++11) |
Generates a pseudo-random value. The state of the engine is advanced by one position.
### Parameters
(none).
### Return value
A pseudo-random number in [`min()`, `max()`].
### Complexity
Amortized constant.
### See also
| | |
| --- | --- |
| [discard](discard "cpp/numeric/random/mersenne twister engine/discard")
(C++11) | advances the engine's state by a specified amount (public member function) |
cpp std::mersenne_twister_engine<UIntType,w,n,m,r,a,u,d,s,b,t,c,l,f>::max std::mersenne\_twister\_engine<UIntType,w,n,m,r,a,u,d,s,b,t,c,l,f>::max
=======================================================================
| | | |
| --- | --- | --- |
|
```
static constexpr result_type max();
```
| | (since C++11) |
Returns the maximum value potentially generated by the random-number engine. This value is equal to 2w
- 1, where `w` is the template parameter also accessible as static member `word_size`.
### Parameters
(none).
### Return value
The maximum potentially generated value.
### Complexity
Constant.
### See also
| | |
| --- | --- |
| [min](min "cpp/numeric/random/mersenne twister engine/min")
[static] (C++11) | gets the smallest possible value in the output range (public static member function) |
cpp std::mersenne_twister_engine<UIntType,w,n,m,r,a,u,d,s,b,t,c,l,f>::min std::mersenne\_twister\_engine<UIntType,w,n,m,r,a,u,d,s,b,t,c,l,f>::min
=======================================================================
| | | |
| --- | --- | --- |
|
```
static constexpr result_type min();
```
| | (since C++11) |
Returns the minimum value potentially generated by the random-number engine. This value is equal to `0u`.
### Parameters
(none).
### Return value
The minimum potentially generated value.
### Complexity
Constant.
### See also
| | |
| --- | --- |
| [max](max "cpp/numeric/random/mersenne twister engine/max")
[static] (C++11) | gets the largest possible value in the output range (public static member function) |
cpp operator==,!=(std::mersenne_twister_engine)
operator==,!=(std::mersenne\_twister\_engine)
=============================================
| | | |
| --- | --- | --- |
|
```
friend bool operator==( const mersenne_twister_engine& lhs,
const mersenne_twister_engine& rhs );
```
| (1) | (since C++11) |
|
```
friend bool operator!=( const mersenne_twister_engine& lhs,
const mersenne_twister_engine& rhs );
```
| (2) | (since C++11) (until C++20) |
Compares two pseudo-random number engines. Two engines are equal, if their internal states are equivalent, that is, if they would generate equivalent values for any number of calls of `operator()`.
These functions are not visible to ordinary [unqualified](../../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../../language/adl "cpp/language/adl") when `std::mersenne_twister_engine<UIntType,w,n,m,r,a,u,d,s,b,t,c,l,f>` is an associated class of the arguments.
| | |
| --- | --- |
| The `!=` operator is [synthesized](../../../language/operators#Relational_operators "cpp/language/operators") from `operator==`. | (since C++20) |
### Parameters
| | | |
| --- | --- | --- |
| lhs, rhs | - | engines to compare |
### Return value
1) `true` if the engines are equivalent, `false` otherwise.
2) `true` if the engines are not equivalent, `false` otherwise. ### Exceptions
Throws nothing.
### 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 3519](https://cplusplus.github.io/LWG/issue3519) | C++11 | the form of equality operators were unspecified | specified to be hidden friends |
| programming_docs |
cpp std::mersenne_twister_engine<UIntType,w,n,m,r,a,u,d,s,b,t,c,l,f>::discard std::mersenne\_twister\_engine<UIntType,w,n,m,r,a,u,d,s,b,t,c,l,f>::discard
===========================================================================
| | | |
| --- | --- | --- |
|
```
void discard( unsigned long long z );
```
| | (since C++11) |
Advances the internal state by `z` times. Equivalent to calling `[operator()](operator() "cpp/numeric/random/mersenne twister engine/operator()")` `z` times and discarding the result.
### Parameters
| | | |
| --- | --- | --- |
| z | - | integer value specifying the number of times to advance the state by |
### Return value
(none).
### Complexity
### Notes
For some engines, "fast jump" algorithms are known, which advance the state by many steps (order of millions) without calculating intermediate state transitions, although not necessarily in constant time.
### See also
| | |
| --- | --- |
| [operator()](operator() "cpp/numeric/random/mersenne twister engine/operator()")
(C++11) | advances the engine's state and returns the generated value (public member function) |
cpp operator<<,>>(std::uniform_int_distribution)
operator<<,>>(std::uniform\_int\_distribution)
==============================================
| | | |
| --- | --- | --- |
|
```
template< class CharT, class Traits >
friend std::basic_ostream<CharT,Traits>&
operator<<( std::basic_ostream<CharT,Traits>& ost,
const uniform_int_distribution& d );
```
| (1) | (since C++11) |
|
```
template< class CharT, class Traits >
friend std::basic_istream<CharT,Traits>&
operator>>( std::basic_istream<CharT,Traits>& ist,
uniform_int_distribution& d );
```
| (2) | (since C++11) |
Performs stream input and output operations on pseudo-random number distribution `d`.
1) Writes a textual representation of the distribution parameters and internal state to `ost` as textual representation. The formatting flags and fill character of `ost` are unchanged.
2) Restores the distribution parameters and internal state with data read from `ist`. The formatting flags of `ist` are unchanged. The data must have been written using a stream with the same locale, `CharT` and `Traits` template parameters, otherwise the behavior is undefined. If bad input is encountered, `ist.setstate(std::ios::failbit)` is called, which may throw `[std::ios\_base::failure](../../../io/ios_base/failure "cpp/io/ios base/failure")`. `d` is unchanged in that case. These function templates are not visible to ordinary [unqualified](../../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../../language/adl "cpp/language/adl") when `std::uniform_int_distribution<ResultType>` is an associated class of the arguments.
### Parameters
| | | |
| --- | --- | --- |
| ost | - | output stream to insert the data to |
| ist | - | input stream to extract the data from |
| d | - | pseudo-random number distribution |
### Return value
1) `ost`
2) `ist`
### Exceptions
1) May throw implementation-defined exceptions.
2) May throw `[std::ios\_base::failure](../../../io/ios_base/failure "cpp/io/ios base/failure")` on bad input. ### 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 3519](https://cplusplus.github.io/LWG/issue3519) | C++11 | the form of insertion and extraction operators were unspecified(could be hidden friends or out-of-class function templates) | specified to be hidden friends |
cpp std::uniform_int_distribution<IntType>::reset std::uniform\_int\_distribution<IntType>::reset
===============================================
| | | |
| --- | --- | --- |
|
```
void reset();
```
| | (since C++11) |
Resets the internal state of the distribution object. After a call to this function, the next call to `[operator()](operator() "cpp/numeric/random/uniform int distribution/operator()")` on the distribution object will not be dependent on previous calls to `[operator()](operator() "cpp/numeric/random/uniform int distribution/operator()")`.
### Parameters
(none).
### Return value
(none).
### Complexity
Constant.
cpp std::uniform_int_distribution<IntType>::uniform_int_distribution std::uniform\_int\_distribution<IntType>::uniform\_int\_distribution
====================================================================
| | | |
| --- | --- | --- |
|
```
uniform_int_distribution() : uniform_int_distribution(0) { }
```
| (1) | (since C++11) |
|
```
explicit uniform_int_distribution( IntType a,
IntType b = std::numeric_limits<IntType>::max() );
```
| (2) | (since C++11) |
|
```
explicit uniform_int_distribution( const param_type& params );
```
| (3) | (since C++11) |
Constructs new distribution object. (2) uses `a` and `b` as the distribution parameters, (3) uses `params` as the distribution parameters.
The behavior is undefined if `a>b`.
### Parameters
| | | |
| --- | --- | --- |
| a | - | the *a* distribution parameter (minimum value) |
| b | - | the *b* distribution parameter (maximum value) |
| params | - | the distribution parameter set |
### 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::uniform_int_distribution<IntType>::operator() std::uniform\_int\_distribution<IntType>::operator()
====================================================
| | | |
| --- | --- | --- |
|
```
template< class Generator >
result_type operator()( Generator& g );
```
| (1) | (since C++11) |
|
```
template< class Generator >
result_type operator()( Generator& g, const param_type& params );
```
| (2) | (since C++11) |
Generates random numbers that are distributed according to the associated probability function. The entropy is acquired by calling `g.operator()`.
The first version uses the associated parameter set, the second version uses `params`. The associated parameter set is not modified.
### Parameters
| | | |
| --- | --- | --- |
| g | - | an uniform random bit generator object |
| params | - | distribution parameter set to use instead of the associated one |
| Type requirements |
| -`Generator` must meet the requirements of [UniformRandomBitGenerator](../../../named_req/uniformrandombitgenerator "cpp/named req/UniformRandomBitGenerator"). |
### Return value
The generated random number.
### Complexity
Amortized constant number of invocations of `g.operator()`.
cpp std::uniform_int_distribution<IntType>::a, b std::uniform\_int\_distribution<IntType>::a, b
==============================================
| | | |
| --- | --- | --- |
|
```
result_type a() const;
```
| (1) | (since C++11) |
|
```
result_type b() const;
```
| (2) | (since C++11) |
Returns the parameters the distribution has been constructed with.
1) Returns the *a* distribution parameter. It defines the minimum possibly generated value. The default value is `โ0โ`.
2) Returns the *b* distribution parameter. It defines the maximum possibly generated value. The default value is `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<IntType>::max()`
### Parameters
(none).
### Return value
1) The *a* distribution parameter.
2) The *b* distribution parameter. ### See also
| | |
| --- | --- |
| [param](param "cpp/numeric/random/uniform int distribution/param")
(C++11) | gets or sets the distribution parameter object (public member function) |
cpp std::uniform_int_distribution<IntType>::max std::uniform\_int\_distribution<IntType>::max
=============================================
| | | |
| --- | --- | --- |
|
```
result_type max() const;
```
| | (since C++11) |
Returns the maximum value potentially generated by the distribution.
### Parameters
(none).
### Return value
The maximum value potentially generated by the distribution.
### Complexity
Constant.
### See also
| | |
| --- | --- |
| [min](min "cpp/numeric/random/uniform int distribution/min")
(C++11) | returns the minimum potentially generated value (public member function) |
cpp std::uniform_int_distribution<IntType>::min std::uniform\_int\_distribution<IntType>::min
=============================================
| | | |
| --- | --- | --- |
|
```
result_type min() const;
```
| | (since C++11) |
Returns the minimum value potentially generated by the distribution.
### Parameters
(none).
### Return value
The minimum value potentially generated by the distribution.
### Complexity
Constant.
### See also
| | |
| --- | --- |
| [max](max "cpp/numeric/random/uniform int distribution/max")
(C++11) | returns the maximum potentially generated value (public member function) |
cpp std::uniform_int_distribution<IntType>::param std::uniform\_int\_distribution<IntType>::param
===============================================
| | | |
| --- | --- | --- |
|
```
param_type param() const;
```
| (1) | (since C++11) |
|
```
void param( const param_type& params );
```
| (2) | (since C++11) |
Manages the associated distribution parameter set.
1) Returns the associated parameter set.
2) Sets the associated parameter set to `params`.
### Parameters
| | | |
| --- | --- | --- |
| params | - | new contents of the associated parameter set |
### Return value
1) The associated parameter set.
2) (none).
### Complexity
Constant.
cpp operator==,!=(std::uniform_int_distribution)
operator==,!=(std::uniform\_int\_distribution)
==============================================
| | | |
| --- | --- | --- |
|
```
friend bool operator==( const uniform_int_distribution& lhs,
const uniform_int_distribution& rhs );
```
| (1) | (since C++11) |
|
```
friend bool operator!=( const uniform_int_distribution& lhs,
const uniform_int_distribution& rhs );
```
| (2) | (since C++11) (until C++20) |
Compares two distribution objects. Two distribution objects are equal when parameter values and internal state is the same.
1) Compares two distribution objects for equality.
2) Compares two distribution objects for inequality. These functions are not visible to ordinary [unqualified](../../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../../language/adl "cpp/language/adl") when `std::uniform_int_distribution<ResultType>` is an associated class of the arguments.
| | |
| --- | --- |
| The `!=` operator is [synthesized](../../../language/operators#Relational_operators "cpp/language/operators") from `operator==`. | (since C++20) |
### Parameters
| | | |
| --- | --- | --- |
| lhs, rhs | - | distribution objects to compare |
### Return value
1) `true` if the distribution objects are equal, `false` otherwise.
2) `true` if the distribution objects are not equal, `false` otherwise. ### Complexity
Constant.
### 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 3519](https://cplusplus.github.io/LWG/issue3519) | C++11 | the form of equality operators were unspecified(could be hidden friends or free function templates) | specified to be hidden friends |
cpp operator<<,>>(std::linear_congruential_engine)
operator<<,>>(std::linear\_congruential\_engine)
================================================
| | | |
| --- | --- | --- |
|
```
template< class CharT, class Traits >
friend std::basic_ostream<CharT,Traits>&
operator<<( std::basic_ostream<CharT,Traits>& ost,
const linear_congruential_engine& e );
```
| (1) | (since C++11) |
|
```
template< class CharT, class Traits >
friend std::basic_istream<CharT,Traits>&
operator>>( std::basic_istream<CharT,Traits>& ist,
linear_congruential_engine& e );
```
| (2) | (since C++11) |
1) Serializes the internal state of the pseudo-random number engine `e` as a sequence of decimal numbers separated by one or more spaces, and inserts it to the stream `ost`. The fill character and the formatting flags of the stream are ignored and unaffected.
2) Restores the internal state of the pseudo-random number engine `e` from the serialized representation, which was created by an earlier call to `operator<<` using a stream with the same imbued locale and the same `CharT` and `Traits`. If the input cannot be deserialized, `e` is left unchanged and `failbit` is raised on `ist`. These function templates are not visible to ordinary [unqualified](../../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../../language/adl "cpp/language/adl") when `std::linear_congruential_engine<UIntType,a,c,m>` is an associated class of the arguments.
If a textual representation is written using `os << x` and that representation is restored into the same or a different object `y` of the same type using `is >> y`, then `x==y`.
The textual representation is written with `os.fmtflags` set to `ios_base::dec`|`ios_base::left` and the fill character set to the space character. The textual representation of the engine's internal state is a set of decimal numbers separated by spaces.
### Parameters
| | | |
| --- | --- | --- |
| ost | - | output stream to insert the data to |
| ist | - | input stream to extract the data from |
| e | - | pseudo-random number engine |
### Return value
1) `ost`
2) `ist`
### Complexity
### Exceptions
1) May throw implementation-defined exceptions.
2) May throw `[std::ios\_base::failure](../../../io/ios_base/failure "cpp/io/ios base/failure")` when setting `failbit`. ### 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 3519](https://cplusplus.github.io/LWG/issue3519) | C++11 | the form of insertion and extraction operators were unspecified | specified to be hidden friends |
cpp std::linear_congruential_engine<UIntType,a,c,m>::seed std::linear\_congruential\_engine<UIntType,a,c,m>::seed
=======================================================
| | | |
| --- | --- | --- |
|
```
void seed( result_type value = default_seed );
```
| (1) | (since C++11) |
|
```
template< class Sseq >
void seed( Sseq& seq );
```
| (2) | (since C++11) |
Reinitializes the internal state of the random-number engine using new seed value.
### Parameters
| | | |
| --- | --- | --- |
| value | - | seed value to use in the initialization of the internal state |
| seq | - | seed sequence to use in the initialization of the internal state |
### Exceptions
Throws nothing.
### Complexity
cpp std::linear_congruential_engine<UIntType,a,c,m>::operator() std::linear\_congruential\_engine<UIntType,a,c,m>::operator()
=============================================================
| | | |
| --- | --- | --- |
|
```
result_type operator()();
```
| | (since C++11) |
Generates a pseudo-random value. The state of the engine is advanced by one position.
### Parameters
(none).
### Return value
A pseudo-random number in [`min()`, `max()`].
### Complexity
Amortized constant.
### See also
| | |
| --- | --- |
| [discard](discard "cpp/numeric/random/linear congruential engine/discard")
(C++11) | advances the engine's state by a specified amount (public member function) |
cpp std::linear_congruential_engine<UIntType,a,c,m>::max std::linear\_congruential\_engine<UIntType,a,c,m>::max
======================================================
| | | |
| --- | --- | --- |
|
```
static constexpr result_type max();
```
| | (since C++11) |
Returns the maximum value potentially generated by the random-number engine. This value is one less than `modulus`.
### Parameters
(none).
### Return value
The maximum potentially generated value.
### Complexity
Constant.
### See also
| | |
| --- | --- |
| [min](min "cpp/numeric/random/linear congruential engine/min")
[static] (C++11) | gets the smallest possible value in the output range (public static member function) |
cpp std::linear_congruential_engine<UIntType,a,c,m>::min std::linear\_congruential\_engine<UIntType,a,c,m>::min
======================================================
| | | |
| --- | --- | --- |
|
```
static constexpr result_type min();
```
| | (since C++11) |
Returns the minimum value potentially generated by the random-number engine. This value is equal to `1u` if `increment` is `0u`, and is equal to `0u` otherwise.
### Parameters
(none).
### Return value
The minimum potentially generated value.
### Complexity
Constant.
### See also
| | |
| --- | --- |
| [max](max "cpp/numeric/random/linear congruential engine/max")
[static] (C++11) | gets the largest possible value in the output range (public static member function) |
cpp std::linear_congruential_engine<UIntType,a,c,m>::linear_congruential_engine std::linear\_congruential\_engine<UIntType,a,c,m>::linear\_congruential\_engine
===============================================================================
| | | |
| --- | --- | --- |
|
```
linear_congruential_engine() : linear_congruential_engine(default_seed) {}
```
| (1) | (since C++11) |
|
```
explicit linear_congruential_engine( result_type value );
```
| (2) | (since C++11) |
|
```
template< class Sseq >
explicit linear_congruential_engine( Sseq& s );
```
| (3) | (since C++11) |
|
```
linear_congruential_engine( const linear_congruential_engine& );
```
| (4) | (since C++11) (implicitly declared) |
Constructs the pseudo-random number engine.
1) Default constructor. Seeds the engine with `default_seed`. The overload (3) only participates in overload resolution if `Sseq` qualifies as a [SeedSequence](../../../named_req/seedsequence "cpp/named req/SeedSequence"). In particular, it is excluded from the set of candidate functions if `Sseq` is convertible to `result_type`.
### Parameters
| | | |
| --- | --- | --- |
| value | - | seed value to use in the initialization of the internal state |
| s | - | seed sequence to use in the initialization of the internal state |
### Complexity
### 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 |
### See also
| | |
| --- | --- |
| [seed](seed "cpp/numeric/random/linear congruential engine/seed")
(C++11) | sets the current state of the engine (public member function) |
| programming_docs |
cpp operator==,!=(std::linear_congruential_engine)
operator==,!=(std::linear\_congruential\_engine)
================================================
| | | |
| --- | --- | --- |
|
```
friend bool operator==( const linear_congruential_engine& lhs,
const linear_congruential_engine& rhs );
```
| (1) | (since C++11) |
|
```
friend bool operator!=( const linear_congruential_engine& lhs,
const linear_congruential_engine& rhs );
```
| (2) | (since C++11) (until C++20) |
Compares two pseudo-random number engines. Two engines are equal, if their internal states are equivalent, that is, if they would generate equivalent values for any number of calls of `operator()`.
These functions are not visible to ordinary [unqualified](../../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../../language/adl "cpp/language/adl") when `std::linear_congruential_engine<UIntType,a,c,m>` is an associated class of the arguments.
| | |
| --- | --- |
| The `!=` operator is [synthesized](../../../language/operators#Relational_operators "cpp/language/operators") from `operator==`. | (since C++20) |
### Parameters
| | | |
| --- | --- | --- |
| lhs, rhs | - | engines to compare |
### Return value
1) `true` if the engines are equivalent, `false` otherwise.
2) `true` if the engines are not equivalent, `false` otherwise. ### Exceptions
Throws nothing.
### 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 3519](https://cplusplus.github.io/LWG/issue3519) | C++11 | the form of equality operators were unspecified | specified to be hidden friends |
cpp std::linear_congruential_engine<UIntType,a,c,m>::discard std::linear\_congruential\_engine<UIntType,a,c,m>::discard
==========================================================
| | | |
| --- | --- | --- |
|
```
void discard( unsigned long long z );
```
| | (since C++11) |
Advances the internal state by `z` times. Equivalent to calling `[operator()](operator() "cpp/numeric/random/linear congruential engine/operator()")` `z` times and discarding the result.
### Parameters
| | | |
| --- | --- | --- |
| z | - | integer value specifying the number of times to advance the state by |
### Return value
(none).
### Complexity
### Notes
For some engines, "fast jump" algorithms are known, which advance the state by many steps (order of millions) without calculating intermediate state transitions, although not necessarily in constant time.
### See also
| | |
| --- | --- |
| [operator()](operator() "cpp/numeric/random/linear congruential engine/operator()")
(C++11) | advances the engine's state and returns the generated value (public member function) |
cpp std::poisson_distribution<IntType>::mean std::poisson\_distribution<IntType>::mean
=========================================
| | | |
| --- | --- | --- |
|
```
double mean() const;
```
| | (since C++11) |
Returns the ฮผ parameter the distribution was constructed with. The parameter defines mean number of occurrences of the event. The default value is `1.0`.
### Parameters
(none).
### Return value
Floating point value identifying the ฮผ distribution parameter.
### See also
| | |
| --- | --- |
| [param](param "cpp/numeric/random/poisson distribution/param")
(C++11) | gets or sets the distribution parameter object (public member function) |
cpp operator<<,>>(std::poisson_distribution)
operator<<,>>(std::poisson\_distribution)
=========================================
| | | |
| --- | --- | --- |
|
```
template< class CharT, class Traits >
friend std::basic_ostream<CharT,Traits>&
operator<<( std::basic_ostream<CharT,Traits>& ost,
const poisson_distribution& d );
```
| (1) | (since C++11) |
|
```
template< class CharT, class Traits >
friend std::basic_istream<CharT,Traits>&
operator>>( std::basic_istream<CharT,Traits>& ist,
poisson_distribution& d );
```
| (2) | (since C++11) |
Performs stream input and output operations on pseudo-random number distribution `d`.
1) Writes a textual representation of the distribution parameters and internal state to `ost` as textual representation. The formatting flags and fill character of `ost` are unchanged.
2) Restores the distribution parameters and internal state with data read from `ist`. The formatting flags of `ist` are unchanged. The data must have been written using a stream with the same locale, `CharT` and `Traits` template parameters, otherwise the behavior is undefined. If bad input is encountered, `ist.setstate(std::ios::failbit)` is called, which may throw `[std::ios\_base::failure](../../../io/ios_base/failure "cpp/io/ios base/failure")`. `d` is unchanged in that case. These function templates are not visible to ordinary [unqualified](../../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../../language/adl "cpp/language/adl") when `std::poisson_distribution<ResultType>` is an associated class of the arguments.
### Parameters
| | | |
| --- | --- | --- |
| ost | - | output stream to insert the data to |
| ist | - | input stream to extract the data from |
| d | - | pseudo-random number distribution |
### Return value
1) `ost`
2) `ist`
### Exceptions
1) May throw implementation-defined exceptions.
2) May throw `[std::ios\_base::failure](../../../io/ios_base/failure "cpp/io/ios base/failure")` on bad input. ### 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 3519](https://cplusplus.github.io/LWG/issue3519) | C++11 | the form of insertion and extraction operators were unspecified(could be hidden friends or out-of-class function templates) | specified to be hidden friends |
cpp std::poisson_distribution<IntType>::reset std::poisson\_distribution<IntType>::reset
==========================================
| | | |
| --- | --- | --- |
|
```
void reset();
```
| | (since C++11) |
Resets the internal state of the distribution object. After a call to this function, the next call to `operator()` on the distribution object will not be dependent on previous calls to `operator()`.
### Parameters
(none).
### Return value
(none).
### Complexity
Constant.
cpp std::poisson_distribution<IntType>::operator() std::poisson\_distribution<IntType>::operator()
===============================================
| | | |
| --- | --- | --- |
|
```
template< class Generator >
result_type operator()( Generator& g );
```
| (1) | (since C++11) |
|
```
template< class Generator >
result_type operator()( Generator& g, const param_type& params );
```
| (2) | (since C++11) |
Generates random numbers that are distributed according to the associated probability function. The entropy is acquired by calling `g.operator()`.
The first version uses the associated parameter set, the second version uses `params`. The associated parameter set is not modified.
### Parameters
| | | |
| --- | --- | --- |
| g | - | an uniform random bit generator object |
| params | - | distribution parameter set to use instead of the associated one |
| Type requirements |
| -`Generator` must meet the requirements of [UniformRandomBitGenerator](../../../named_req/uniformrandombitgenerator "cpp/named req/UniformRandomBitGenerator"). |
### Return value
The generated random number.
### Complexity
Amortized constant number of invocations of `g.operator()`.
cpp std::poisson_distribution<IntType>::poisson_distribution std::poisson\_distribution<IntType>::poisson\_distribution
==========================================================
| | | |
| --- | --- | --- |
|
```
poisson_distribution() : poisson_distribution(1.0) {}
```
| (1) | (since C++11) |
|
```
explicit poisson_distribution( double mean );
```
| (2) | (since C++11) |
|
```
explicit poisson_distribution( const param_type& params );
```
| (3) | (since C++11) |
Constructs a new distribution object.
1) uses `1.0` as the distribution parameter.
2) uses `mean` as the distribution parameter.
3) uses `params` as the distribution parameter. ### Parameters
| | | |
| --- | --- | --- |
| mean | - | the *ฮผ* distribution parameter (the mean of the distribution) |
| params | - | the distribution parameter set |
### Notes
Requires that `0 < mean`.
### 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::poisson_distribution<IntType>::max std::poisson\_distribution<IntType>::max
========================================
| | | |
| --- | --- | --- |
|
```
result_type max() const;
```
| | (since C++11) |
Returns the maximum value potentially generated by the distribution.
### Parameters
(none).
### Return value
The maximum value potentially generated by the distribution.
### Complexity
Constant.
### See also
| | |
| --- | --- |
| [min](min "cpp/numeric/random/poisson distribution/min")
(C++11) | returns the minimum potentially generated value (public member function) |
cpp std::poisson_distribution<IntType>::min std::poisson\_distribution<IntType>::min
========================================
| | | |
| --- | --- | --- |
|
```
result_type min() const;
```
| | (since C++11) |
Returns the minimum value potentially generated by the distribution.
### Parameters
(none).
### Return value
The minimum value potentially generated by the distribution.
### Complexity
Constant.
### See also
| | |
| --- | --- |
| [max](max "cpp/numeric/random/poisson distribution/max")
(C++11) | returns the maximum potentially generated value (public member function) |
cpp std::poisson_distribution<IntType>::param std::poisson\_distribution<IntType>::param
==========================================
| | | |
| --- | --- | --- |
|
```
param_type param() const;
```
| (1) | (since C++11) |
|
```
void param( const param_type& params );
```
| (2) | (since C++11) |
Manages the associated distribution parameter set.
1) Returns the associated parameter set.
2) Sets the associated parameter set to `params`.
### Parameters
| | | |
| --- | --- | --- |
| params | - | new contents of the associated parameter set |
### Return value
1) The associated parameter set.
2) (none).
### Complexity
Constant.
cpp operator==,!=(std::poisson_distribution)
operator==,!=(std::poisson\_distribution)
=========================================
| | | |
| --- | --- | --- |
|
```
friend bool operator==( const poisson_distribution& lhs,
const poisson_distribution& rhs );
```
| (1) | (since C++11) |
|
```
friend bool operator!=( const poisson_distribution& lhs,
const poisson_distribution& rhs );
```
| (2) | (since C++11) (until C++20) |
Compares two distribution objects. Two distribution objects are equal when parameter values and internal state is the same.
1) Compares two distribution objects for equality.
2) Compares two distribution objects for inequality. These functions are not visible to ordinary [unqualified](../../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../../language/adl "cpp/language/adl") when `std::poisson_distribution<ResultType>` is an associated class of the arguments.
| | |
| --- | --- |
| The `!=` operator is [synthesized](../../../language/operators#Relational_operators "cpp/language/operators") from `operator==`. | (since C++20) |
### Parameters
| | | |
| --- | --- | --- |
| lhs, rhs | - | distribution objects to compare |
### Return value
1) `true` if the distribution objects are equal, `false` otherwise.
2) `true` if the distribution objects are not equal, `false` otherwise. ### Complexity
Constant.
### 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 3519](https://cplusplus.github.io/LWG/issue3519) | C++11 | the form of equality operators were unspecified(could be hidden friends or free function templates) | specified to be hidden friends |
cpp std::unsigned_integral std::unsigned\_integral
=======================
| Defined in header `[<concepts>](../header/concepts "cpp/header/concepts")` | | |
| --- | --- | --- |
|
```
template < class T >
concept unsigned_integral = std::integral<T> && !std::signed_integral<T>;
```
| | (since C++20) |
The concept `unsigned_integral<T>` is satisfied if and only if `T` is an integral type and `[std::is\_signed\_v](http://en.cppreference.com/w/cpp/types/is_signed)<T>` is `false`.
### Notes
`unsigned_integral<T>` may be satisfied by a type that is not an [unsigned integer type](../language/type#Type_classification "cpp/language/type"), for example, `bool`.
### See also
| | |
| --- | --- |
| [is\_integral](../types/is_integral "cpp/types/is integral")
(C++11) | checks if a type is an integral type (class template) |
| [is\_signed](../types/is_signed "cpp/types/is signed")
(C++11) | checks if a type is a signed arithmetic type (class template) |
cpp std::default_initializable std::default\_initializable
===========================
| Defined in header `[<concepts>](../header/concepts "cpp/header/concepts")` | | |
| --- | --- | --- |
|
```
template < class T >
concept default_initializable = std::constructible_from<T> && requires { T{}; } &&
/* T t; is well-formed, see below */;
```
| | (since C++20) |
The `default_initializable` concept checks whether variables of type `T` can be.
* [value-initialized](../language/value_initialization "cpp/language/value initialization") (`T()` is well-formed);
* [direct-list-initialized](../language/list_initialization "cpp/language/list initialization") from an empty initializer list (`T{}` is well-formed); and
* [default-initialized](../language/default_initialization "cpp/language/default initialization") (`T t;` is well-formed).
Access checking is performed as if in a context unrelated to T. Only the validity of the immediate context of the variable initialization is considered.
### Possible implementation
| |
| --- |
|
```
template<class T>
concept default_initializable =
std::constructible_from<T> &&
requires { T{}; } &&
requires { ::new (static_cast<void*>(nullptr)) T; };
```
|
### See also
| | |
| --- | --- |
| [constructible\_from](constructible_from "cpp/concepts/constructible from")
(C++20) | specifies that a variable of the type can be constructed from or bound to a set of argument types (concept) |
| [is\_default\_constructibleis\_trivially\_default\_constructibleis\_nothrow\_default\_constructible](../types/is_default_constructible "cpp/types/is default constructible")
(C++11)(C++11)(C++11) | checks if a type has a default constructor (class template) |
cpp std::movable std::movable
============
| Defined in header `[<concepts>](../header/concepts "cpp/header/concepts")` | | |
| --- | --- | --- |
|
```
template < class T >
concept movable =
std::is_object_v<T> &&
std::move_constructible<T> &&
std::assignable_from<T&, T> &&
std::swappable<T>;
```
| | (since C++20) |
The concept `movable<T>` specifies that `T` is an object type that can be moved (that is, it can be move constructed, move assigned, and lvalues of type `T` can be swapped).
### See also
| | |
| --- | --- |
| [copyable](copyable "cpp/concepts/copyable")
(C++20) | specifies that an object of a type can be copied, moved, and swapped (concept) |
cpp std::assignable_from std::assignable\_from
=====================
| Defined in header `[<concepts>](../header/concepts "cpp/header/concepts")` | | |
| --- | --- | --- |
|
```
template< class LHS, class RHS >
concept assignable_from =
std::is_lvalue_reference_v<LHS> &&
std::common_reference_with<
const std::remove_reference_t<LHS>&,
const std::remove_reference_t<RHS>&> &&
requires(LHS lhs, RHS&& rhs) {
{ lhs = std::forward<RHS>(rhs) } -> std::same_as<LHS>;
};
```
| | (since C++20) |
The concept `assignable_from<LHS, RHS>` specifies that an expression of the type and value category specified by `RHS` can be assigned to an lvalue expression whose type is specified by `LHS`.
### Semantic requirements
Given.
* `lhs`, an lvalue that refers to an object `lcopy` such that `decltype((lhs))` is `LHS`,
* `rhs`, an expression such that `decltype((rhs))` is `RHS`,
* `rcopy`, a distinct object that is equal to `rhs`,
`assignable_from<LHS, RHS>` is modeled only if.
* `[std::addressof](http://en.cppreference.com/w/cpp/memory/addressof)(lhs = rhs) == [std::addressof](http://en.cppreference.com/w/cpp/memory/addressof)(lcopy)` (i.e., the assignment expression yields an lvalue referring to the left operand);
* After evaluating `lhs = rhs`:
+ `lhs` is equal to `rcopy`, unless `rhs` is a non-const xvalue that refers to `lcopy` (i.e., the assignment is a self-move-assignment),
+ if `rhs` is a glvalue:
- If it is a non-const xvalue, the object to which it refers is in a valid but unspecified state;
- Otherwise, the object it refers to is not modified;
### Equality preservation
An expression is *equality preserving* if it results in equal outputs given equal inputs.
* The inputs to an expression consist of its operands.
* The outputs of an expression consist of its result and all operands modified by the expression (if any).
In specification of standard concepts, operands are defined as the largest subexpressions that include only:
* an [id-expression](../language/expressions#Primary_expressions "cpp/language/expressions"), and
* invocations of [`std::move`](../utility/move "cpp/utility/move"), `[std::forward](../utility/forward "cpp/utility/forward")`, and `[std::declval](../utility/declval "cpp/utility/declval")`.
The cv-qualification and value category of each operand is determined by assuming that each template type parameter denotes a cv-unqualified complete non-array object type.
Every expression required to be equality preserving is further required to be *stable*: two evaluations of such an expression with the same input objects must have equal outputs absent any explicit intervening modification of those input objects.
Unless noted otherwise, every expression used in a *requires-expression* is required to be equality preserving and stable, and the evaluation of the expression may modify only its non-constant operands. Operands that are constant must not be modified.
### Notes
Assignment need not be a total function. In particular, if assigning to some object `x` can cause some other object `y` to be modified, then `x = y` is likely not in the domain of `=`. This typically happens if the right operand is owned directly or indirectly by the left operand (e.g., with smart pointers to nodes in an node-based data structure, or with something like `[std::vector](http://en.cppreference.com/w/cpp/container/vector)<[std::any](http://en.cppreference.com/w/cpp/utility/any)>`).
### See also
| | |
| --- | --- |
| [is\_assignableis\_trivially\_assignableis\_nothrow\_assignable](../types/is_assignable "cpp/types/is assignable")
(C++11)(C++11)(C++11) | checks if a type has a assignment operator for a specific argument (class template) |
| programming_docs |
cpp std::same_as std::same\_as
=============
| Defined in header `[<concepts>](../header/concepts "cpp/header/concepts")` | | |
| --- | --- | --- |
|
```
template < class T, class U >
concept same_as = /* see below */;
```
| | (since C++20) |
The concept `same_as<T, U>` is satisfied if and only if `T` and `U` denote the same type.
`std::same_as<T, U>` [subsumes](../language/constraints#Partial_ordering_of_constraints "cpp/language/constraints") `std::same_as<U, T>` and vice versa.
### Possible implementation
| |
| --- |
|
```
namespace detail {
template< class T, class U >
concept SameHelper = std::is_same_v<T, U>;
}
template< class T, class U >
concept same_as = detail::SameHelper<T, U> && detail::SameHelper<U, T>;
```
|
### Example
```
#include <concepts>
#include <iostream>
template<typename T, typename ... U>
concept IsAnyOf = (std::same_as<T, U> || ...);
template<typename T>
concept IsPrintable = std::integral<T> || std::floating_point<T> ||
IsAnyOf<std::remove_cvref_t<std::remove_pointer_t<std::decay_t<T>>>, char, wchar_t>;
void println(IsPrintable auto const ... arguments)
{
(std::wcout << ... << arguments) << '\n';
}
int main() { println("Example: ", 3.14, " : ", 42, " : [", 'a', L'-', L"Z]"); }
```
Output:
```
Example: 3.14 : 42 : [a-Z]
```
### See also
| | |
| --- | --- |
| [is\_same](../types/is_same "cpp/types/is same")
(C++11) | checks if two types are the same (class template) |
cpp std::derived_from std::derived\_from
==================
| Defined in header `[<concepts>](../header/concepts "cpp/header/concepts")` | | |
| --- | --- | --- |
|
```
template< class Derived, class Base >
concept derived_from =
std::is_base_of_v<Base, Derived> &&
std::is_convertible_v<const volatile Derived*, const volatile Base*>;
```
| | (since C++20) |
The concept `derived_from<Derived, Base>` is satisfied if and only if `Base` is a class type that is either `Derived` or a public and unambiguous base of `Derived`, ignoring cv-qualifiers.
Note that this behaviour is different to `std::is_base_of` when `Base` is a private or protected base of `Derived`.
### Example
```
#include <concepts>
class A {};
class B: public A {};
class C: private A{};
int main() {
// std::derived_from == true only for public inheritance or exact same class
static_assert( std::derived_from<B, B> == true ); // same class: true
static_assert( std::derived_from<int, int> == false ); // same primitive type: false
static_assert( std::derived_from<B, A> == true ); // public inheritance: true
static_assert( std::derived_from<C, A> == false ); // private inheritance: false
// std::is_base_of == true also for private inheritance
static_assert( std::is_base_of_v<B, B> == true ); // same class: true
static_assert( std::is_base_of_v<int, int> == false ); // same primitive type: false
static_assert( std::is_base_of_v<A, B> == true ); // public inheritance: true
static_assert( std::is_base_of_v<A, C> == true ); // private inheritance: true
}
```
### See also
| | |
| --- | --- |
| [is\_base\_of](../types/is_base_of "cpp/types/is base of")
(C++11) | checks if a type is derived from the other type (class template) |
| [is\_convertibleis\_nothrow\_convertible](../types/is_convertible "cpp/types/is convertible")
(C++11)(C++20) | checks if a type can be converted to the other type (class template) |
cpp std::regular std::regular
============
| Defined in header `[<concepts>](../header/concepts "cpp/header/concepts")` | | |
| --- | --- | --- |
|
```
template <class T>
concept regular = std::semiregular<T> && std::equality_comparable<T>;
```
| | (since C++20) |
The `regular` concept specifies that a type is *regular*, that is, it is copyable, default constructible, and equality comparable. It is satisfied by types that behave similarly to built-in types like `int`, and that are comparable with `==`.
### Example
```
#include <concepts>
#include <iostream>
template<std::regular T>
struct Single {
T value;
friend bool operator==(const Single&, const Single&) = default;
};
int main()
{
Single<int> myInt1{4};
Single<int> myInt2;
myInt2 = myInt1;
if (myInt1 == myInt2)
std::cout << "Equal\n";
std::cout << myInt1.value << ' ' << myInt2.value << '\n';
}
```
Output:
```
Equal
4 4
```
### See also
| | |
| --- | --- |
| [semiregular](semiregular "cpp/concepts/semiregular")
(C++20) | specifies that an object of a type can be copied, moved, swapped, and default constructed (concept) |
cpp std::equivalence_relation std::equivalence\_relation
==========================
| Defined in header `[<concepts>](../header/concepts "cpp/header/concepts")` | | |
| --- | --- | --- |
|
```
template < class R, class T, class U >
concept equivalence_relation = std::relation<R, T, U>;
```
| | (since C++20) |
The concept `equivalence_relation<R, T, U>` specifies that the [`relation`](relation "cpp/concepts/relation") `R` imposes an equivalence relation on its arguments.
### Semantic requirements
A relation `r` is an equivalence relation if.
* it is reflexive: for all `x`, `r(x, x)` is true;
* it is symmetric: for all `a` and `b`, `r(a, b)` is true if and only if `r(b, a)` is true;
* it is transitive: `r(a, b) && r(b, c)` implies `r(a, c)`.
### Notes
The distinction between [`relation`](relation "cpp/concepts/relation") and `equivalence_relation` is purely semantic.
cpp std::integral std::integral
=============
| Defined in header `[<concepts>](../header/concepts "cpp/header/concepts")` | | |
| --- | --- | --- |
|
```
template < class T >
concept integral = std::is_integral_v<T>;
```
| | (since C++20) |
The concept `integral<T>` is satisfied if and only if `T` is an integral type.
### Example
```
#include <concepts>
#include <iostream>
void print(std::integral auto i) {
std::cout << "Integral: " << i << '\n';
}
void print(auto x) {
std::cout << "Non-integral: " << x << '\n';
}
int main()
{
std::cout << std::boolalpha;
print(true ); static_assert( std::integral<bool> );
print( 'o' ); static_assert( std::integral<char> );
print( 007 ); static_assert( std::integral<int> );
print( 2e2 ); static_assert( !std::integral<float> );
print("โซโซโซ"); static_assert( !std::integral<decltype("")> );
}
```
Output:
```
Integral: true
Integral: o
Integral: 7
Non-integral: 200
Non-integral: โซโซโซ
```
### See also
| | |
| --- | --- |
| [is\_integral](../types/is_integral "cpp/types/is integral")
(C++11) | checks if a type is an integral type (class template) |
cpp std::copy_constructible std::copy\_constructible
========================
| Defined in header `[<concepts>](../header/concepts "cpp/header/concepts")` | | |
| --- | --- | --- |
|
```
template <class T>
concept copy_constructible =
std::move_constructible<T> &&
std::constructible_from<T, T&> && std::convertible_to<T&, T> &&
std::constructible_from<T, const T&> && std::convertible_to<const T&, T> &&
std::constructible_from<T, const T> && std::convertible_to<const T, T>;
```
| | (since C++20) |
The concept `copy_constructible` is satisfied if `T` is an lvalue reference type, or if it is a [`move_constructible`](move_constructible "cpp/concepts/move constructible") object type where an object of that type can constructed from a (possibly const) lvalue or const rvalue of that type in both direct- and copy-initialization contexts with the usual semantics (a copy is constructed with the source unchanged).
### Semantic requirements
If `T` is an object type, then `copy_constructible<T>` is modeled only if given.
* `v`, a lvalue of type (possibly `const`) `T` or an rvalue of type `const T`,
the following are true:
* After the definition `T u = v;`, `u` is equal to `v` and `v` is not modified;
* `T(v)` is equal to `v` and does not modify `v`.
### See also
| | |
| --- | --- |
| [is\_copy\_constructibleis\_trivially\_copy\_constructibleis\_nothrow\_copy\_constructible](../types/is_copy_constructible "cpp/types/is copy constructible")
(C++11)(C++11)(C++11) | checks if a type has a copy constructor (class template) |
cpp std::floating_point std::floating\_point
====================
| Defined in header `[<concepts>](../header/concepts "cpp/header/concepts")` | | |
| --- | --- | --- |
|
```
template < class T >
concept floating_point = std::is_floating_point_v<T>;
```
| | (since C++20) |
The concept `floating_point<T>` is satisfied if and only if `T` is a floating-point type.
### Example
```
#include <concepts>
#include <iostream>
#include <type_traits>
constexpr std::floating_point auto x2(std::floating_point auto x) {
return x + x;
}
constexpr std::integral auto x2(std::integral auto x) {
return x << 1;
}
int main() {
constexpr auto d = x2(1.1);
static_assert(std::is_same_v<double const, decltype(d)>);
std::cout << d << '\n';
constexpr auto f = x2(2.2f);
static_assert(std::is_same_v<float const, decltype(f)>);
std::cout << f << '\n';
constexpr auto i = x2(444);
static_assert(std::is_same_v<int const, decltype(i)>);
std::cout << i << '\n';
}
```
Output:
```
2.2
4.4
888
```
### See also
| | |
| --- | --- |
| [is\_floating\_point](../types/is_floating_point "cpp/types/is floating point")
(C++11) | checks if a type is a floating-point type (class template) |
cpp std::convertible_to std::convertible\_to
====================
| Defined in header `[<concepts>](../header/concepts "cpp/header/concepts")` | | |
| --- | --- | --- |
|
```
template <class From, class To>
concept convertible_to =
std::is_convertible_v<From, To> &&
requires {
static_cast<To>(std::declval<From>());
};
```
| | (since C++20) |
The concept `convertible_to<From, To>` specifies that an expression of the same type and value category as those of `[std::declval](http://en.cppreference.com/w/cpp/utility/declval)<From>()` can be implicitly and explicitly converted to the type `To`, and the two forms of conversion are equivalent.
### Semantic requirements
`convertible_to<From, To>` is modeled only if, given a function `fun` of type `[std::add\_rvalue\_reference\_t](http://en.cppreference.com/w/cpp/types/add_reference)<From>()` such that the expression `fun()` is equality-preserving (see below),
* Either
+ `To` is neither an object type nor a reference-to-object type, or
+ `static_cast<To>(fun())` is equal to `[]() -> To { return fun(); }()`, and
* One of the following is true:
+ `[std::add\_rvalue\_reference\_t](http://en.cppreference.com/w/cpp/types/add_reference)<From>` is not a reference-to-object type, or
+ `[std::add\_rvalue\_reference\_t](http://en.cppreference.com/w/cpp/types/add_reference)<From>` is an rvalue reference to a non-const-qualified type, and the resulting state of the object referenced by `fun()` is valid but unspecified after either expression above; or
+ the object referred to by `fun()` is not modified by either expression above.
### Equality preservation
An expression is *equality preserving* if it results in equal outputs given equal inputs.
* The inputs to an expression consist of its operands.
* The outputs of an expression consist of its result and all operands modified by the expression (if any).
In specification of standard concepts, operands are defined as the largest subexpressions that include only:
* an [id-expression](../language/expressions#Primary_expressions "cpp/language/expressions"), and
* invocations of [`std::move`](../utility/move "cpp/utility/move"), `[std::forward](../utility/forward "cpp/utility/forward")`, and `[std::declval](../utility/declval "cpp/utility/declval")`.
The cv-qualification and value category of each operand is determined by assuming that each template type parameter denotes a cv-unqualified complete non-array object type.
Every expression required to be equality preserving is further required to be *stable*: two evaluations of such an expression with the same input objects must have equal outputs absent any explicit intervening modification of those input objects.
Unless noted otherwise, every expression used in a *requires-expression* is required to be equality preserving and stable, and the evaluation of the expression may modify only its non-constant operands. Operands that are constant must not be modified.
### See also
| | |
| --- | --- |
| [is\_convertibleis\_nothrow\_convertible](../types/is_convertible "cpp/types/is convertible")
(C++11)(C++20) | checks if a type can be converted to the other type (class template) |
cpp std::copyable std::copyable
=============
| Defined in header `[<concepts>](../header/concepts "cpp/header/concepts")` | | |
| --- | --- | --- |
|
```
template <class T>
concept copyable =
std::copy_constructible<T> &&
std::movable<T> &&
std::assignable_from<T&, T&> &&
std::assignable_from<T&, const T&> &&
std::assignable_from<T&, const T>;
```
| | (since C++20) |
The concept `copyable<T>` specifies that `T` is a [`movable`](movable "cpp/concepts/movable") object type that can also copied (that is, it supports copy construction and copy assignment).
### See also
| | |
| --- | --- |
| [movable](movable "cpp/concepts/movable")
(C++20) | specifies that an object of a type can be moved and swapped (concept) |
cpp std::destructible std::destructible
=================
| Defined in header `[<concepts>](../header/concepts "cpp/header/concepts")` | | |
| --- | --- | --- |
|
```
template < class T >
concept destructible = std::is_nothrow_destructible_v<T>;
```
| | (since C++20) |
The concept `destructible` specifies the concept of all types whose instances can safely be destroyed at the end of their lifetime (including reference types).
### Notes
Unlike the [Destructible](../named_req/destructible "cpp/named req/Destructible") named requirement, `std::destructible` requires the destructor to be `noexcept(true)`, not merely non-throwing when invoked, and allows reference types and array types.
### See also
| | |
| --- | --- |
| [is\_destructibleis\_trivially\_destructibleis\_nothrow\_destructible](../types/is_destructible "cpp/types/is destructible")
(C++11)(C++11)(C++11) | checks if a type has a non-deleted destructor (class template) |
cpp std::strict_weak_order std::strict\_weak\_order
========================
| Defined in header `[<concepts>](../header/concepts "cpp/header/concepts")` | | |
| --- | --- | --- |
|
```
template < class R, class T, class U >
concept strict_weak_order = std::relation<R, T, U>;
```
| | (since C++20) |
The concept `strict_weak_order<R, T, U>` specifies that the [`relation`](relation "cpp/concepts/relation") `R` imposes a strict weak ordering on its arguments.
### Semantic requirements
A relation `r` is a strict weak ordering if.
* it is irreflexive: for all `x`, `r(x, x)` is false;
* it is transitive: for all `a`, `b` and `c`, if `r(a, b)` and `r(b, c)` are both true then `r(a, c)` is true;
* let `e(a, b)` be `!r(a, b) &&ย !r(b, a)`, then `e` is transitive: `e(a, b) && e(b, c)` implies `e(a, c)`.
Under these conditions, it can be shown that `e` is an equivalence relation, and `r` induces a strict total ordering on the equivalence classes determined by `e`.
### Notes
The distinction between [`relation`](relation "cpp/concepts/relation") and `strict_weak_order` is purely semantic.
cpp std::invocable, std::regular_invocable std::invocable, std::regular\_invocable
=======================================
| Defined in header `[<concepts>](../header/concepts "cpp/header/concepts")` | | |
| --- | --- | --- |
|
```
template< class F, class... Args >
concept invocable =
requires(F&& f, Args&&... args) {
std::invoke(std::forward<F>(f), std::forward<Args>(args)...);
/* not required to be equality preserving */
};
```
| | (since C++20) |
|
```
template< class F, class... Args >
concept regular_invocable = std::invocable<F, Args...>;
```
| | (since C++20) |
The `invocable` concept specifies that a callable type `F` can be called with a set of argument `Args...` using the function template `[std::invoke](../utility/functional/invoke "cpp/utility/functional/invoke")`.
The `regular_invocable` concept adds to the `invocable` concept by requiring the `invoke` expression to be equality preserving and not modify either the function object or the arguments.
### Equality preservation
An expression is *equality preserving* if it results in equal outputs given equal inputs.
* The inputs to an expression consist of its operands.
* The outputs of an expression consist of its result and all operands modified by the expression (if any).
In specification of standard concepts, operands are defined as the largest subexpressions that include only:
* an [id-expression](../language/expressions#Primary_expressions "cpp/language/expressions"), and
* invocations of [`std::move`](../utility/move "cpp/utility/move"), `[std::forward](../utility/forward "cpp/utility/forward")`, and `[std::declval](../utility/declval "cpp/utility/declval")`.
The cv-qualification and value category of each operand is determined by assuming that each template type parameter denotes a cv-unqualified complete non-array object type.
Every expression required to be equality preserving is further required to be *stable*: two evaluations of such an expression with the same input objects must have equal outputs absent any explicit intervening modification of those input objects.
Unless noted otherwise, every expression used in a *requires-expression* is required to be equality preserving and stable, and the evaluation of the expression may modify only its non-constant operands. Operands that are constant must not be modified.
### Notes
The distinction between `invocable` and `regular_invocable` is purely semantic.
A random number generator may satisfy `invocable` but cannot satisfy `regular_invocable` ([comical](https://xkcd.com/221/) [ones](http://dilbert.com/strip/2001-10-25) excluded).
### See also
| | |
| --- | --- |
| [is\_invocableis\_invocable\_ris\_nothrow\_invocableis\_nothrow\_invocable\_r](../types/is_invocable "cpp/types/is invocable")
(C++17) | checks if a type can be invoked (as if by `[std::invoke](../utility/functional/invoke "cpp/utility/functional/invoke")`) with the given argument types (class template) |
cpp std::swappable, std::swappable_with std::swappable, std::swappable\_with
====================================
| Defined in header `[<concepts>](../header/concepts "cpp/header/concepts")` | | |
| --- | --- | --- |
|
```
template< class T >
concept swappable =
requires(T& a, T& b) {
ranges::swap(a, b);
};
```
| (1) | (since C++20) |
|
```
template< class T, class U >
concept swappable_with =
std::common_reference_with<T, U> &&
requires(T&& t, U&& u) {
ranges::swap(std::forward<T>(t), std::forward<T>(t));
ranges::swap(std::forward<U>(u), std::forward<U>(u));
ranges::swap(std::forward<T>(t), std::forward<U>(u));
ranges::swap(std::forward<U>(u), std::forward<T>(t));
};
```
| (2) | (since C++20) |
The concept `swappable<T>` specifies that lvalues of type `T` are swappable.
The concept `swappable_with<T, U>` specifies that expressions of the type and value category encoded by `T` and `U` are swappable with each other. `swappable_with<T, U>` is satisfied only if a call to `[ranges::swap](http://en.cppreference.com/w/cpp/ranges-utility-placeholder/swap)(t, u)` exchanges the value of `t` and `u`, that is, given distinct objects `t2` equal to `t` and `u2` equal to `u`, after evaluating either `[ranges::swap](http://en.cppreference.com/w/cpp/ranges-utility-placeholder/swap)(t, u)` or `[ranges::swap](http://en.cppreference.com/w/cpp/ranges-utility-placeholder/swap)(u, t)`, `t2` is equal to `u` and `u2` is equal to `t`.
### Equality preservation
An expression is *equality preserving* if it results in equal outputs given equal inputs.
* The inputs to an expression consist of its operands.
* The outputs of an expression consist of its result and all operands modified by the expression (if any).
In specification of standard concepts, operands are defined as the largest subexpressions that include only:
* an [id-expression](../language/expressions#Primary_expressions "cpp/language/expressions"), and
* invocations of [`std::move`](../utility/move "cpp/utility/move"), `[std::forward](../utility/forward "cpp/utility/forward")`, and `[std::declval](../utility/declval "cpp/utility/declval")`.
The cv-qualification and value category of each operand is determined by assuming that each template type parameter denotes a cv-unqualified complete non-array object type.
Every expression required to be equality preserving is further required to be *stable*: two evaluations of such an expression with the same input objects must have equal outputs absent any explicit intervening modification of those input objects.
Unless noted otherwise, every expression used in a *requires-expression* is required to be equality preserving and stable, and the evaluation of the expression may modify only its non-constant operands. Operands that are constant must not be modified.
| programming_docs |
cpp std::move_constructible std::move\_constructible
========================
| Defined in header `[<concepts>](../header/concepts "cpp/header/concepts")` | | |
| --- | --- | --- |
|
```
template< class T >
concept move_constructible = std::constructible_from<T, T> && std::convertible_to<T, T>;
```
| | (since C++20) |
The concept `move_constructible` is satisfied if `T` is a reference type, or if it is an object type where an object of that type can be constructed from an rvalue of that type in both direct- and copy-initialization contexts, with the usual semantics.
### Semantic requirements
If `T` is an object type, then `move_constructible<T>` is modeled only if given.
* `rv`, an rvalue of type `T`, and
* `u2`, a distinct object of type `T` equal to `rv`,
the following are true:
* After the definition `T u = rv;`, `u` is equal to `u2`;
* `T(rv)` is equal to `u2`; and
* If `T` is not const-qualified, then `rv`'s resulting state (after the definition/expression is evaluated in either bullets above) is valid but unspecified; otherwise, it is unchanged.
### See also
| | |
| --- | --- |
| [is\_move\_constructibleis\_trivially\_move\_constructibleis\_nothrow\_move\_constructible](../types/is_move_constructible "cpp/types/is move constructible")
(C++11)(C++11)(C++11) | checks if a type can be constructed from an rvalue reference (class template) |
cpp std::constructible_from std::constructible\_from
========================
| Defined in header `[<concepts>](../header/concepts "cpp/header/concepts")` | | |
| --- | --- | --- |
|
```
template < class T, class... Args >
concept constructible_from =
std::destructible<T> && std::is_constructible_v<T, Args...>;
```
| | (since C++20) |
The `constructible_from` concept specifies that a variable of type `T` can be initialized with the given set of argument types `Args...`.
### See also
| | |
| --- | --- |
| [is\_constructibleis\_trivially\_constructibleis\_nothrow\_constructible](../types/is_constructible "cpp/types/is constructible")
(C++11)(C++11)(C++11) | checks if a type has a constructor for specific arguments (class template) |
cpp std::predicate std::predicate
==============
| Defined in header `[<concepts>](../header/concepts "cpp/header/concepts")` | | |
| --- | --- | --- |
|
```
template < class F, class... Args >
concept predicate =
std::regular_invocable<F, Args...> &&
boolean-testable<std::invoke_result_t<F, Args...>>;
```
| | (since C++20) |
The concept `predicate<F, Args...>` specifies that `F` is a predicate that accepts arguments whose types and value categories are encoded by `Args...`, i.e., it can be invoked with these arguments to produce a [`boolean-testable`](boolean-testable "cpp/concepts/boolean-testable") result.
Note that [`regular_invocable`](invocable "cpp/concepts/invocable") requires the invocation to not modify either the callable object or the arguments and be equality-preserving.
### Equality preservation
An expression is *equality preserving* if it results in equal outputs given equal inputs.
* The inputs to an expression consist of its operands.
* The outputs of an expression consist of its result and all operands modified by the expression (if any).
In specification of standard concepts, operands are defined as the largest subexpressions that include only:
* an [id-expression](../language/expressions#Primary_expressions "cpp/language/expressions"), and
* invocations of [`std::move`](../utility/move "cpp/utility/move"), `[std::forward](../utility/forward "cpp/utility/forward")`, and `[std::declval](../utility/declval "cpp/utility/declval")`.
The cv-qualification and value category of each operand is determined by assuming that each template type parameter denotes a cv-unqualified complete non-array object type.
Every expression required to be equality preserving is further required to be *stable*: two evaluations of such an expression with the same input objects must have equal outputs absent any explicit intervening modification of those input objects.
cpp std::signed_integral std::signed\_integral
=====================
| Defined in header `[<concepts>](../header/concepts "cpp/header/concepts")` | | |
| --- | --- | --- |
|
```
template < class T >
concept signed_integral = std::integral<T> && std::is_signed_v<T>;
```
| | (since C++20) |
The concept `signed_integral<T>` is satisfied if and only if `T` is an integral type and `[std::is\_signed\_v](http://en.cppreference.com/w/cpp/types/is_signed)<T>` is `true`.
### Notes
`signed_integral<T>` may be satisfied by a type that is not a [signed integer type](../language/type#Type_classification "cpp/language/type"), for example, `char` (on a system where `char` is signed).
### Example
```
#include <concepts>
#include <iostream>
void print(std::signed_integral auto i) {
std::cout << "Signed integral: " << i << '\n';
}
void print(std::unsigned_integral auto u) {
std::cout << "Unsigned integral: " << u << '\n';
}
void print(auto x) {
std::cout << "Non-integral: " << x << '\n';
}
int main() {
print(42); // signed
print(0xFull); // unsigned
print(true); // unsigned
print('A'); // platform-dependent
print(4e-2); // non-integral (hex-float)
print("โซโซโซ"); // non-integral
}
```
Possible output:
```
Signed integral: 42
Unsigned integral: 15
Unsigned integral: 1
Signed integral: A
Non-integral: 0.04
Non-integral: โซโซโซ
```
### See also
| | |
| --- | --- |
| [is\_integral](../types/is_integral "cpp/types/is integral")
(C++11) | checks if a type is an integral type (class template) |
| [is\_signed](../types/is_signed "cpp/types/is signed")
(C++11) | checks if a type is a signed arithmetic type (class template) |
cpp std::common_reference_with std::common\_reference\_with
============================
| Defined in header `[<concepts>](../header/concepts "cpp/header/concepts")` | | |
| --- | --- | --- |
|
```
template < class T, class U >
concept common_reference_with =
std::same_as<std::common_reference_t<T, U>, std::common_reference_t<U, T>> &&
std::convertible_to<T, std::common_reference_t<T, U>> &&
std::convertible_to<U, std::common_reference_t<T, U>>;
```
| | (since C++20) |
The concept `common_reference_with<T, U>` specifies that two types `T` and `U` share a *common reference type* (as computed by `std::common_reference_t`) to which both can be converted.
### Semantic requirements
T and U model `common_reference_with<T, U>` only if, given equality-preserving expressions `t1`, `t2`, `u1` and `u2` such that `decltype((t1))` and `decltype((t2))` are both `T` and `decltype((u1))` and `decltype((u2))` are both `U`,
* `[std::common\_reference\_t](http://en.cppreference.com/w/cpp/types/common_reference)<T, U>(t1)` equals `[std::common\_reference\_t](http://en.cppreference.com/w/cpp/types/common_reference)<T, U>(t2)` if and only if `t1` equals `t2`; and
* `[std::common\_reference\_t](http://en.cppreference.com/w/cpp/types/common_reference)<T, U>(u1)` equals `[std::common\_reference\_t](http://en.cppreference.com/w/cpp/types/common_reference)<T, U>(u2)` if and only if `u1` equals `u2`.
In other words, the conversion to the common reference type must preserve equality.
### Equality preservation
An expression is *equality preserving* if it results in equal outputs given equal inputs.
* The inputs to an expression consist of its operands.
* The outputs of an expression consist of its result and all operands modified by the expression (if any).
In specification of standard concepts, operands are defined as the largest subexpressions that include only:
* an [id-expression](../language/expressions#Primary_expressions "cpp/language/expressions"), and
* invocations of [`std::move`](../utility/move "cpp/utility/move"), `[std::forward](../utility/forward "cpp/utility/forward")`, and `[std::declval](../utility/declval "cpp/utility/declval")`.
The cv-qualification and value category of each operand is determined by assuming that each template type parameter denotes a cv-unqualified complete non-array object type.
Every expression required to be equality preserving is further required to be *stable*: two evaluations of such an expression with the same input objects must have equal outputs absent any explicit intervening modification of those input objects.
### See also
| | |
| --- | --- |
| [common\_referencebasic\_common\_reference](../types/common_reference "cpp/types/common reference")
(C++20) | determines the common reference type of a group of types (class template) |
| [common\_with](common_with "cpp/concepts/common with")
(C++20) | specifies that two types share a common type (concept) |
| [common\_type](../types/common_type "cpp/types/common type")
(C++11) | determines the common type of a group of types (class template) |
cpp boolean-testable *boolean-testable*
==================
| | | |
| --- | --- | --- |
|
```
template<class B>
concept __boolean_testable_impl = // exposition only
std::convertible_to<B, bool>;
```
| | (since C++20) |
|
```
template<class B>
concept boolean-testable = // exposition only
__boolean_testable_impl<B> &&
requires (B&& b) {
{ !std::forward<B>(b) } -> __boolean_testable_impl;
};
```
| | (since C++20) |
The exposition-only concept `*boolean-testable*` specifies the requirements for expressions that are convertible to `bool` and for which the logical operators have the usual behavior (including short-circuiting), even for two different `*boolean-testable*` types.
Formally, to model the exposition-only concept `__boolean_testable_impl`, the type must not define any member `operator&&` and `operator||`, and no viable non-member `operator&&` and `operator||` may be visible by [argument-dependent lookup](../language/adl "cpp/language/adl"). Additionally, given an expression `e` such that `decltype((e))` is `B`, `*boolean-testable*` is modeled only if `bool(e) == !bool(!e)`.
### Equality preservation
An expression is *equality preserving* if it results in equal outputs given equal inputs.
* The inputs to an expression consist of its operands.
* The outputs of an expression consist of its result and all operands modified by the expression (if any).
In specification of standard concepts, operands are defined as the largest subexpressions that include only:
* an [id-expression](../language/expressions#Primary_expressions "cpp/language/expressions"), and
* invocations of [`std::move`](../utility/move "cpp/utility/move"), `[std::forward](../utility/forward "cpp/utility/forward")`, and `[std::declval](../utility/declval "cpp/utility/declval")`.
The cv-qualification and value category of each operand is determined by assuming that each template type parameter denotes a cv-unqualified complete non-array object type.
Every expression required to be equality preserving is further required to be *stable*: two evaluations of such an expression with the same input objects must have equal outputs absent any explicit intervening modification of those input objects.
Unless noted otherwise, every expression used in a *requires-expression* is required to be equality preserving and stable, and the evaluation of the expression may modify only its non-constant operands. Operands that are constant must not be modified.
### Notes
Examples of `*boolean-testable*` types include `bool`, `[std::true\_type](http://en.cppreference.com/w/cpp/types/integral_constant)`, and `[std::bitset](http://en.cppreference.com/w/cpp/utility/bitset)<N>::reference`, and `int*`.
cpp std::semiregular std::semiregular
================
| Defined in header `[<concepts>](../header/concepts "cpp/header/concepts")` | | |
| --- | --- | --- |
|
```
template <class T>
concept semiregular = std::copyable<T> && std::default_initializable<T>;
```
| | (since C++20) |
The `semiregular` concept specifies that a type is both copyable and default constructible. It is satisfied by types that behave similarly to built-in types like `int`, except that they need not support comparison with `==`.
### Example
```
#include <concepts>
#include <iostream>
template<std::semiregular T>
// Credit Alexander Stepanov
// concepts are requirements on T
// Requirement on T: T is semiregular
// T a(b); or T a = b; => copy constructor
// T a; => default constructor
// a = b; => assignment
struct Single {
T value;
// Aggregation initialization for Single behaves like following constructor:
// explicit Single(const T& x) : value(x){}
// Implicitly declared special member functions behave like following definitions,
// except that they may have additional properties:
// Single(const Single& x) : value(x.value){}
// Single(){}
// ~Single(){}
// Single& operator=(const Single& x) { value = x.value; return *this; }
// comparison operator is not defined; it is not required by `semiregular` concept
// bool operator== (Single const& other) const = delete;
};
void print(std::semiregular auto x)
{
std::cout << x.value << ' ';
}
int main()
{
Single<int> myInt1{4}; // aggregate initialization: myInt1.value = 4
Single<int> myInt2(myInt1); // copy constructor
Single<int> myInt3; // default constructor
myInt3 = myInt2; // copy assignment operator
// myInt1 == myInt2; // Error: operator== is not defined
print(myInt1); // ok: Single<int> is a `semiregular` type
print(myInt2);
print(myInt3);
} // Single<int> variables are destroyed here
```
Output:
```
4 4 4
```
### See also
| | |
| --- | --- |
| [regular](regular "cpp/concepts/regular")
(C++20) | specifies that a type is regular, that is, it is both **`semiregular`** and [`equality_comparable`](equality_comparable "cpp/concepts/equality comparable") (concept) |
cpp std::common_with std::common\_with
=================
| Defined in header `[<concepts>](../header/concepts "cpp/header/concepts")` | | |
| --- | --- | --- |
|
```
template <class T, class U>
concept common_with =
std::same_as<std::common_type_t<T, U>, std::common_type_t<U, T>> &&
requires {
static_cast<std::common_type_t<T, U>>(std::declval<T>());
static_cast<std::common_type_t<T, U>>(std::declval<U>());
} &&
std::common_reference_with<
std::add_lvalue_reference_t<const T>,
std::add_lvalue_reference_t<const U>> &&
std::common_reference_with<
std::add_lvalue_reference_t<std::common_type_t<T, U>>,
std::common_reference_t<
std::add_lvalue_reference_t<const T>,
std::add_lvalue_reference_t<const U>>>;
```
| | (since C++20) |
The concept `common_with<T, U>` specifies that two types `T` and `U` share a *common type* (as computed by `[std::common\_type\_t](../types/common_type "cpp/types/common type")`) to which both can be converted.
### Semantic requirements
T and U model `common_with<T, U>` only if, given equality-preserving expressions `t1`, `t2`, `u1` and `u2` such that `decltype((t1))` and `decltype((t2))` are both `T` and `decltype((u1))` and `decltype((u2))` are both `U`,
* `[std::common\_type\_t](http://en.cppreference.com/w/cpp/types/common_type)<T, U>(t1)` equals `[std::common\_type\_t](http://en.cppreference.com/w/cpp/types/common_type)<T, U>(t2)` if and only if `t1` equals `t2`; and
* `[std::common\_type\_t](http://en.cppreference.com/w/cpp/types/common_type)<T, U>(u1)` equals `[std::common\_type\_t](http://en.cppreference.com/w/cpp/types/common_type)<T, U>(u2)` if and only if `u1` equals `u2`.
In other words, the conversion to the common type must preserve equality.
### Equality preservation
An expression is *equality preserving* if it results in equal outputs given equal inputs.
* The inputs to an expression consist of its operands.
* The outputs of an expression consist of its result and all operands modified by the expression (if any).
In specification of standard concepts, operands are defined as the largest subexpressions that include only:
* an [id-expression](../language/expressions#Primary_expressions "cpp/language/expressions"), and
* invocations of [`std::move`](../utility/move "cpp/utility/move"), `[std::forward](../utility/forward "cpp/utility/forward")`, and `[std::declval](../utility/declval "cpp/utility/declval")`.
The cv-qualification and value category of each operand is determined by assuming that each template type parameter denotes a cv-unqualified complete non-array object type.
Every expression required to be equality preserving is further required to be *stable*: two evaluations of such an expression with the same input objects must have equal outputs absent any explicit intervening modification of those input objects.
### See also
| | |
| --- | --- |
| [common\_type](../types/common_type "cpp/types/common type")
(C++11) | determines the common type of a group of types (class template) |
| [common\_referencebasic\_common\_reference](../types/common_reference "cpp/types/common reference")
(C++20) | determines the common reference type of a group of types (class template) |
| [common\_reference\_with](common_reference_with "cpp/concepts/common reference with")
(C++20) | specifies that two types share a common reference type (concept) |
cpp std::relation std::relation
=============
| Defined in header `[<concepts>](../header/concepts "cpp/header/concepts")` | | |
| --- | --- | --- |
|
```
template <class R, class T, class U>
concept relation =
std::predicate<R, T, T> && std::predicate<R, U, U> &&
std::predicate<R, T, U> && std::predicate<R, U, T>;
```
| (1) | (since C++20) |
The concept `relation<R, T, U>` specifies that `R` defines a binary relation over the set of expressions whose type and value category are those encoded by either `T` or `U`.
cpp std::char_traits std::char\_traits
=================
| Defined in header `[<string>](../header/string "cpp/header/string")` | | |
| --- | --- | --- |
|
```
template<
class CharT
> class char_traits;
```
| | |
The `char_traits` class is a traits class template that abstracts basic character and string operations for a given character type. The defined operation set is such that generic algorithms almost always can be implemented in terms of it. It is thus possible to use such algorithms with almost any possible character or string type, just by supplying a customized `char_traits` class.
The `char_traits` class template serves as a basis for explicit instantiations. The user can [provide a specialization](../language/extending_std "cpp/language/extending std") for any custom character types. Several specializations are defined for the standard character types.
If an operation on traits emits an exception, the behavior is undefined.
### Standard specializations
Member typedefs of standard specializations are as follows.
| Specialization | `char_type` | `int_type` | `pos_type` |
| --- | --- | --- | --- |
| `std::char_traits<char>` | `char` | `int` | `[std::streampos](../io/fpos "cpp/io/fpos")` |
| `std::char_traits<wchar_t>` | `wchar_t` | `std::wint_t` | `[std::wstreampos](../io/fpos "cpp/io/fpos")` |
| `std::char_traits<char16_t>` (C++11) | `char16_t` | `[std::uint\_least16\_t](../types/integer "cpp/types/integer")` | `[std::u16streampos](../io/fpos "cpp/io/fpos")` |
| `std::char_traits<char32_t>` (C++11) | `char32_t` | `[std::uint\_least32\_t](../types/integer "cpp/types/integer")` | `[std::u32streampos](../io/fpos "cpp/io/fpos")` |
| `std::char_traits<char8_t>` (C++20) | `char8_t` | `unsigned int` | `[std::u8streampos](../io/fpos "cpp/io/fpos")` |
| Member type | Definition (same among all standard specializations) |
| --- | --- |
| `off_type` | `[std::streamoff](../io/streamoff "cpp/io/streamoff")` |
| `state_type` | `[std::mbstate\_t](multibyte/mbstate_t "cpp/string/multibyte/mbstate t")` |
| `comparison_category` (C++20) | `std::strong_ordering` |
The semantics of the member functions of standard specializations are defined are as follows.
| Specialization | `assign` | `eq` | `lt` | `eof` |
| --- | --- | --- | --- | --- |
| `std::char_traits<char>` | `=` | `==` for `unsigned char` | `<` for `unsigned char` | `[EOF](../io/c "cpp/io/c")` |
| `std::char_traits<wchar_t>` | `=` | `==` | `<` | `WEOF` |
| `std::char_traits<char16_t>` (C++11) | `=` | `==` | `<` | invalid UTF-16 code unit |
| `std::char_traits<char32_t>` (C++11) | `=` | `==` | `<` | invalid UTF-32 code unit |
| `std::char_traits<char8_t>` (C++20) | `=` | `==` | `<` | invalid UTF-8 code unit |
Standard specializations of `char_traits` class template satisfy the requirements of [CharTraits](../named_req/chartraits "cpp/named req/CharTraits").
### Member types
| Type | Definition |
| --- | --- |
| `char_type` | `CharT` |
| `int_type` | an integer type that can hold all values of `char_type` plus `EOF` |
| `off_type` | *implementation-defined* |
| `pos_type` | *implementation-defined* |
| `state_type` | *implementation-defined* |
### Member functions
| | |
| --- | --- |
| [assign](char_traits/assign "cpp/string/char traits/assign")
[static] | assigns a character (public static member function) |
| [eqlt](char_traits/cmp "cpp/string/char traits/cmp")
[static] | compares two characters (public static member function) |
| [move](char_traits/move "cpp/string/char traits/move")
[static] | moves one character sequence onto another (public static member function) |
| [copy](char_traits/copy "cpp/string/char traits/copy")
[static] | copies a character sequence (public static member function) |
| [compare](char_traits/compare "cpp/string/char traits/compare")
[static] | lexicographically compares two character sequences (public static member function) |
| [length](char_traits/length "cpp/string/char traits/length")
[static] | returns the length of a character sequence (public static member function) |
| [find](char_traits/find "cpp/string/char traits/find")
[static] | finds a character in a character sequence (public static member function) |
| [to\_char\_type](char_traits/to_char_type "cpp/string/char traits/to char type")
[static] | converts `int_type` to equivalent `char_type` (public static member function) |
| [to\_int\_type](char_traits/to_int_type "cpp/string/char traits/to int type")
[static] | converts `char_type` to equivalent `int_type` (public static member function) |
| [eq\_int\_type](char_traits/eq_int_type "cpp/string/char traits/eq int type")
[static] | compares two `int_type` values (public static member function) |
| [eof](char_traits/eof "cpp/string/char traits/eof")
[static] | returns an *eof* value (public static member function) |
| [not\_eof](char_traits/not_eof "cpp/string/char traits/not eof")
[static] | checks whether a character is *eof* value (public static member function) |
### Example
User-defined character traits may be used to provide [case-insensitive comparison](http://www.gotw.ca/gotw/029.htm).
```
#include <string>
#include <string_view>
#include <iostream>
#include <cctype>
struct ci_char_traits : public std::char_traits<char> {
static char to_upper(char ch) {
return std::toupper((unsigned char) ch);
}
static bool eq(char c1, char c2) {
return to_upper(c1) == to_upper(c2);
}
static bool lt(char c1, char c2) {
return to_upper(c1) < to_upper(c2);
}
static int compare(const char* s1, const char* s2, std::size_t n) {
while ( n-- != 0 ) {
if ( to_upper(*s1) < to_upper(*s2) ) return -1;
if ( to_upper(*s1) > to_upper(*s2) ) return 1;
++s1; ++s2;
}
return 0;
}
static const char* find(const char* s, std::size_t n, char a) {
auto const ua (to_upper(a));
while ( n-- != 0 )
{
if (to_upper(*s) == ua)
return s;
s++;
}
return nullptr;
}
};
template<class DstTraits, class CharT, class SrcTraits>
constexpr std::basic_string_view<CharT, DstTraits>
traits_cast(const std::basic_string_view<CharT, SrcTraits> src) noexcept
{
return {src.data(), src.size()};
}
int main()
{
using namespace std::literals;
constexpr auto s1 = "Hello"sv;
constexpr auto s2 = "heLLo"sv;
if (traits_cast<ci_char_traits>(s1) == traits_cast<ci_char_traits>(s2))
std::cout << s1 << " and " << s2 << " are equal\n";
}
```
Output:
```
Hello and heLLo are equal
```
### See also
| | |
| --- | --- |
| [basic\_string](basic_string "cpp/string/basic string") | stores and manipulates sequences of characters (class template) |
| programming_docs |
cpp std::basic_string std::basic\_string
==================
| Defined in header `[<string>](../header/string "cpp/header/string")` | | |
| --- | --- | --- |
|
```
template<
class CharT,
class Traits = std::char_traits<CharT>,
class Allocator = std::allocator<CharT>
> class basic_string;
```
| (1) | |
|
```
namespace pmr {
template <class CharT, class Traits = std::char_traits<CharT>>
using basic_string = std::basic_string< CharT, Traits,
std::pmr::polymorphic_allocator<CharT> >;
}
```
| (2) | (since C++17) |
The class template `basic_string` stores and manipulates sequences of [`char`](../language/types#Character_types "cpp/language/types")-like objects, which are non-array objects of [trivial](../named_req/trivialtype "cpp/named req/TrivialType") [standard-layout](../named_req/standardlayouttype "cpp/named req/StandardLayoutType") type. The class is dependent neither on the character type nor on the nature of operations on that type. The definitions of the operations are supplied via the `Traits` template parameter - a specialization of `[std::char\_traits](char_traits "cpp/string/char traits")` or a compatible traits class. `Traits::char_type` and `CharT` must name the same type; otherwise the program is ill-formed.
The elements of a `basic_string` are stored contiguously, that is, for a `basic_string` `s`, `&*(s.begin() + n) == &*s.begin() + n` for any n in `[0, s.size())`, or, equivalently, a pointer to `s[0]` can be passed to functions that expect a pointer to the first element of a null-terminated (since C++11)`CharT[]` array.
`std::basic_string` satisfies the requirements of [AllocatorAwareContainer](../named_req/allocatorawarecontainer "cpp/named req/AllocatorAwareContainer") (except that customized `construct`/`destroy` are not used for construction/destruction of elements), [SequenceContainer](../named_req/sequencecontainer "cpp/named req/SequenceContainer") and [ContiguousContainer](../named_req/contiguouscontainer "cpp/named req/ContiguousContainer") (since C++17).
| | |
| --- | --- |
| Member functions of `std::basic_string` are `constexpr`: it is possible to create and use `std::string` objects in the evaluation of a constant expression.
However, `std::string` objects generally cannot be `constexpr`, because any dynamically allocated storage must be released in the same evaluation of constant expression. | (since C++20) |
Several typedefs for common character types are provided:
| Defined in header `[<string>](../header/string "cpp/header/string")` |
| --- |
| Type | Definition |
| `std::string` | `std::basic_string<char>` |
| `std::wstring` | `std::basic_string<wchar_t>` |
| `std::u8string` (C++20) | `std::basic_string<char8_t>` |
| `std::u16string` (C++11) | `std::basic_string<char16_t>` |
| `std::u32string` (C++11) | `std::basic_string<char32_t>` |
| `std::pmr::string` (C++17) | `std::pmr::basic_string<char>` |
| `std::pmr::wstring` (C++17) | `std::pmr::basic_string<wchar_t>` |
| `std::pmr::u8string` (C++20) | `std::pmr::basic_string<char8_t>` |
| `std::pmr::u16string` (C++17) | `std::pmr::basic_string<char16_t>` |
| `std::pmr::u32string` (C++17) | `std::pmr::basic_string<char32_t>` |
### Template parameters
| | | |
| --- | --- | --- |
| CharT | - | character type |
| Traits | - | traits class specifying the operations on the character type |
| Allocator | - | [Allocator](../named_req/allocator "cpp/named req/Allocator") type used to allocate internal storage |
### Member types
| Member type | Definition |
| --- | --- |
| `traits_type` | `Traits` |
| `value_type` | `CharT` |
| `allocator_type` | `Allocator` |
| `size_type` |
| | |
| --- | --- |
| `Allocator::size_type` | (until C++11) |
| `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<Allocator>::size\_type` | (since C++11) |
|
| `difference_type` |
| | |
| --- | --- |
| `Allocator::difference_type` | (until C++11) |
| `[std::allocator\_traits](http://en.cppreference.com/w/cpp/memory/allocator_traits)<Allocator>::difference\_type` | (since C++11) |
|
| `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)](basic_string/basic_string "cpp/string/basic string/basic string") | constructs a `basic_string` (public member function) |
| (destructor) | destroys the string, deallocating internal storage if used (public member function) |
| [operator=](basic_string/operator= "cpp/string/basic string/operator=") | assigns values to the string (public member function) |
| [assign](basic_string/assign "cpp/string/basic string/assign") | assign characters to a string (public member function) |
| [get\_allocator](basic_string/get_allocator "cpp/string/basic string/get allocator") | returns the associated allocator (public member function) |
| Element access |
| [at](basic_string/at "cpp/string/basic string/at") | accesses the specified character with bounds checking (public member function) |
| [operator[]](basic_string/operator_at "cpp/string/basic string/operator at") | accesses the specified character (public member function) |
| [front](basic_string/front "cpp/string/basic string/front")
(C++11) | accesses the first character (public member function) |
| [back](basic_string/back "cpp/string/basic string/back")
(C++11) | accesses the last character (public member function) |
| [data](basic_string/data "cpp/string/basic string/data") | returns a pointer to the first character of a string (public member function) |
| [c\_str](basic_string/c_str "cpp/string/basic string/c str") | returns a non-modifiable standard C character array version of the string (public member function) |
| [operator basic\_string\_view](basic_string/operator_basic_string_view "cpp/string/basic string/operator basic string view")
(C++17) | returns a non-modifiable string\_view into the entire string (public member function) |
| Iterators |
| [begincbegin](basic_string/begin "cpp/string/basic string/begin")
(C++11) | returns an iterator to the beginning (public member function) |
| [end cend](basic_string/end "cpp/string/basic string/end")
(C++11) | returns an iterator to the end (public member function) |
| [rbegin crbegin](basic_string/rbegin "cpp/string/basic string/rbegin")
(C++11) | returns a reverse iterator to the beginning (public member function) |
| [rend crend](basic_string/rend "cpp/string/basic string/rend")
(C++11) | returns a reverse iterator to the end (public member function) |
| Capacity |
| [empty](basic_string/empty "cpp/string/basic string/empty") | checks whether the string is empty (public member function) |
| [sizelength](basic_string/size "cpp/string/basic string/size") | returns the number of characters (public member function) |
| [max\_size](basic_string/max_size "cpp/string/basic string/max size") | returns the maximum number of characters (public member function) |
| [reserve](basic_string/reserve "cpp/string/basic string/reserve") | reserves storage (public member function) |
| [capacity](basic_string/capacity "cpp/string/basic string/capacity") | returns the number of characters that can be held in currently allocated storage (public member function) |
| [shrink\_to\_fit](basic_string/shrink_to_fit "cpp/string/basic string/shrink to fit")
(C++11) | reduces memory usage by freeing unused memory (public member function) |
| Operations |
| [clear](basic_string/clear "cpp/string/basic string/clear") | clears the contents (public member function) |
| [insert](basic_string/insert "cpp/string/basic string/insert") | inserts characters (public member function) |
| [erase](basic_string/erase "cpp/string/basic string/erase") | removes characters (public member function) |
| [push\_back](basic_string/push_back "cpp/string/basic string/push back") | appends a character to the end (public member function) |
| [pop\_back](basic_string/pop_back "cpp/string/basic string/pop back")
(C++11) | removes the last character (public member function) |
| [append](basic_string/append "cpp/string/basic string/append") | appends characters to the end (public member function) |
| [operator+=](basic_string/operator_plus_= "cpp/string/basic string/operator+=") | appends characters to the end (public member function) |
| [compare](basic_string/compare "cpp/string/basic string/compare") | compares two strings (public member function) |
| [starts\_with](basic_string/starts_with "cpp/string/basic string/starts with")
(C++20) | checks if the string starts with the given prefix (public member function) |
| [ends\_with](basic_string/ends_with "cpp/string/basic string/ends with")
(C++20) | checks if the string ends with the given suffix (public member function) |
| [contains](basic_string/contains "cpp/string/basic string/contains")
(C++23) | checks if the string contains the given substring or character (public member function) |
| [replace](basic_string/replace "cpp/string/basic string/replace") | replaces specified portion of a string (public member function) |
| [substr](basic_string/substr "cpp/string/basic string/substr") | returns a substring (public member function) |
| [copy](basic_string/copy "cpp/string/basic string/copy") | copies characters (public member function) |
| [resize](basic_string/resize "cpp/string/basic string/resize") | changes the number of characters stored (public member function) |
| [resize\_and\_overwrite](basic_string/resize_and_overwrite "cpp/string/basic string/resize and overwrite")
(C++23) | changes the number of characters stored and possibly overwrites indeterminate contents via user-provided operation (public member function) |
| [swap](basic_string/swap "cpp/string/basic string/swap") | swaps the contents (public member function) |
| Search |
| [find](basic_string/find "cpp/string/basic string/find") | find characters in the string (public member function) |
| [rfind](basic_string/rfind "cpp/string/basic string/rfind") | find the last occurrence of a substring (public member function) |
| [find\_first\_of](basic_string/find_first_of "cpp/string/basic string/find first of") | find first occurrence of characters (public member function) |
| [find\_first\_not\_of](basic_string/find_first_not_of "cpp/string/basic string/find first not of") | find first absence of characters (public member function) |
| [find\_last\_of](basic_string/find_last_of "cpp/string/basic string/find last of") | find last occurrence of characters (public member function) |
| [find\_last\_not\_of](basic_string/find_last_not_of "cpp/string/basic string/find last not of") | find last absence of characters (public member function) |
| Constants |
| [npos](basic_string/npos "cpp/string/basic string/npos")
[static] | special value. The exact meaning depends on the context (public static member constant) |
### Non-member functions
| | |
| --- | --- |
| [operator+](basic_string/operator_plus_ "cpp/string/basic string/operator+") | concatenates two strings or a string and a char (function template) |
| [operator==operator!=operator<operator>operator<=operator>=operator<=>](basic_string/operator_cmp "cpp/string/basic string/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 two strings (function template) |
| [std::swap(std::basic\_string)](basic_string/swap2 "cpp/string/basic string/swap2") | specializes the `[std::swap](../algorithm/swap "cpp/algorithm/swap")` algorithm (function template) |
| [erase(std::basic\_string)erase\_if(std::basic\_string)](basic_string/erase2 "cpp/string/basic string/erase2")
(C++20) | Erases all elements satisfying specific criteria (function template) |
| Input/output |
| [operator<<operator>>](basic_string/operator_ltltgtgt "cpp/string/basic string/operator ltltgtgt") | performs stream input and output on strings (function template) |
| [getline](basic_string/getline "cpp/string/basic string/getline") | read data from an I/O stream into a string (function template) |
| Numeric conversions |
| [stoistolstoll](basic_string/stol "cpp/string/basic string/stol")
(C++11)(C++11)(C++11) | converts a string to a signed integer (function) |
| [stoulstoull](basic_string/stoul "cpp/string/basic string/stoul")
(C++11)(C++11) | converts a string to an unsigned integer (function) |
| [stofstodstold](basic_string/stof "cpp/string/basic string/stof")
(C++11)(C++11)(C++11) | converts a string to a floating point value (function) |
| [to\_string](basic_string/to_string "cpp/string/basic string/to string")
(C++11) | converts an integral or floating point value to `string` (function) |
| [to\_wstring](basic_string/to_wstring "cpp/string/basic string/to wstring")
(C++11) | converts an integral or floating point value to `wstring` (function) |
### Literals
| Defined in inline namespace `std::literals::string_literals` |
| --- |
| [operator""s](basic_string/operator%22%22s "cpp/string/basic string/operator\"\"s")
(C++14) | Converts a character array literal to `basic_string` (function) |
### Helper classes
| | |
| --- | --- |
| [std::hash<std::string>std::hash<std::u8string>std::hash<std::u16string>std::hash<std::u32string>std::hash<std::wstring>std::hash<std::pmr::string>std::hash<std::pmr::u8string>std::hash<std::pmr::u16string>std::hash<std::pmr::u32string>std::hash<std::pmr::wstring>](basic_string/hash "cpp/string/basic string/hash")
(C++11)(C++20)(C++11)(C++11)(C++11)(C++17)(C++20)(C++17)(C++17)(C++17) | hash support for strings (class template specialization) |
### [Deduction guides](basic_string/deduction_guides "cpp/string/basic string/deduction guides") (since C++17)
### Notes
Although it is required that customized `construct` or `destroy` is used when constructing or destroying elements of `std::basic_string` until C++23, all implementations only used the default mechanism. The requirement is corrected by [P1072R10](https://wg21.link/P1072R10) to match existing practice.
| [Feature-test](../utility/feature_test "cpp/utility/feature test") macro | Value | Std | Comment |
| --- | --- | --- | --- |
| [`__cpp_lib_string_udls`](../feature_test#Library_features "cpp/feature test") | `201304L` | (C++14) | [User-defined literals for string types](#Literals) |
| [`__cpp_lib_string_contains`](../feature_test#Library_features "cpp/feature test") | `202011L` | (C++23) | [`contains`](basic_string/contains "cpp/string/basic string/contains") |
| [`__cpp_lib_string_resize_and_overwrite`](../feature_test#Library_features "cpp/feature test") | `202110L` | (C++23) | [`resize_and_overwrite`](basic_string/resize_and_overwrite "cpp/string/basic string/resize and overwrite") |
### Example
```
#include <iostream>
#include <string>
int main()
{
using namespace std::literals;
// Creating a string from const char*
std::string str1 = "hello";
// Creating a string using string literal
auto str2 = "world"s;
// Concatenating strings
std::string str3 = str1 + " " + str2;
// Print out the result
std::cout << str3 << '\n';
std::string::size_type pos = str3.find(" ");
str1 = str3.substr(pos + 1); // the part after the space
str2 = str3.substr(0, pos); // the part till the space
std::cout << str1 << ' ' << str2 << '\n';
// Accessing an element using subscript operator[]
std::cout << str1[0] << '\n';
str1[0] = 'W';
std::cout << str1 << '\n';
}
```
Output:
```
hello world
world hello
w
World
```
### See also
| | |
| --- | --- |
| [basic\_string\_view](basic_string_view "cpp/string/basic string view")
(C++17) | read-only string view (class template) |
cpp Null-terminated byte strings Null-terminated byte strings
============================
A null-terminated byte string (NTBS) is a sequence of nonzero bytes followed by a byte with value zero (the terminating null character). Each byte in a byte string encodes one character of some character set. For example, the character array `{'\x63', '\x61', '\x74', '\0'}` is an NTBS holding the string `"cat"` in ASCII encoding.
### Functions
| |
| --- |
| Character classification |
| Defined in header `[<cctype>](../header/cctype "cpp/header/cctype")` |
| [isalnum](byte/isalnum "cpp/string/byte/isalnum") | checks if a character is alphanumeric (function) |
| [isalpha](byte/isalpha "cpp/string/byte/isalpha") | checks if a character is alphabetic (function) |
| [islower](byte/islower "cpp/string/byte/islower") | checks if a character is lowercase (function) |
| [isupper](byte/isupper "cpp/string/byte/isupper") | checks if a character is an uppercase character (function) |
| [isdigit](byte/isdigit "cpp/string/byte/isdigit") | checks if a character is a digit (function) |
| [isxdigit](byte/isxdigit "cpp/string/byte/isxdigit") | checks if a character is a hexadecimal character (function) |
| [iscntrl](byte/iscntrl "cpp/string/byte/iscntrl") | checks if a character is a control character (function) |
| [isgraph](byte/isgraph "cpp/string/byte/isgraph") | checks if a character is a graphical character (function) |
| [isspace](byte/isspace "cpp/string/byte/isspace") | checks if a character is a space character (function) |
| [isblank](byte/isblank "cpp/string/byte/isblank")
(C++11) | checks if a character is a blank character (function) |
| [isprint](byte/isprint "cpp/string/byte/isprint") | checks if a character is a printing character (function) |
| [ispunct](byte/ispunct "cpp/string/byte/ispunct") | checks if a character is a punctuation character (function) |
| Character manipulation |
| [tolower](byte/tolower "cpp/string/byte/tolower") | converts a character to lowercase (function) |
| [toupper](byte/toupper "cpp/string/byte/toupper") | converts a character to uppercase (function) |
| ASCII values | characters | [`iscntrl`](byte/iscntrl "cpp/string/byte/iscntrl") [`iswcntrl`](wide/iswcntrl "cpp/string/wide/iswcntrl"). | [`isprint`](byte/isprint "cpp/string/byte/isprint") [`iswprint`](wide/iswprint "cpp/string/wide/iswprint"). | [`isspace`](byte/isspace "cpp/string/byte/isspace") [`iswspace`](wide/iswspace "cpp/string/wide/iswspace"). | [`isblank`](byte/isblank "cpp/string/byte/isblank") [`iswblank`](wide/iswblank "cpp/string/wide/iswblank"). | [`isgraph`](byte/isgraph "cpp/string/byte/isgraph") [`iswgraph`](wide/iswgraph "cpp/string/wide/iswgraph"). | [`ispunct`](byte/ispunct "cpp/string/byte/ispunct") [`iswpunct`](wide/iswpunct "cpp/string/wide/iswpunct"). | [`isalnum`](byte/isalnum "cpp/string/byte/isalnum") [`iswalnum`](wide/iswalnum "cpp/string/wide/iswalnum"). | [`isalpha`](byte/isalpha "cpp/string/byte/isalpha") [`iswalpha`](wide/iswalpha "cpp/string/wide/iswalpha"). | [`isupper`](byte/isupper "cpp/string/byte/isupper") [`iswupper`](wide/iswupper "cpp/string/wide/iswupper"). | [`islower`](byte/islower "cpp/string/byte/islower") [`iswlower`](wide/iswlower "cpp/string/wide/iswlower"). | [`isdigit`](byte/isdigit "cpp/string/byte/isdigit") [`iswdigit`](wide/iswdigit "cpp/string/wide/iswdigit"). | [`isxdigit`](byte/isxdigit "cpp/string/byte/isxdigit") [`iswxdigit`](wide/iswxdigit "cpp/string/wide/iswxdigit"). |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| decimal | hexadecimal | octal |
| 0โ8 | `\x0`โ`\x8` | `\0`โ`\10` | control codes (`NUL`, etc.) | **`โ 0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 9 | `\x9` | `\11` | tab (`\t`) | **`โ 0`** | **`0`** | **`โ 0`** | **`โ 0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 10โ13 | `\xA`โ`\xD` | `\12`โ`\15` | whitespaces (`\n`, `\v`, `\f`, `\r`) | **`โ 0`** | **`0`** | **`โ 0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 14โ31 | `\xE`โ`\x1F` | `\16`โ`\37` | control codes | **`โ 0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 32 | `\x20` | `\40` | space | **`0`** | **`โ 0`** | **`โ 0`** | **`โ 0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 33โ47 | `\x21`โ`\x2F` | `\41`โ`\57` | `!"#$%&'()*+,-./` | **`0`** | **`โ 0`** | **`0`** | **`0`** | **`โ 0`** | **`โ 0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 48โ57 | `\x30`โ`\x39` | `\60`โ`\71` | `0123456789` | **`0`** | **`โ 0`** | **`0`** | **`0`** | **`โ 0`** | **`0`** | **`โ 0`** | **`0`** | **`0`** | **`0`** | **`โ 0`** | **`โ 0`** |
| 58โ64 | `\x3A`โ`\x40` | `\72`โ`\100` | `:;<=>?@` | **`0`** | **`โ 0`** | **`0`** | **`0`** | **`โ 0`** | **`โ 0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 65โ70 | `\x41`โ`\x46` | `\101`โ`\106` | `ABCDEF` | **`0`** | **`โ 0`** | **`0`** | **`0`** | **`โ 0`** | **`0`** | **`โ 0`** | **`โ 0`** | **`โ 0`** | **`0`** | **`0`** | **`โ 0`** |
| 71โ90 | `\x47`โ`\x5A` | `\107`โ`\132` | `GHIJKLMNOP``QRSTUVWXYZ` | **`0`** | **`โ 0`** | **`0`** | **`0`** | **`โ 0`** | **`0`** | **`โ 0`** | **`โ 0`** | **`โ 0`** | **`0`** | **`0`** | **`0`** |
| 91โ96 | `\x5B`โ`\x60` | `\133`โ`\140` | `[\]^_`` | **`0`** | **`โ 0`** | **`0`** | **`0`** | **`โ 0`** | **`โ 0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 97โ102 | `\x61`โ`\x66` | `\141`โ`\146` | `abcdef` | **`0`** | **`โ 0`** | **`0`** | **`0`** | **`โ 0`** | **`0`** | **`โ 0`** | **`โ 0`** | **`0`** | **`โ 0`** | **`0`** | **`โ 0`** |
| 103โ122 | `\x67`โ`\x7A` | `\147`โ`\172` | `ghijklmnop``qrstuvwxyz` | **`0`** | **`โ 0`** | **`0`** | **`0`** | **`โ 0`** | **`0`** | **`โ 0`** | **`โ 0`** | **`0`** | **`โ 0`** | **`0`** | **`0`** |
| 123โ126 | `\x7B`โ`\x7E` | `\172`โ`\176` | `{|}~` | **`0`** | **`โ 0`** | **`0`** | **`0`** | **`โ 0`** | **`โ 0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 127 | `\x7F` | `\177` | backspace character (`DEL`) | **`โ 0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| |
| --- |
| Conversions to numeric formats |
| Defined in header `[<cstdlib>](../header/cstdlib "cpp/header/cstdlib")` |
| [atof](byte/atof "cpp/string/byte/atof") | converts a byte string to a floating point value (function) |
| [atoiatolatoll](byte/atoi "cpp/string/byte/atoi")
(C++11) | converts a byte string to an integer value (function) |
| [strtolstrtoll](byte/strtol "cpp/string/byte/strtol")
(C++11) | converts a byte string to an integer value (function) |
| [strtoulstrtoull](byte/strtoul "cpp/string/byte/strtoul")
(C++11) | converts a byte string to an unsigned integer value (function) |
| [strtofstrtodstrtold](byte/strtof "cpp/string/byte/strtof") | converts a byte string to a floating point value (function) |
| Defined in header `[<cinttypes>](../header/cinttypes "cpp/header/cinttypes")` |
| [strtoimaxstrtoumax](byte/strtoimax "cpp/string/byte/strtoimax")
(C++11)(C++11) | converts a byte string to `[std::intmax\_t](../types/integer "cpp/types/integer")` or `[std::uintmax\_t](../types/integer "cpp/types/integer")` (function) |
| String manipulation |
| Defined in header `[<cstring>](../header/cstring "cpp/header/cstring")` |
| [strcpy](byte/strcpy "cpp/string/byte/strcpy") | copies one string to another (function) |
| [strncpy](byte/strncpy "cpp/string/byte/strncpy") | copies a certain amount of characters from one string to another (function) |
| [strcat](byte/strcat "cpp/string/byte/strcat") | concatenates two strings (function) |
| [strncat](byte/strncat "cpp/string/byte/strncat") | concatenates a certain amount of characters of two strings (function) |
| [strxfrm](byte/strxfrm "cpp/string/byte/strxfrm") | transform a string so that strcmp would produce the same result as strcoll (function) |
| String examination |
| Defined in header `[<cstring>](../header/cstring "cpp/header/cstring")` |
| [strlen](byte/strlen "cpp/string/byte/strlen") | returns the length of a given string (function) |
| [strcmp](byte/strcmp "cpp/string/byte/strcmp") | compares two strings (function) |
| [strncmp](byte/strncmp "cpp/string/byte/strncmp") | compares a certain number of characters from two strings (function) |
| [strcoll](byte/strcoll "cpp/string/byte/strcoll") | compares two strings in accordance to the current locale (function) |
| [strchr](byte/strchr "cpp/string/byte/strchr") | finds the first occurrence of a character (function) |
| [strrchr](byte/strrchr "cpp/string/byte/strrchr") | finds the last occurrence of a character (function) |
| [strspn](byte/strspn "cpp/string/byte/strspn") | returns the length of the maximum initial segment that consists of only the characters found in another byte string (function) |
| [strcspn](byte/strcspn "cpp/string/byte/strcspn") | returns the length of the maximum initial segment that consists of only the characters not found in another byte string (function) |
| [strpbrk](byte/strpbrk "cpp/string/byte/strpbrk") | finds the first location of any character from a set of separators (function) |
| [strstr](byte/strstr "cpp/string/byte/strstr") | finds the first occurrence of a substring of characters (function) |
| [strtok](byte/strtok "cpp/string/byte/strtok") | finds the next token in a byte string (function) |
| Character array functions |
| Defined in header `[<cstring>](../header/cstring "cpp/header/cstring")` |
| [memchr](byte/memchr "cpp/string/byte/memchr") | searches an array for the first occurrence of a character (function) |
| [memcmp](byte/memcmp "cpp/string/byte/memcmp") | compares two buffers (function) |
| [memset](byte/memset "cpp/string/byte/memset") | fills a buffer with a character (function) |
| [memcpy](byte/memcpy "cpp/string/byte/memcpy") | copies one buffer to another (function) |
| [memmove](byte/memmove "cpp/string/byte/memmove") | moves one buffer to another (function) |
| Miscellaneous |
| Defined in header `[<cstring>](../header/cstring "cpp/header/cstring")` |
| [strerror](byte/strerror "cpp/string/byte/strerror") | returns a text version of a given error code (function) |
### See also
| |
| --- |
| [C documentation](https://en.cppreference.com/w/c/string/byte "c/string/byte") for `Null`-terminated byte strings |
| programming_docs |
cpp Null-terminated wide strings Null-terminated wide strings
============================
A null-terminated wide string is a sequence of valid wide characters, ending with a null character.
### Functions
| |
| --- |
| Character classification |
| Defined in header `[<cwctype>](../header/cwctype "cpp/header/cwctype")` |
| [iswalnum](wide/iswalnum "cpp/string/wide/iswalnum") | checks if a wide character is alphanumeric (function) |
| [iswalpha](wide/iswalpha "cpp/string/wide/iswalpha") | checks if a wide character is alphabetic (function) |
| [iswlower](wide/iswlower "cpp/string/wide/iswlower") | checks if a wide character is lowercase (function) |
| [iswupper](wide/iswupper "cpp/string/wide/iswupper") | checks if a wide character is an uppercase character (function) |
| [iswdigit](wide/iswdigit "cpp/string/wide/iswdigit") | checks if a wide character is a digit (function) |
| [iswxdigit](wide/iswxdigit "cpp/string/wide/iswxdigit") | checks if a character is a hexadecimal character (function) |
| [iswcntrl](wide/iswcntrl "cpp/string/wide/iswcntrl") | checks if a wide character is a control character (function) |
| [iswgraph](wide/iswgraph "cpp/string/wide/iswgraph") | checks if a wide character is a graphical character (function) |
| [iswspace](wide/iswspace "cpp/string/wide/iswspace") | checks if a wide character is a space character (function) |
| [iswblank](wide/iswblank "cpp/string/wide/iswblank")
(C++11) | checks if a wide character is a blank character (function) |
| [iswprint](wide/iswprint "cpp/string/wide/iswprint") | checks if a wide character is a printing character (function) |
| [iswpunct](wide/iswpunct "cpp/string/wide/iswpunct") | checks if a wide character is a punctuation character (function) |
| [iswctype](wide/iswctype "cpp/string/wide/iswctype") | classifies a wide character according to the specified LC\_CTYPE category (function) |
| [wctype](wide/wctype "cpp/string/wide/wctype") | looks up a character classification category in the current C locale (function) |
| Character manipulation |
| Defined in header `[<cwctype>](../header/cwctype "cpp/header/cwctype")` |
| [towlower](wide/towlower "cpp/string/wide/towlower") | converts a wide character to lowercase (function) |
| [towupper](wide/towupper "cpp/string/wide/towupper") | converts a wide character to uppercase (function) |
| [towctrans](wide/towctrans "cpp/string/wide/towctrans") | performs character mapping according to the specified LC\_CTYPE mapping category (function) |
| [wctrans](wide/wctrans "cpp/string/wide/wctrans") | looks up a character mapping category in the current C locale (function) |
| ASCII values | characters | [`iscntrl`](byte/iscntrl "cpp/string/byte/iscntrl") [`iswcntrl`](wide/iswcntrl "cpp/string/wide/iswcntrl"). | [`isprint`](byte/isprint "cpp/string/byte/isprint") [`iswprint`](wide/iswprint "cpp/string/wide/iswprint"). | [`isspace`](byte/isspace "cpp/string/byte/isspace") [`iswspace`](wide/iswspace "cpp/string/wide/iswspace"). | [`isblank`](byte/isblank "cpp/string/byte/isblank") [`iswblank`](wide/iswblank "cpp/string/wide/iswblank"). | [`isgraph`](byte/isgraph "cpp/string/byte/isgraph") [`iswgraph`](wide/iswgraph "cpp/string/wide/iswgraph"). | [`ispunct`](byte/ispunct "cpp/string/byte/ispunct") [`iswpunct`](wide/iswpunct "cpp/string/wide/iswpunct"). | [`isalnum`](byte/isalnum "cpp/string/byte/isalnum") [`iswalnum`](wide/iswalnum "cpp/string/wide/iswalnum"). | [`isalpha`](byte/isalpha "cpp/string/byte/isalpha") [`iswalpha`](wide/iswalpha "cpp/string/wide/iswalpha"). | [`isupper`](byte/isupper "cpp/string/byte/isupper") [`iswupper`](wide/iswupper "cpp/string/wide/iswupper"). | [`islower`](byte/islower "cpp/string/byte/islower") [`iswlower`](wide/iswlower "cpp/string/wide/iswlower"). | [`isdigit`](byte/isdigit "cpp/string/byte/isdigit") [`iswdigit`](wide/iswdigit "cpp/string/wide/iswdigit"). | [`isxdigit`](byte/isxdigit "cpp/string/byte/isxdigit") [`iswxdigit`](wide/iswxdigit "cpp/string/wide/iswxdigit"). |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| decimal | hexadecimal | octal |
| 0โ8 | `\x0`โ`\x8` | `\0`โ`\10` | control codes (`NUL`, etc.) | **`โ 0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 9 | `\x9` | `\11` | tab (`\t`) | **`โ 0`** | **`0`** | **`โ 0`** | **`โ 0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 10โ13 | `\xA`โ`\xD` | `\12`โ`\15` | whitespaces (`\n`, `\v`, `\f`, `\r`) | **`โ 0`** | **`0`** | **`โ 0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 14โ31 | `\xE`โ`\x1F` | `\16`โ`\37` | control codes | **`โ 0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 32 | `\x20` | `\40` | space | **`0`** | **`โ 0`** | **`โ 0`** | **`โ 0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 33โ47 | `\x21`โ`\x2F` | `\41`โ`\57` | `!"#$%&'()*+,-./` | **`0`** | **`โ 0`** | **`0`** | **`0`** | **`โ 0`** | **`โ 0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 48โ57 | `\x30`โ`\x39` | `\60`โ`\71` | `0123456789` | **`0`** | **`โ 0`** | **`0`** | **`0`** | **`โ 0`** | **`0`** | **`โ 0`** | **`0`** | **`0`** | **`0`** | **`โ 0`** | **`โ 0`** |
| 58โ64 | `\x3A`โ`\x40` | `\72`โ`\100` | `:;<=>?@` | **`0`** | **`โ 0`** | **`0`** | **`0`** | **`โ 0`** | **`โ 0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 65โ70 | `\x41`โ`\x46` | `\101`โ`\106` | `ABCDEF` | **`0`** | **`โ 0`** | **`0`** | **`0`** | **`โ 0`** | **`0`** | **`โ 0`** | **`โ 0`** | **`โ 0`** | **`0`** | **`0`** | **`โ 0`** |
| 71โ90 | `\x47`โ`\x5A` | `\107`โ`\132` | `GHIJKLMNOP``QRSTUVWXYZ` | **`0`** | **`โ 0`** | **`0`** | **`0`** | **`โ 0`** | **`0`** | **`โ 0`** | **`โ 0`** | **`โ 0`** | **`0`** | **`0`** | **`0`** |
| 91โ96 | `\x5B`โ`\x60` | `\133`โ`\140` | `[\]^_`` | **`0`** | **`โ 0`** | **`0`** | **`0`** | **`โ 0`** | **`โ 0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 97โ102 | `\x61`โ`\x66` | `\141`โ`\146` | `abcdef` | **`0`** | **`โ 0`** | **`0`** | **`0`** | **`โ 0`** | **`0`** | **`โ 0`** | **`โ 0`** | **`0`** | **`โ 0`** | **`0`** | **`โ 0`** |
| 103โ122 | `\x67`โ`\x7A` | `\147`โ`\172` | `ghijklmnop``qrstuvwxyz` | **`0`** | **`โ 0`** | **`0`** | **`0`** | **`โ 0`** | **`0`** | **`โ 0`** | **`โ 0`** | **`0`** | **`โ 0`** | **`0`** | **`0`** |
| 123โ126 | `\x7B`โ`\x7E` | `\172`โ`\176` | `{|}~` | **`0`** | **`โ 0`** | **`0`** | **`0`** | **`โ 0`** | **`โ 0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 127 | `\x7F` | `\177` | backspace character (`DEL`) | **`โ 0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| |
| --- |
| Conversions to numeric formats |
| Defined in header `[<cwchar>](../header/cwchar "cpp/header/cwchar")` |
| [wcstolwcstoll](wide/wcstol "cpp/string/wide/wcstol") | converts a wide string to an integer value (function) |
| [wcstoulwcstoull](wide/wcstoul "cpp/string/wide/wcstoul") | converts a wide string to an unsigned integer value (function) |
| [wcstofwcstodwcstold](wide/wcstof "cpp/string/wide/wcstof") | converts a wide string to a floating point value (function) |
| Defined in header `[<cinttypes>](../header/cinttypes "cpp/header/cinttypes")` |
| [wcstoimaxwcstoumax](wide/wcstoimax "cpp/string/wide/wcstoimax")
(C++11)(C++11) | converts a wide string to `[std::intmax\_t](../types/integer "cpp/types/integer")` or `[std::uintmax\_t](../types/integer "cpp/types/integer")` (function) |
| |
| --- |
| String manipulation |
| Defined in header `[<cwchar>](../header/cwchar "cpp/header/cwchar")` |
| [wcscpy](wide/wcscpy "cpp/string/wide/wcscpy") | copies one wide string to another (function) |
| [wcsncpy](wide/wcsncpy "cpp/string/wide/wcsncpy") | copies a certain amount of wide characters from one string to another (function) |
| [wcscat](wide/wcscat "cpp/string/wide/wcscat") | appends a copy of one wide string to another (function) |
| [wcsncat](wide/wcsncat "cpp/string/wide/wcsncat") | appends a certain amount of wide characters from one wide string to another (function) |
| [wcsxfrm](wide/wcsxfrm "cpp/string/wide/wcsxfrm") | transform a wide string so that wcscmp would produce the same result as wcscoll (function) |
| String examination |
| Defined in header `[<cwchar>](../header/cwchar "cpp/header/cwchar")` |
| [wcslen](wide/wcslen "cpp/string/wide/wcslen") | returns the length of a wide string (function) |
| [wcscmp](wide/wcscmp "cpp/string/wide/wcscmp") | compares two wide strings (function) |
| [wcsncmp](wide/wcsncmp "cpp/string/wide/wcsncmp") | compares a certain amount of characters from two wide strings (function) |
| [wcscoll](wide/wcscoll "cpp/string/wide/wcscoll") | compares two wide strings in accordance to the current locale (function) |
| [wcschr](wide/wcschr "cpp/string/wide/wcschr") | finds the first occurrence of a wide character in a wide string (function) |
| [wcsrchr](wide/wcsrchr "cpp/string/wide/wcsrchr") | finds the last occurrence of a wide character in a wide string (function) |
| [wcsspn](wide/wcsspn "cpp/string/wide/wcsspn") | returns the length of the maximum initial segment that consists of only the wide characters found in another wide string (function) |
| [wcscspn](wide/wcscspn "cpp/string/wide/wcscspn") | returns the length of the maximum initial segment that consists of only the wide *not* found in another wide string (function) |
| [wcspbrk](wide/wcspbrk "cpp/string/wide/wcspbrk") | finds the first location of any wide character in one wide string, in another wide string (function) |
| [wcsstr](wide/wcsstr "cpp/string/wide/wcsstr") | finds the first occurrence of a wide string within another wide string (function) |
| [wcstok](wide/wcstok "cpp/string/wide/wcstok") | finds the next token in a wide string (function) |
| |
| --- |
| Wide character array manipulation |
| Defined in header `[<cwchar>](../header/cwchar "cpp/header/cwchar")` |
| [wmemcpy](wide/wmemcpy "cpp/string/wide/wmemcpy") | copies a certain amount of wide characters between two non-overlapping arrays (function) |
| [wmemmove](wide/wmemmove "cpp/string/wide/wmemmove") | copies a certain amount of wide characters between two, possibly overlapping, arrays (function) |
| [wmemcmp](wide/wmemcmp "cpp/string/wide/wmemcmp") | compares a certain amount of wide characters from two arrays (function) |
| [wmemchr](wide/wmemchr "cpp/string/wide/wmemchr") | finds the first occurrence of a wide character in a wide character array (function) |
| [wmemset](wide/wmemset "cpp/string/wide/wmemset") | copies the given wide character to every position in a wide character array (function) |
### Types
| Defined in header `[<cwctype>](../header/cwctype "cpp/header/cwctype")` |
| --- |
| wctrans\_t | scalar type that holds locale-specific character mapping (typedef) |
| wctype\_t | scalar type that holds locale-specific character classification (typedef) |
| Defined in header `[<cwctype>](../header/cwctype "cpp/header/cwctype")` |
| Defined in header `[<cwchar>](../header/cwchar "cpp/header/cwchar")` |
| wint\_t | integer type that can hold any valid wide character and at least one more value (typedef) |
### Macros
| Defined in header `[<cwchar>](../header/cwchar "cpp/header/cwchar")` |
| --- |
| WEOF | a non-character value of type wint\_t used to indicate errors (macro constant) |
| WCHAR\_MIN | the smallest valid value of wchar\_t (macro constant) |
| WCHAR\_MAX | the largest valid value of wchar\_t (macro constant) |
### See also
| |
| --- |
| [C documentation](https://en.cppreference.com/w/c/string/wide "c/string/wide") for `Null-terminated wide strings` |
cpp Null-terminated multibyte strings Null-terminated multibyte strings
=================================
A null-terminated multibyte string (NTMBS), or "multibyte string", is a sequence of nonzero bytes followed by a byte with value zero (the terminating null character).
Each character stored in the string may occupy more than one byte. The encoding used to represent characters in a multibyte character string is locale-specific: it may be UTF-8, GB18030, EUC-JP, Shift-JIS, etc. For example, the char array `{'\xe4','\xbd','\xa0','\xe5','\xa5','\xbd','\0'}` is an NTMBS holding the string `"ไฝ ๅฅฝ"` in UTF-8 multibyte encoding: the first three bytes encode the character ไฝ , the next three bytes encode the character ๅฅฝ. The same string encoded in GB18030 is the char array `{'\xc4', '\xe3', '\xba', '\xc3', '\0'}`, where each of the two characters is encoded as a two-byte sequence.
In some multibyte encodings, any given multibyte character sequence may represent different characters depending on the previous byte sequences, known as "shift sequences". Such encodings are known as state-dependent: knowledge of the current shift state is required to interpret each character. An NTMBS is only valid if it begins and ends in the initial shift state: if a shift sequence was used, the corresponding unshift sequence has to be present before the terminating null character. Examples of such encodings are the 7-bit JIS, BOCU-1 and [SCSU](http://www.unicode.org/reports/tr6).
A multibyte character string is layout-compatible with null-terminated byte string (NTBS), that is, can be stored, copied, and examined using the same facilities, except for calculating the number of characters. If the correct locale is in effect, I/O functions also handle multibyte strings. Multibyte strings can be converted to and from wide strings using the `[std::codecvt](../locale/codecvt "cpp/locale/codecvt")` member functions, `[std::wstring\_convert](../locale/wstring_convert "cpp/locale/wstring convert")`, or the following locale-dependent conversion functions:
### Multibyte/wide character conversions
| Defined in header `[<cstdlib>](../header/cstdlib "cpp/header/cstdlib")` |
| --- |
| [mblen](multibyte/mblen "cpp/string/multibyte/mblen") | returns the number of bytes in the next multibyte character (function) |
| [mbtowc](multibyte/mbtowc "cpp/string/multibyte/mbtowc") | converts the next multibyte character to wide character (function) |
| [wctomb](multibyte/wctomb "cpp/string/multibyte/wctomb") | converts a wide character to its multibyte representation (function) |
| [mbstowcs](multibyte/mbstowcs "cpp/string/multibyte/mbstowcs") | converts a narrow multibyte character string to wide string (function) |
| [wcstombs](multibyte/wcstombs "cpp/string/multibyte/wcstombs") | converts a wide string to narrow multibyte character string (function) |
| Defined in header `[<cwchar>](../header/cwchar "cpp/header/cwchar")` |
| [mbsinit](multibyte/mbsinit "cpp/string/multibyte/mbsinit") | checks if the mbstate\_t object represents initial shift state (function) |
| [btowc](multibyte/btowc "cpp/string/multibyte/btowc") | widens a single-byte narrow character to wide character, if possible (function) |
| [wctob](multibyte/wctob "cpp/string/multibyte/wctob") | narrows a wide character to a single-byte narrow character, if possible (function) |
| [mbrlen](multibyte/mbrlen "cpp/string/multibyte/mbrlen") | returns the number of bytes in the next multibyte character, given state (function) |
| [mbrtowc](multibyte/mbrtowc "cpp/string/multibyte/mbrtowc") | converts the next multibyte character to wide character, given state (function) |
| [wcrtomb](multibyte/wcrtomb "cpp/string/multibyte/wcrtomb") | converts a wide character to its multibyte representation, given state (function) |
| [mbsrtowcs](multibyte/mbsrtowcs "cpp/string/multibyte/mbsrtowcs") | converts a narrow multibyte character string to wide string, given state (function) |
| [wcsrtombs](multibyte/wcsrtombs "cpp/string/multibyte/wcsrtombs") | converts a wide string to narrow multibyte character string, given state (function) |
| Defined in header `[<cuchar>](../header/cuchar "cpp/header/cuchar")` |
| [mbrtoc8](multibyte/mbrtoc8 "cpp/string/multibyte/mbrtoc8")
(C++20) | converts a narrow multibyte character to UTF-8 encoding (function) |
| [c8rtomb](multibyte/c8rtomb "cpp/string/multibyte/c8rtomb")
(C++20) | converts UTF-8 string to narrow multibyte encoding (function) |
| [mbrtoc16](multibyte/mbrtoc16 "cpp/string/multibyte/mbrtoc16")
(C++11) | Converts a narrow multibyte character to UTF-16 encoding (function) |
| [c16rtomb](multibyte/c16rtomb "cpp/string/multibyte/c16rtomb")
(C++11) | convert a 16-bit wide character to narrow multibyte string (function) |
| [mbrtoc32](multibyte/mbrtoc32 "cpp/string/multibyte/mbrtoc32")
(C++11) | converts a narrow multibyte character to UTF-32 encoding (function) |
| [c32rtomb](multibyte/c32rtomb "cpp/string/multibyte/c32rtomb")
(C++11) | convert a 32-bit wide character to narrow multibyte string (function) |
### Types
| Defined in header `[<cwchar>](../header/cwchar "cpp/header/cwchar")` |
| --- |
| [mbstate\_t](multibyte/mbstate_t "cpp/string/multibyte/mbstate t") | conversion state information necessary to iterate multibyte character strings (class) |
### Macros
| Defined in header `[<climits>](../header/climits "cpp/header/climits")` |
| --- |
| MB\_LEN\_MAX | maximum number of bytes in a multibyte character (macro constant) |
| Defined in header `[<cstdlib>](../header/cstdlib "cpp/header/cstdlib")` |
| MB\_CUR\_MAX | maximum number of bytes in a multibyte character in the current C locale(macro variable) |
| Defined in header `[<cuchar>](../header/cuchar "cpp/header/cuchar")` |
| \_\_STDC\_UTF\_16\_\_
(C++11) | indicates that UTF-16 encoding is used by mbrtoc16 and c16rtomb (macro constant) |
| \_\_STDC\_UTF\_32\_\_
(C++11) | indicates that UTF-32 encoding is used by mbrtoc32 and c32rtomb (macro constant) |
### See also
| |
| --- |
| [C documentation](https://en.cppreference.com/w/c/string/multibyte "c/string/multibyte") for `Null-terminated multibyte strings` |
cpp std::basic_string_view std::basic\_string\_view
========================
| Defined in header `[<string\_view>](../header/string_view "cpp/header/string view")` | | |
| --- | --- | --- |
|
```
template<
class CharT,
class Traits = std::char_traits<CharT>
> class basic_string_view;
```
| | (since C++17) |
The class template `basic_string_view` describes an object that can refer to a constant contiguous sequence of `char`-like objects with the first element of the sequence at position zero.
| | |
| --- | --- |
| Every specialization of `std::basic_string_view` is a [TriviallyCopyable](../named_req/triviallycopyable "cpp/named req/TriviallyCopyable") type. | (since C++23) |
A typical implementation holds only two members: a pointer to constant `CharT` and a size.
Several typedefs for common character types are provided:
| Defined in header `[<string\_view>](../header/string_view "cpp/header/string view")` |
| --- |
| Type | Definition |
| `std::string_view` (C++17) | `std::basic_string_view<char>` |
| `std::wstring_view` (C++17) | `std::basic_string_view<wchar_t>` |
| `std::u8string_view` (C++20) | `std::basic_string_view<char8_t>` |
| `std::u16string_view` (C++17) | `std::basic_string_view<char16_t>` |
| `std::u32string_view` (C++17) | `std::basic_string_view<char32_t>` |
### Template parameters
| | | |
| --- | --- | --- |
| CharT | - | character type |
| Traits | - | [CharTraits](../named_req/chartraits "cpp/named req/CharTraits") class specifying the operations on the character type. Like for `basic_string`, `Traits::char_type` must name the same type as `CharT` or the program is ill-formed. |
### Member types
| Member type | Definition |
| --- | --- |
| `traits_type` | `Traits` |
| `value_type` | `CharT` |
| `pointer` | `CharT*` |
| `const_pointer` | `const CharT*` |
| `reference` | `CharT&` |
| `const_reference` | `const CharT&` |
| `const_iterator` | implementation-defined constant [LegacyRandomAccessIterator](../named_req/randomaccessiterator "cpp/named req/RandomAccessIterator"), [ConstexprIterator](../named_req/constexpriterator "cpp/named req/ConstexprIterator") (since C++20) and [LegacyContiguousIterator](../named_req/contiguousiterator "cpp/named req/ContiguousIterator") (until C++20)[`contiguous_iterator`](../iterator/contiguous_iterator "cpp/iterator/contiguous iterator") (since C++20) whose `value_type` is `CharT` |
| `iterator` | `const_iterator` |
| `const_reverse_iterator` | `[std::reverse\_iterator](http://en.cppreference.com/w/cpp/iterator/reverse_iterator)<const_iterator>` |
| `reverse_iterator` | `const_reverse_iterator` |
| `size_type` | `[std::size\_t](../types/size_t "cpp/types/size t")` |
| `difference_type` | `[std::ptrdiff\_t](../types/ptrdiff_t "cpp/types/ptrdiff t")` |
Note: `iterator` and `const_iterator` are the same type because string views are views into constant character sequences.
All requirements on the iterator types of a [Container](../named_req/container "cpp/named req/Container") applies to the `iterator` and `const_iterator` types of `basic_string_view` as well.
### Member functions
| |
| --- |
| Constructors and assignment |
| [(constructor)](basic_string_view/basic_string_view "cpp/string/basic string view/basic string view")
(C++17) | constructs a `basic_string_view` (public member function) |
| [operator=](basic_string_view/operator= "cpp/string/basic string view/operator=")
(C++17) | assigns a view (public member function) |
| Iterators |
| [begincbegin](basic_string_view/begin "cpp/string/basic string view/begin")
(C++17) | returns an iterator to the beginning (public member function) |
| [endcend](basic_string_view/end "cpp/string/basic string view/end")
(C++17) | returns an iterator to the end (public member function) |
| [rbegincrbegin](basic_string_view/rbegin "cpp/string/basic string view/rbegin")
(C++17) | returns a reverse iterator to the beginning (public member function) |
| [rendcrend](basic_string_view/rend "cpp/string/basic string view/rend")
(C++17) | returns a reverse iterator to the end (public member function) |
| Element access |
| [operator[]](basic_string_view/operator_at "cpp/string/basic string view/operator at")
(C++17) | accesses the specified character (public member function) |
| [at](basic_string_view/at "cpp/string/basic string view/at")
(C++17) | accesses the specified character with bounds checking (public member function) |
| [front](basic_string_view/front "cpp/string/basic string view/front")
(C++17) | accesses the first character (public member function) |
| [back](basic_string_view/back "cpp/string/basic string view/back")
(C++17) | accesses the last character (public member function) |
| [data](basic_string_view/data "cpp/string/basic string view/data")
(C++17) | returns a pointer to the first character of a view (public member function) |
| Capacity |
| [sizelength](basic_string_view/size "cpp/string/basic string view/size")
(C++17) | returns the number of characters (public member function) |
| [max\_size](basic_string_view/max_size "cpp/string/basic string view/max size")
(C++17) | returns the maximum number of characters (public member function) |
| [empty](basic_string_view/empty "cpp/string/basic string view/empty")
(C++17) | checks whether the view is empty (public member function) |
| Modifiers |
| [remove\_prefix](basic_string_view/remove_prefix "cpp/string/basic string view/remove prefix")
(C++17) | shrinks the view by moving its start forward (public member function) |
| [remove\_suffix](basic_string_view/remove_suffix "cpp/string/basic string view/remove suffix")
(C++17) | shrinks the view by moving its end backward (public member function) |
| [swap](basic_string_view/swap "cpp/string/basic string view/swap")
(C++17) | swaps the contents (public member function) |
| Operations |
| [copy](basic_string_view/copy "cpp/string/basic string view/copy")
(C++17) | copies characters (public member function) |
| [substr](basic_string_view/substr "cpp/string/basic string view/substr")
(C++17) | returns a substring (public member function) |
| [compare](basic_string_view/compare "cpp/string/basic string view/compare")
(C++17) | compares two views (public member function) |
| [starts\_with](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) |
| [ends\_with](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) |
| [contains](basic_string_view/contains "cpp/string/basic string view/contains")
(C++23) | checks if the string view contains the given substring or character (public member function) |
| [find](basic_string_view/find "cpp/string/basic string view/find")
(C++17) | find characters in the view (public member function) |
| [rfind](basic_string_view/rfind "cpp/string/basic string view/rfind")
(C++17) | find the last occurrence of a substring (public member function) |
| [find\_first\_of](basic_string_view/find_first_of "cpp/string/basic string view/find first of")
(C++17) | find first occurrence of characters (public member function) |
| [find\_last\_of](basic_string_view/find_last_of "cpp/string/basic string view/find last of")
(C++17) | find last occurrence of characters (public member function) |
| [find\_first\_not\_of](basic_string_view/find_first_not_of "cpp/string/basic string view/find first not of")
(C++17) | find first absence of characters (public member function) |
| [find\_last\_not\_of](basic_string_view/find_last_not_of "cpp/string/basic string view/find last not of")
(C++17) | find last absence of characters (public member function) |
| Constants |
| [npos](basic_string_view/npos "cpp/string/basic string view/npos")
[static] (C++17) | special value. The exact meaning depends on the context (public static member constant) |
### Non-member functions
| | |
| --- | --- |
| [operator==operator!=operator<operator>operator<=operator>=operator<=>](basic_string_view/operator_cmp "cpp/string/basic string view/operator cmp")
(C++17)(removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(C++20) | lexicographically compares two string views (function template) |
| Input/output |
| [operator<<](basic_string_view/operator_ltlt "cpp/string/basic string view/operator ltlt")
(C++17) | performs stream output on string views (function template) |
### Literals
| Defined in inline namespace `[std::literals::string\_view\_literals](../header/string_view#Synopsis "cpp/header/string view")` |
| --- |
| [operator""sv](basic_string_view/operator%22%22sv "cpp/string/basic string view/operator\"\"sv")
(C++17) | Creates a string view of a character array literal (function) |
### Helper classes
| | |
| --- | --- |
| [std::hash<std::string\_view>std::hash<std::wstring\_view>std::hash<std::u8string\_view>std::hash<std::u16string\_view>std::hash<std::u32string\_view>](basic_string_view/hash "cpp/string/basic string view/hash")
(C++17)(C++17)(C++20)(C++17)(C++17) | hash support for string views (class template specialization) |
### Helper templates
| | | |
| --- | --- | --- |
|
```
template<class CharT, class Traits>
inline constexpr bool ranges::enable_borrowed_range<std::basic_string_view<CharT, Traits>> = true;
```
| | (since C++20) |
This specialization of [`ranges::enable_borrowed_range`](../ranges/borrowed_range "cpp/ranges/borrowed range") makes `basic_string_view` satisfy [`borrowed_range`](../ranges/borrowed_range "cpp/ranges/borrowed range").
| | | |
| --- | --- | --- |
|
```
template<class CharT, class Traits>
inline constexpr bool ranges::enable_view<std::basic_string_view<CharT, Traits>> = true;
```
| | (since C++20) |
This specialization of `[ranges::enable\_view](../ranges/view "cpp/ranges/view")` makes `basic_string_view` satisfy [`view`](../ranges/view "cpp/ranges/view").
### [Deduction guides](basic_string_view/deduction_guides "cpp/string/basic string view/deduction guides")(since C++20)
### Notes
It is the programmer's responsibility to ensure that `std::string_view` does not outlive the pointed-to character array:
```
std::string_view good{"a string literal"};
// "Good" case: `good` points to a static array. String literals usually
// reside in persistent data segments.
std::string_view bad{"a temporary string"s};
// "Bad" case: `bad` holds a dangling pointer since the std::string temporary,
// created by std::operator""s, will be destroyed at the end of the statement.
```
Specializations of `std::basic_string_view` 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 | Value | Std | Comment |
| --- | --- | --- | --- |
| [`__cpp_lib_string_view`](../feature_test#Library_features "cpp/feature test") | `201606L` | (C++17) |
| [`__cpp_lib_string_view`](../feature_test#Library_features "cpp/feature test") | `201803L` | (C++20) | [ConstexprIterator](../named_req/constexpriterator "cpp/named req/ConstexprIterator") |
| [`__cpp_lib_string_contains`](../feature_test#Library_features "cpp/feature test") | `202011L` | (C++23) | [`contains`](basic_string_view/contains "cpp/string/basic string view/contains") |
### Example
```
#include <iostream>
#include <string_view>
int main() {
constexpr std::string_view unicode[] {
"โโโ", "โโโ", "โโโ", "โโโ"
};
for (int y{}, p{}; y != 6; ++y, p = ((p + 1) % 4)) {
for (int x{}; x != 16; ++x)
std::cout << unicode[p];
std::cout << '\n';
}
}
```
Possible output:
```
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
```
### See also
| | |
| --- | --- |
| [basic\_string](basic_string "cpp/string/basic string") | stores and manipulates sequences of characters (class template) |
| [span](../container/span "cpp/container/span")
(C++20) | a non-owning view over a contiguous sequence of objects (class template) |
| [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) |
| programming_docs |
cpp std::char_traits<CharT>::compare std::char\_traits<CharT>::compare
=================================
| | | |
| --- | --- | --- |
|
```
static int compare( const char_type* s1, const char_type* s2, std::size_t count );
```
| | (until C++17) |
|
```
static constexpr int compare( const char_type* s1, const char_type* s2, std::size_t count );
```
| | (since C++17) |
Compares the first `count` characters of the character strings `s1` and `s2`. The comparison is done lexicographically.
If `count` is zero, strings are considered equal.
### Parameters
| | | |
| --- | --- | --- |
| s1, s2 | - | pointers to character strings to compare |
| count | - | the number of characters to compare from each character string |
### Return value
Negative value if `s1` is *less than* `s2`.
`โ0โ` if `s1` is *equal to* `s2`.
Positive value if `s1` is *greater than* `s2`.
### Exceptions
Throws nothing.
### Complexity
Linear in `count`.
cpp std::char_traits<CharT>::to_int_type std::char\_traits<CharT>::to\_int\_type
=======================================
| | | |
| --- | --- | --- |
|
```
static int_type to_int_type( char_type c );
```
| | (until C++11) |
|
```
static constexpr int_type to_int_type( char_type c ) noexcept;
```
| | (since C++11) |
Converts a value of `char_type` to `int_type`.
### Parameters
| | | |
| --- | --- | --- |
| c | - | value to convert |
### Return value
A value equivalent to `c`.
### Complexity
Constant.
### Notes
For every valid value of `char_type`, there must be a unique value of `int_type` distinct from `eof()`. For example, a common implementation of `char_traits<char>::eof()` is `return -1`, and a corresponding valid implementation of `char_traits<char>::to_int_type(c)` is `return (unsigned char)c`.
cpp std::char_traits<CharT>::eq_int_type std::char\_traits<CharT>::eq\_int\_type
=======================================
| | | |
| --- | --- | --- |
|
```
static bool eq_int_type( int_type c1, int_type c2 );
```
| | (until C++11) |
|
```
static constexpr bool eq_int_type( int_type c1, int_type c2 ) noexcept;
```
| | (since C++11) |
Checks whether two values of type `int_type` are equal.
Formally,
* if there exist values `a` and `b` such that `c1 == X::to_int_type(a)` and `c2 == X::to_int_type(b)`, yields the same as `X::eq(a,b)`
* otherwise, if `c1` and `c2` are both copies of `X::eof()`, yields true
* otherwise, if one of `c1` and `c2` is a copy of `X::eof()` and the other is not, yields false
* otherwise, the result is unspecified
### Parameters
| | | |
| --- | --- | --- |
| c1, c2 | - | values to compare |
### Return value
`true` if `c1` is equal to `c2` under the rules described above, `false` otherwise.
### Complexity
Constant.
cpp std::char_traits<CharT>::length std::char\_traits<CharT>::length
================================
| | | |
| --- | --- | --- |
|
```
static std::size_t length( const char_type* s );
```
| | (until C++17) |
|
```
static constexpr std::size_t length( const char_type* s );
```
| | (since C++17) |
Returns the length of the character sequence pointed to by `s`, that is, the position of the terminating null character (`CharT()`).
### Parameters
| | | |
| --- | --- | --- |
| s | - | pointer to a character sequence to return length of |
### Return value
The length of character sequence pointed to by `s`.
### Exceptions
Throws nothing.
### Complexity
Linear.
### Example
```
#include <iostream>
#include <iomanip>
#include <string>
void print(const char* str)
{
std::cout << std::quoted(str) << " has length = "
<< std::char_traits<char>::length(str) << '\n';
}
int main()
{
print("foo");
std::string s{"booo"};
print(s.c_str());
}
```
Output:
```
"foo" has length = 3
"booo" has length = 4
```
cpp std::char_traits<CharT>::eof std::char\_traits<CharT>::eof
=============================
| | | |
| --- | --- | --- |
|
```
static int_type eof();
```
| | (until C++11) |
|
```
static constexpr int_type eof() noexcept;
```
| | (since C++11) |
Returns a value not equivalent to any valid value of type `char_type`.
Formally, returns a value `e` such that `X::eq_int_type(e, X::to_int_type(c))` is `false` for all values `c`.
### Parameters
(none).
### Return value
A value not equivalent to any valid value of type `char_type`.
### Complexity
Constant.
### See also
| | |
| --- | --- |
| [not\_eof](not_eof "cpp/string/char traits/not eof")
[static] | checks whether a character is *eof* value (public static member function) |
cpp std::char_traits<CharT>::assign std::char\_traits<CharT>::assign
================================
| | | |
| --- | --- | --- |
| | (1) | |
|
```
static void assign( char_type& r, const char_type& a );
```
| (until C++11) |
|
```
static void assign( char_type& r, const char_type& a ) noexcept;
```
| (since C++11) (until C++17) |
|
```
static constexpr void assign( char_type& r, const char_type& a ) noexcept;
```
| (since C++17) |
| | (2) | |
|
```
static char_type* assign( char_type* p, std::size_t count, char_type a );
```
| (until C++20) |
|
```
static constexpr char_type* assign( char_type* p,
std::size_t count, char_type a );
```
| (since C++20) |
Assigns a character.
1) Assigns character `a` to character `r`.
2) Assigns character `a` to each character in `count` characters in the character sequence pointed to by `p`. ### Parameters
| | | |
| --- | --- | --- |
| a | - | character value to assign |
| r | - | character to assign to |
| p | - | pointer to a character sequence to assign to |
| count | - | the length of the character sequence |
### Return value
1) (none)
2) `p`
### Complexity
1) Constant.
2) Linear in `count`
cpp std::char_traits<CharT>::to_char_type std::char\_traits<CharT>::to\_char\_type
========================================
| | | |
| --- | --- | --- |
|
```
static char_type to_char_type( int_type c );
```
| | (until C++11) |
|
```
static constexpr char_type to_char_type( int_type c ) noexcept;
```
| | (since C++11) |
Converts a value of `int_type` to `char_type`. If there are no equivalent value (such as when `c` is a copy of the [`eof()`](eof "cpp/string/char traits/eof") value), the result is unspecified.
Formally, returns the value `x` such that `X::eq_int_type(c, X::to_int_type(x))` is true, and an unspecified value if no such `x` exists.
### Parameters
| | | |
| --- | --- | --- |
| c | - | value to convert |
### Return value
A value equivalent to `c`.
### Complexity
Constant.
cpp std::char_traits<CharT>::find std::char\_traits<CharT>::find
==============================
| | | |
| --- | --- | --- |
|
```
static const char_type* find( const char_type* p, std::size_t count, const char_type& ch );
```
| | (until C++17) |
|
```
static constexpr const char_type* find( const char_type* p, std::size_t count, const char_type& ch );
```
| | (since C++17) |
Searches for character `ch` within the first `count` characters of the sequence pointed to by `p`.
### Parameters
| | | |
| --- | --- | --- |
| p | - | pointer to a character string to search |
| count | - | the number of characters to analyze |
| ch | - | the character to search for |
### Return value
A pointer to the first character in the range specified by `[p, p + count)` that compares equal to `ch`, or a null pointer if not found.
### Exceptions
Throws nothing.
### Complexity
Linear in `count`.
cpp std::char_traits<CharT>::not_eof std::char\_traits<CharT>::not\_eof
==================================
| | | |
| --- | --- | --- |
|
```
static int_type not_eof( int_type e );
```
| | (until C++11) |
|
```
static constexpr int_type not_eof( int_type e ) noexcept;
```
| | (since C++11) |
Given `e`, produce a suitable value that is not equivalent to *eof*.
Formally.
* if `X::eq_int_type(e, X::eof())` is `false`, returns `e`
* otherwise, returns a value `f` such that `X::eq_int_type(f, X::eof())` is `false`
This function is typically used when a value other than *eof* needs to be returned, such as in implementations of `[std::basic\_streambuf::overflow()](../../io/basic_streambuf/overflow "cpp/io/basic streambuf/overflow")`.
### Parameters
| | | |
| --- | --- | --- |
| e | - | value to analyze |
### Return value
`e` if `e` and *eof* value are not equivalent, returns some other non-eof value otherwise.
### Complexity
Constant.
### See also
| | |
| --- | --- |
| [eof](eof "cpp/string/char traits/eof")
[static] | returns an *eof* value (public static member function) |
cpp std::char_traits<CharT>::copy std::char\_traits<CharT>::copy
==============================
| | | |
| --- | --- | --- |
|
```
static char_type* copy( char_type* dest, const char_type* src, std::size_t count );
```
| | (until C++20) |
|
```
static constexpr char_type* copy( char_type* dest, const char_type* src, std::size_t count );
```
| | (since C++20) |
Copies `count` characters from the character string pointed to by `src` to the character string pointed to by `dest`.
Formally, for each `i` in `[0, count)`, performs `assign(src[i], dest[i])`.
The behavior is undefined if copied character ranges overlap, i.e. `src` is in [`dest`, `dest + count`).
### Parameters
| | | |
| --- | --- | --- |
| dest | - | pointer to a character string to copy to |
| src | - | pointer to a character string to copy from |
| count | - | the number of characters to copy |
### Return value
`dest`.
### Exceptions
Throws nothing.
### Complexity
Linear.
### See also
| | |
| --- | --- |
| [assign](assign "cpp/string/char traits/assign")
[static] | assigns a character (public static member function) |
cpp std::char_traits<CharT>::eq, std::char_traits<CharT>::lt std::char\_traits<CharT>::eq, std::char\_traits<CharT>::lt
==========================================================
| | | |
| --- | --- | --- |
| | (1) | |
|
```
static bool eq( char_type a, char_type b );
```
| (until C++11) |
|
```
static constexpr bool eq( char_type a, char_type b ) noexcept;
```
| (since C++11) |
| | (2) | |
|
```
static bool lt( char_type a, char_type b );
```
| (until C++11) |
|
```
static constexpr bool lt( char_type a, char_type b ) noexcept;
```
| (since C++11) |
Compares two characters.
1) Compares `a` and `b` for equality.
2) Compares `a` and `b` in such a way that they are totally ordered.
| | |
| --- | --- |
| For the `char` specialization, `eq` and `lt` are defined identically to the built-in operators `==` and `<` for type `unsigned char` (*not* `char`). | (since C++11) |
### Parameters
| | | |
| --- | --- | --- |
| a, b | - | character values to compare |
### Return value
1) `true` if `a` and `b` are equal, `false` otherwise.
2) `true` if `a` is *less* than `b`, `false` otherwise. ### Complexity
Constant.
cpp std::char_traits<CharT>::move std::char\_traits<CharT>::move
==============================
| | | |
| --- | --- | --- |
|
```
static char_type*
move( char_type* dest, const char_type* src, std::size_t count );
```
| | (until C++20) |
|
```
static constexpr char_type*
move( char_type* dest, const char_type* src, std::size_t count );
```
| | (since C++20) |
Copies `count` characters from the character string pointed to by `src` to the character string pointed to by `dest`.
Performs correctly even if the ranges `[src, src + count)` and `[dest, dest + count)` overlap.
### Parameters
| | | |
| --- | --- | --- |
| dest | - | pointer to a character string to copy to |
| src | - | pointer to a character string to copy from |
| count | - | the number of characters to copy |
### Return value
`dest`.
### Exceptions
Throws nothing.
### Complexity
Linear.
### 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 7](https://cplusplus.github.io/LWG/issue7) | C++98 | the copy was guaranteed to perform correctly if`src` is in `[dest, dest + count)`, but not the otherway round (i.e. `dest` is in `[src, src + count)`) | also guaranteed |
cpp std::wcschr std::wcschr
===========
| Defined in header `[<cwchar>](../../header/cwchar "cpp/header/cwchar")` | | |
| --- | --- | --- |
|
```
const wchar_t* wcschr( const wchar_t* str, wchar_t ch );
```
| | |
|
```
wchar_t* wcschr( wchar_t* str, wchar_t ch );
```
| | |
Finds the first occurrence of the wide character `ch` in the wide string pointed to by `str`.
### Parameters
| | | |
| --- | --- | --- |
| str | - | pointer to the null-terminated wide string to be analyzed |
| ch | - | wide character to search for |
### Return value
Pointer to the found character in `str`, or a null pointer if no such character is found.
### Example
```
#include <iostream>
#include <cwchar>
#include <locale>
int main()
{
const wchar_t arr[] = L"็ฝ็ซ ้ป็ซ ะบะพัะบะธ";
const wchar_t* cat = std::wcschr(arr, L'็ซ');
const wchar_t* dog = std::wcschr(arr, L'็ฌ');
std::cout.imbue(std::locale("en_US.utf8"));
if(cat)
std::cout << "The character ็ซ found at position " << cat - arr << '\n';
else
std::cout << "The character ็ซ not found\n";
if(dog)
std::cout << "The character ็ฌ found at position " << dog - arr << '\n';
else
std::cout << "The character ็ฌ not found\n";
}
```
Output:
```
The character ็ซ found at position 1
The character ็ฌ not found
```
### See also
| | |
| --- | --- |
| [find](../basic_string/find "cpp/string/basic string/find") | find characters in the string (public member function of `std::basic_string<CharT,Traits,Allocator>`) |
| [strchr](../byte/strchr "cpp/string/byte/strchr") | finds the first occurrence of a character (function) |
| [wcsrchr](wcsrchr "cpp/string/wide/wcsrchr") | finds the last occurrence of a wide character in a wide string (function) |
| [wcspbrk](wcspbrk "cpp/string/wide/wcspbrk") | finds the first location of any wide character in one wide string, in another wide string (function) |
| [C documentation](https://en.cppreference.com/w/c/string/wide/wcschr "c/string/wide/wcschr") for `wcschr` |
cpp std::iswctype std::iswctype
=============
| Defined in header `[<cwctype>](../../header/cwctype "cpp/header/cwctype")` | | |
| --- | --- | --- |
|
```
int iswctype( std::wint_t wc, std::wctype_t desc );
```
| | |
Classifies the wide character `wc` using the current C locale's LC\_CTYPE category identified by `desc`.
If the value of `wc` is neither representable as a `wchar_t` nor equal to the value of the macro `WEOF`, the behavior is undefined.
### Parameters
| | | |
| --- | --- | --- |
| wc | - | the wide character to classify |
| desc | - | the LC\_CTYPE category, obtained from a call to `[std::wctype](wctype "cpp/string/wide/wctype")` |
### Return value
Non-zero if the character `ch` has the property identified by `desc` in LC\_CTYPE facet of the current C locale, zero otherwise.
### Example
```
#include <clocale>
#include <cwctype>
#include <iostream>
bool classify(wchar_t wc, const std::string& cat)
{
return std::iswctype(wc, std::wctype(cat.c_str()));
}
int main()
{
std::setlocale(LC_ALL, "ja_JP.UTF-8");
std::cout << "The character \u6c34 is...\n";
for(std::string s : {"digit", "alpha", "space", "cntrl", "jkanji"})
std::cout << s << "? " << std::boolalpha << classify(L'\u6c34', s) << '\n';
}
```
Output:
```
The character ๆฐด is...
digit? false
alpha? true
space? false
cntrl? false
jkanji? true
```
### See also
| | |
| --- | --- |
| [wctype](wctype "cpp/string/wide/wctype") | looks up a character classification category in the current C locale (function) |
| [C documentation](https://en.cppreference.com/w/c/string/wide/iswctype "c/string/wide/iswctype") for `iswctype` |
cpp std::wcsstr std::wcsstr
===========
| Defined in header `[<cwchar>](../../header/cwchar "cpp/header/cwchar")` | | |
| --- | --- | --- |
|
```
const wchar_t* wcsstr( const wchar_t* dest, const wchar_t* src );
```
| | |
|
```
wchar_t* wcsstr( wchar_t* dest, const wchar_t* src );
```
| | |
Finds the first occurrence of the wide string `src` in the wide string pointed to by `dest`. The terminating null characters are not compared.
### Parameters
| | | |
| --- | --- | --- |
| dest | - | pointer to the null-terminated wide string to examine |
| src | - | pointer to the null-terminated wide string to search for |
### Return value
Pointer to the first character of the found substring in `dest`, or a null pointer if no such substring is found. If `src` points to an empty string, `dest` is returned.
### Example
```
#include <iostream>
#include <cwchar>
#include <clocale>
int main()
{
wchar_t const* origin = L"ใขใซใใก, ใใผใฟ, ใฌใณใ, ใขใซใใก, ใใผใฟ, ใฌใณใ.";
wchar_t const* target = L"ใใผใฟ";
wchar_t const* result = origin;
std::setlocale(LC_ALL, "en_US.utf8");
std::wcout << L"Substring to find: \"" << target << L"\"\n"
<< L"String to search: \"" << origin << L"\"\n\n";
for (; (result = std::wcsstr(result, target)) != nullptr; ++result)
std::wcout << L"Found: \"" << result << L"\"\n";
}
```
Possible output:
```
Substring to find: "ใใผใฟ"
String to search: "ใขใซใใก, ใใผใฟ, ใฌใณใ, ใขใซใใก, ใใผใฟ, ใฌใณใ."
Found: "ใใผใฟ, ใฌใณใ, ใขใซใใก, ใใผใฟ, ใฌใณใ."
Found: "ใใผใฟ, ใฌใณใ."
```
### See also
| | |
| --- | --- |
| [find](../basic_string/find "cpp/string/basic string/find") | find characters in the string (public member function of `std::basic_string<CharT,Traits,Allocator>`) |
| [strstr](../byte/strstr "cpp/string/byte/strstr") | finds the first occurrence of a substring of characters (function) |
| [wcschr](wcschr "cpp/string/wide/wcschr") | finds the first occurrence of a wide character in a wide string (function) |
| [wcsrchr](wcsrchr "cpp/string/wide/wcsrchr") | finds the last occurrence of a wide character in a wide string (function) |
| [C documentation](https://en.cppreference.com/w/c/string/wide/wcsstr "c/string/wide/wcsstr") for `wcsstr` |
cpp std::wcsncat std::wcsncat
============
| Defined in header `[<cwchar>](../../header/cwchar "cpp/header/cwchar")` | | |
| --- | --- | --- |
|
```
wchar_t *wcsncat( wchar_t *dest, const wchar_t *src, std::size_t count );
```
| | |
Appends at most `count` wide characters from the wide string pointed to by `src` to the end of the character string pointed to by `dest`, stopping if the null terminator is copied. The wide character `src[0]` replaces the null terminator at the end of `dest`. The null terminator is always appended in the end (so the maximum number of wide characters the function may write is `count+1`).
The behavior is undefined if the destination array is not large enough for the contents of both `str` and `dest` and the terminating null wide character.
The behavior is undefined if the strings overlap.
### Parameters
| | | |
| --- | --- | --- |
| dest | - | pointer to the null-terminated wide string to append to |
| src | - | pointer to the null-terminated wide string to copy from |
| count | - | maximum number of wide characters to copy |
### Return value
`dest`.
### Example
```
#include <cwchar>
#include <iostream>
#include <clocale>
int main(void)
{
wchar_t str[50] = L"ะะตะผะปั, ะฟัะพัะฐะน.";
std::wcsncat(str, L" ", 1);
std::wcsncat(str, L"ะ ะดะพะฑััะน ะฟััั.", 8); // only append the first 8 wide chars
std::setlocale(LC_ALL, "en_US.utf8");
std::wcout.imbue(std::locale("en_US.utf8"));
std::wcout << str << '\n';
}
```
Possible output:
```
ะะตะผะปั, ะฟัะพัะฐะน. ะ ะดะพะฑััะน
```
### See also
| | |
| --- | --- |
| [wcscat](wcscat "cpp/string/wide/wcscat") | appends a copy of one wide string to another (function) |
| [strncat](../byte/strncat "cpp/string/byte/strncat") | concatenates a certain amount of characters of two strings (function) |
| [wcscpy](wcscpy "cpp/string/wide/wcscpy") | copies one wide string to another (function) |
| [C documentation](https://en.cppreference.com/w/c/string/wide/wcsncat "c/string/wide/wcsncat") for `wcsncat` |
| programming_docs |
cpp std::towupper std::towupper
=============
| Defined in header `[<cwctype>](../../header/cwctype "cpp/header/cwctype")` | | |
| --- | --- | --- |
|
```
std::wint_t towupper( std::wint_t ch );
```
| | |
Converts the given wide character to uppercase, if possible.
If the value of `ch` is neither representable as a `wchar_t` nor equal to the value of the macro `WEOF`, the behavior is undefined.
### Parameters
| | | |
| --- | --- | --- |
| ch | - | wide character to be converted |
### Return value
Uppercase version of `ch` or unmodified `ch` if no uppercase version is listed in the current C locale.
### Notes
Only 1:1 character mapping can be performed by this function, e.g. the uppercase form of 'ร' is (with some exceptions) the two-character string "SS", which cannot be obtained by `std::towupper`.
[ISO 30112](http://www.open-std.org/JTC1/SC35/WG5/docs/30112d10.pdf) specifies which pairs of Unicode characters are included in this mapping.
### Example
The latin [letter 'ลฟ' (U+017F)](https://en.wikipedia.org/wiki/Long_s "enwiki:Long s") is the alternative lowercase form of 'S' (U+0053).
```
#include <iostream>
#include <cwctype>
#include <clocale>
int main()
{
wchar_t c = L'\u017f'; // Latin small letter Long S ('ลฟ')
std::cout << std::hex << std::showbase;
std::cout << "in the default locale, towupper(" << (std::wint_t)c << ") = "
<< std::towupper(c) << '\n';
std::setlocale(LC_ALL, "en_US.utf8");
std::cout << "in Unicode locale, towupper(" << (std::wint_t)c << ") = "
<< std::towupper(c) << '\n';
}
```
Output:
```
in the default locale, towupper(0x17f) = 0x17f
in Unicode locale, towupper(0x17f) = 0x53
```
### See also
| | |
| --- | --- |
| [towlower](towlower "cpp/string/wide/towlower") | converts a wide character to lowercase (function) |
| [toupper(std::locale)](../../locale/toupper "cpp/locale/toupper") | converts a character to uppercase using the ctype facet of a locale (function template) |
| [toupper](../byte/toupper "cpp/string/byte/toupper") | converts a character to uppercase (function) |
| [C documentation](https://en.cppreference.com/w/c/string/wide/towupper "c/string/wide/towupper") for `towupper` |
cpp std::wctype std::wctype
===========
| Defined in header `[<cwctype>](../../header/cwctype "cpp/header/cwctype")` | | |
| --- | --- | --- |
|
```
std::wctype_t wctype( const char* str );
```
| | |
Constructs a value of type `std::wctype_t` that describes a LC\_CTYPE category of wide character classification. It may be one of the standard classification categories, or a locale-specific category, such as `"jkanji"`.
### Parameters
| | | |
| --- | --- | --- |
| str | - | C string holding the name of the desired category |
The following values of `str` are supported in all C locales:
| value of `str` | effect |
| --- | --- |
| `"alnum"` | identifies the category used by `[std::iswalnum](iswalnum "cpp/string/wide/iswalnum")` |
| `"alpha"` | identifies the category used by `[std::iswalpha](iswalpha "cpp/string/wide/iswalpha")` |
| `"blank"` | identifies the category used by `[std::iswblank](iswblank "cpp/string/wide/iswblank")` (C++11) |
| `"cntrl"` | identifies the category used by `[std::iswcntrl](iswcntrl "cpp/string/wide/iswcntrl")` |
| `"digit"` | identifies the category used by `[std::iswdigit](iswdigit "cpp/string/wide/iswdigit")` |
| `"graph"` | identifies the category used by `[std::iswgraph](iswgraph "cpp/string/wide/iswgraph")` |
| `"lower"` | identifies the category used by `[std::iswlower](iswlower "cpp/string/wide/iswlower")` |
| `"print"` | identifies the category used by `[std::iswprint](iswprint "cpp/string/wide/iswprint")` |
| `"space"` | identifies the category used by `[std::iswspace](iswspace "cpp/string/wide/iswspace")` |
| `"upper"` | identifies the category used by `[std::iswupper](iswupper "cpp/string/wide/iswupper")` |
| `"xdigit"` | identifies the category used by `[std::iswxdigit](iswxdigit "cpp/string/wide/iswxdigit")` |
### Return value
`std::wctype_t` object suitable for use with `[std::iswctype](iswctype "cpp/string/wide/iswctype")` to classify wide characters according to the named category of the current C locale or zero if `str` does not name a category supported by the current C locale.
### See also
| | |
| --- | --- |
| [iswctype](iswctype "cpp/string/wide/iswctype") | classifies a wide character according to the specified LC\_CTYPE category (function) |
| [C documentation](https://en.cppreference.com/w/c/string/wide/wctype "c/string/wide/wctype") for `wctype` |
cpp std::wcscpy std::wcscpy
===========
| Defined in header `[<cwchar>](../../header/cwchar "cpp/header/cwchar")` | | |
| --- | --- | --- |
|
```
wchar_t *wcscpy( wchar_t *dest, const wchar_t *src );
```
| | |
Copies the wide string pointed to by `src` (including the terminating null wide character) to wide character array pointed to by `dest`.
If the strings overlap, the behavior is undefined.
### Parameters
| | | |
| --- | --- | --- |
| dest | - | pointer to the wide character array to copy to |
| src | - | pointer to the null-terminated wide string to copy from |
### Return value
`dest`.
### Example
```
#include <iostream>
#include <cwchar>
#include <memory>
#include <clocale>
int main()
{
const wchar_t* src = L"็ฌ means dog";
// src[0] = L'็'; // can't modify string literal
auto dst = std::make_unique<wchar_t[]>(std::wcslen(src)+1); // +1 for the null
std::wcscpy(dst.get(), src);
dst[0] = L'็';
std::setlocale(LC_ALL, "en_US.utf8");
std::wcout.imbue(std::locale(""));
std::wcout << src << '\n' << dst.get() << '\n';
}
```
Output:
```
็ฌ means dog
็ means dog
```
### See also
| | |
| --- | --- |
| [wcsncpy](wcsncpy "cpp/string/wide/wcsncpy") | copies a certain amount of wide characters from one string to another (function) |
| [wmemcpy](wmemcpy "cpp/string/wide/wmemcpy") | copies a certain amount of wide characters between two non-overlapping arrays (function) |
| [strcpy](../byte/strcpy "cpp/string/byte/strcpy") | copies one string to another (function) |
| [C documentation](https://en.cppreference.com/w/c/string/wide/wcscpy "c/string/wide/wcscpy") for `wcscpy` |
cpp std::wcstoul, std::wcstoull std::wcstoul, std::wcstoull
===========================
| Defined in header `[<cwchar>](../../header/cwchar "cpp/header/cwchar")` | | |
| --- | --- | --- |
|
```
unsigned long wcstoul( const wchar_t* str, wchar_t** str_end, int base );
```
| | |
|
```
unsigned long long wcstoull( const wchar_t* str, wchar_t** str_end, int base );
```
| | (since C++11) |
Interprets an unsigned integer value in a wide string pointed to by `str`.
Discards any whitespace characters (as identified by calling [`std::iswspace`](iswspace "cpp/string/wide/iswspace")) until the first non-whitespace character is found, then takes as many characters as possible to form a valid *base-n* (where n=`base`) unsigned integer number representation and converts them to an integer value. The valid unsigned integer value consists of the following parts:
* (optional) plus or minus sign
* (optional) prefix (`0`) indicating octal base (applies only when the base is `8` or `โ0โ`)
* (optional) prefix (`0x` or `0X`) indicating hexadecimal base (applies only when the base is `16` or `โ0โ`)
* a sequence of digits
The set of valid values for base is `{0,2,3,...,36}.` The set of valid digits for base-`2` integers is `{0,1},` for base-`3` integers is `{0,1,2},` and so on. For bases larger than `10`, valid digits include alphabetic characters, starting from `Aa` for base-`11` integer, to `Zz` for base-`36` integer. The case of the characters is ignored.
Additional numeric formats may be accepted by the currently installed C [locale](../../locale/setlocale "cpp/locale/setlocale").
If the value of `base` is `โ0โ`, the numeric base is auto-detected: if the prefix is `0`, the base is octal, if the prefix is `0x` or `0X`, the base is hexadecimal, otherwise the base is decimal.
If the minus sign was part of the input sequence, the numeric value calculated from the sequence of digits is negated as if by [unary minus](../../language/operator_arithmetic#Unary_arithmetic_operators "cpp/language/operator arithmetic") in the result type, which applies unsigned integer wraparound rules.
The functions sets the pointer pointed to by `str_end` to point to the wide character past the last character interpreted. If `str_end` is a null pointer, it is ignored.
### Parameters
| | | |
| --- | --- | --- |
| str | - | pointer to the null-terminated wide string to be interpreted |
| str\_end | - | pointer to a pointer to a wide character. |
| base | - | *base* of the interpreted integer value |
### Return value
Integer value corresponding to the contents of `str` on success. If the converted value falls out of range of corresponding return type, range error occurs and `[ULONG\_MAX](../../types/climits "cpp/types/climits")` or `[ULLONG\_MAX](../../types/climits "cpp/types/climits")` is returned. If no conversion can be performed, `โ0โ` is returned.
### Example
```
#include <iostream>
#include <string>
#include <errno.h>
#include <cwchar>
int main()
{
const wchar_t* p = L"10 200000000000000000000000000000 30 40";
wchar_t *end;
std::wcout << "Parsing L'" << p << "':\n";
for (unsigned long i = std::wcstoul(p, &end, 10);
p != end;
i = std::wcstoul(p, &end, 10))
{
std::wcout << "'" << std::wstring(p, end-p) << "' -> ";
p = end;
if (errno == ERANGE){
std::wcout << "range error, got ";
errno = 0;
}
std::wcout << i << '\n';
}
}
```
Possible output:
```
Parsing L'10 200000000000000000000000000000 30 40':
'10' -> 10
' 200000000000000000000000000000' -> range error, got 18446744073709551615
' 30' -> 30
' 40' -> 40
```
### See also
| | |
| --- | --- |
| [strtoulstrtoull](../byte/strtoul "cpp/string/byte/strtoul")
(C++11) | converts a byte string to an unsigned integer value (function) |
| [wcstolwcstoll](wcstol "cpp/string/wide/wcstol") | converts a wide string to an integer value (function) |
| [C documentation](https://en.cppreference.com/w/c/string/wide/wcstoul "c/string/wide/wcstoul") for `wcstoul, wcstoull` |
cpp std::iswalnum std::iswalnum
=============
| Defined in header `[<cwctype>](../../header/cwctype "cpp/header/cwctype")` | | |
| --- | --- | --- |
|
```
int iswalnum( std::wint_t ch );
```
| | |
Checks if the given wide character is an alphanumeric character, i.e. either a number (`0123456789`), an uppercase letter (`ABCDEFGHIJKLMNOPQRSTUVWXYZ`), a lowercase letter (`abcdefghijklmnopqrstuvwxyz`) or any alphanumeric character specific to the current locale.
If the value of `ch` is neither representable as a `wchar_t` nor equal to the value of the macro `WEOF`, the behavior is undefined.
### Parameters
| | | |
| --- | --- | --- |
| ch | - | wide character |
### Return value
Non-zero value if the wide character is a alphanumeric character, zero otherwise.
### Notes
[ISO 30112](http://www.open-std.org/JTC1/SC35/WG5/docs/30112d10.pdf) specifies which Unicode characters are included in the POSIX alnum category.
### Example
```
#include <iostream>
#include <cwctype>
#include <clocale>
int main()
{
wchar_t c = L'\u13ad'; // the Cherokee letter HA ('แญ')
std::cout << std::hex << std::showbase << std::boolalpha;
std::cout << "in the default locale, iswalnum(" << (std::wint_t)c << ") = "
<< (bool)std::iswalnum(c) << '\n';
std::setlocale(LC_ALL, "en_US.utf8");
std::cout << "in Unicode locale, iswalnum(" << (std::wint_t)c << ") = "
<< (bool)std::iswalnum(c) << '\n';
}
```
Output:
```
in the default locale, iswalnum(0x13ad) = false
in Unicode locale, iswalnum(0x13ad) = true
```
### See also
| | |
| --- | --- |
| [isalnum(std::locale)](../../locale/isalnum "cpp/locale/isalnum") | checks if a character is classified as alphanumeric by a locale (function template) |
| [isalnum](../byte/isalnum "cpp/string/byte/isalnum") | checks if a character is alphanumeric (function) |
| [C documentation](https://en.cppreference.com/w/c/string/wide/iswalnum "c/string/wide/iswalnum") for `iswalnum` |
| ASCII values | characters | [`iscntrl`](../byte/iscntrl "cpp/string/byte/iscntrl") [`iswcntrl`](iswcntrl "cpp/string/wide/iswcntrl"). | [`isprint`](../byte/isprint "cpp/string/byte/isprint") [`iswprint`](iswprint "cpp/string/wide/iswprint"). | [`isspace`](../byte/isspace "cpp/string/byte/isspace") [`iswspace`](iswspace "cpp/string/wide/iswspace"). | [`isblank`](../byte/isblank "cpp/string/byte/isblank") [`iswblank`](iswblank "cpp/string/wide/iswblank"). | [`isgraph`](../byte/isgraph "cpp/string/byte/isgraph") [`iswgraph`](iswgraph "cpp/string/wide/iswgraph"). | [`ispunct`](../byte/ispunct "cpp/string/byte/ispunct") [`iswpunct`](iswpunct "cpp/string/wide/iswpunct"). | [`isalnum`](../byte/isalnum "cpp/string/byte/isalnum") **`iswalnum`**. | [`isalpha`](../byte/isalpha "cpp/string/byte/isalpha") [`iswalpha`](iswalpha "cpp/string/wide/iswalpha"). | [`isupper`](../byte/isupper "cpp/string/byte/isupper") [`iswupper`](iswupper "cpp/string/wide/iswupper"). | [`islower`](../byte/islower "cpp/string/byte/islower") [`iswlower`](iswlower "cpp/string/wide/iswlower"). | [`isdigit`](../byte/isdigit "cpp/string/byte/isdigit") [`iswdigit`](iswdigit "cpp/string/wide/iswdigit"). | [`isxdigit`](../byte/isxdigit "cpp/string/byte/isxdigit") [`iswxdigit`](iswxdigit "cpp/string/wide/iswxdigit"). |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| decimal | hexadecimal | octal |
| 0โ8 | `\x0`โ`\x8` | `\0`โ`\10` | control codes (`NUL`, etc.) | **`โ 0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 9 | `\x9` | `\11` | tab (`\t`) | **`โ 0`** | **`0`** | **`โ 0`** | **`โ 0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 10โ13 | `\xA`โ`\xD` | `\12`โ`\15` | whitespaces (`\n`, `\v`, `\f`, `\r`) | **`โ 0`** | **`0`** | **`โ 0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 14โ31 | `\xE`โ`\x1F` | `\16`โ`\37` | control codes | **`โ 0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 32 | `\x20` | `\40` | space | **`0`** | **`โ 0`** | **`โ 0`** | **`โ 0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 33โ47 | `\x21`โ`\x2F` | `\41`โ`\57` | `!"#$%&'()*+,-./` | **`0`** | **`โ 0`** | **`0`** | **`0`** | **`โ 0`** | **`โ 0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 48โ57 | `\x30`โ`\x39` | `\60`โ`\71` | `0123456789` | **`0`** | **`โ 0`** | **`0`** | **`0`** | **`โ 0`** | **`0`** | **`โ 0`** | **`0`** | **`0`** | **`0`** | **`โ 0`** | **`โ 0`** |
| 58โ64 | `\x3A`โ`\x40` | `\72`โ`\100` | `:;<=>?@` | **`0`** | **`โ 0`** | **`0`** | **`0`** | **`โ 0`** | **`โ 0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 65โ70 | `\x41`โ`\x46` | `\101`โ`\106` | `ABCDEF` | **`0`** | **`โ 0`** | **`0`** | **`0`** | **`โ 0`** | **`0`** | **`โ 0`** | **`โ 0`** | **`โ 0`** | **`0`** | **`0`** | **`โ 0`** |
| 71โ90 | `\x47`โ`\x5A` | `\107`โ`\132` | `GHIJKLMNOP``QRSTUVWXYZ` | **`0`** | **`โ 0`** | **`0`** | **`0`** | **`โ 0`** | **`0`** | **`โ 0`** | **`โ 0`** | **`โ 0`** | **`0`** | **`0`** | **`0`** |
| 91โ96 | `\x5B`โ`\x60` | `\133`โ`\140` | `[\]^_`` | **`0`** | **`โ 0`** | **`0`** | **`0`** | **`โ 0`** | **`โ 0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 97โ102 | `\x61`โ`\x66` | `\141`โ`\146` | `abcdef` | **`0`** | **`โ 0`** | **`0`** | **`0`** | **`โ 0`** | **`0`** | **`โ 0`** | **`โ 0`** | **`0`** | **`โ 0`** | **`0`** | **`โ 0`** |
| 103โ122 | `\x67`โ`\x7A` | `\147`โ`\172` | `ghijklmnop``qrstuvwxyz` | **`0`** | **`โ 0`** | **`0`** | **`0`** | **`โ 0`** | **`0`** | **`โ 0`** | **`โ 0`** | **`0`** | **`โ 0`** | **`0`** | **`0`** |
| 123โ126 | `\x7B`โ`\x7E` | `\172`โ`\176` | `{|}~` | **`0`** | **`โ 0`** | **`0`** | **`0`** | **`โ 0`** | **`โ 0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 127 | `\x7F` | `\177` | backspace character (`DEL`) | **`โ 0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
cpp std::wcscoll std::wcscoll
============
| Defined in header `[<cwchar>](../../header/cwchar "cpp/header/cwchar")` | | |
| --- | --- | --- |
|
```
int wcscoll( const wchar_t* lhs, const wchar_t* rhs );
```
| | |
Compares two null-terminated wide strings according to the locale most recently installed by `[std::setlocale](../../locale/setlocale "cpp/locale/setlocale")`, as defined by the `[LC\_COLLATE](../../locale/lc_categories "cpp/locale/LC categories")` category.
### Parameters
| | | |
| --- | --- | --- |
| lhs, rhs | - | pointers to the null-terminated wide strings to compare |
### Return value
Negative value if `lhs` is *less than* (precedes) `rhs`.
`โ0โ` if `lhs` is *equal to* `rhs`.
Positive value if `lhs` is *greater than* (follows) `rhs`.
### Notes
Collation order is the dictionary order: the position of the letter in the national alphabet (its *equivalence class*) has higher priority than its case or variant. Within an equivalence class, lowercase characters collate before their uppercase equivalents and locale-specific order may apply to the characters with diacritics. In some locales, groups of characters compare as single *collation units*. For example, `"ch"` in Czech follows `"h"` and precedes `"i"`, and `"dzs"` in Hungarian follows `"dz"` and precedes `"g"`.
### Example
```
#include <iostream>
#include <clocale>
void try_compare(const wchar_t* p1, const wchar_t* p2)
{
if(std::wcscoll(p1, p2) < 0)
std::wcout << p1 << " before " << p2 << '\n';
else
std::wcout << p2 << " before " << p1 << '\n';
}
int main()
{
std::setlocale(LC_ALL, "en_US.utf8");
std::wcout << "In the American locale: ";
try_compare(L"hrnec", L"chrt");
std::setlocale(LC_COLLATE, "cs_CZ.utf8");
std::wcout << "In the Czech locale: ";
try_compare(L"hrnec", L"chrt");
std::setlocale(LC_COLLATE, "en_US.utf8");
std::wcout << "In the American locale: ";
try_compare(L"รฅr", L"รคngel");
std::setlocale(LC_COLLATE, "sv_SE.utf8");
std::wcout << "In the Swedish locale: ";
try_compare(L"รฅr", L"รคngel");
}
```
Output:
```
In the American locale: chrt before hrnec
In the Czech locale: hrnec before chrt
In the American locale: รคngel before รฅr
In the Swedish locale: รฅr before รคngel
```
### See also
| | |
| --- | --- |
| [strcoll](../byte/strcoll "cpp/string/byte/strcoll") | compares two strings in accordance to the current locale (function) |
| [do\_compare](../../locale/collate/compare "cpp/locale/collate/compare")
[virtual] | compares two strings using this facet's collation rules (virtual protected member function of `std::collate<CharT>`) |
| [wcsxfrm](wcsxfrm "cpp/string/wide/wcsxfrm") | transform a wide string so that wcscmp would produce the same result as wcscoll (function) |
| [C documentation](https://en.cppreference.com/w/c/string/wide/wcscoll "c/string/wide/wcscoll") for `wcscoll` |
cpp std::iswlower std::iswlower
=============
| Defined in header `[<cwctype>](../../header/cwctype "cpp/header/cwctype")` | | |
| --- | --- | --- |
|
```
int iswlower( std::wint_t ch );
```
| | |
Checks if the given wide character is a lowercase letter, i.e. one of `abcdefghijklmnopqrstuvwxyz` or any lowercase letter specific to the current locale.
If the value of `ch` is neither representable as a `wchar_t` nor equal to the value of the macro `WEOF`, the behavior is undefined.
### Parameters
| | | |
| --- | --- | --- |
| ch | - | wide character |
### Return value
Non-zero value if the wide character is an lowercase letter, zero otherwise.
### Notes
[ISO 30112](http://www.open-std.org/JTC1/SC35/WG5/docs/30112d10.pdf) specifies which Unicode characters are include in POSIX lower category.
### Example
```
#include <iostream>
#include <cwctype>
#include <clocale>
int main()
{
wchar_t c = L'\u0444'; // Cyrillic small letter ef ('ั')
std::cout << std::hex << std::showbase << std::boolalpha;
std::cout << "in the default locale, iswlower(" << (std::wint_t)c << ") = "
<< (bool)std::iswlower(c) << '\n';
std::setlocale(LC_ALL, "en_US.utf8");
std::cout << "in Unicode locale, iswlower(" << (std::wint_t)c << ") = "
<< (bool)std::iswlower(c) << '\n';
}
```
Output:
```
in the default locale, iswlower(0x444) = false
in Unicode locale, iswlower(0x444) = true
```
### See also
| | |
| --- | --- |
| [islower(std::locale)](../../locale/islower "cpp/locale/islower") | checks if a character is classified as lowercase by a locale (function template) |
| [islower](../byte/islower "cpp/string/byte/islower") | checks if a character is lowercase (function) |
| [C documentation](https://en.cppreference.com/w/c/string/wide/iswlower "c/string/wide/iswlower") for `iswlower` |
| ASCII values | characters | [`iscntrl`](../byte/iscntrl "cpp/string/byte/iscntrl") [`iswcntrl`](iswcntrl "cpp/string/wide/iswcntrl"). | [`isprint`](../byte/isprint "cpp/string/byte/isprint") [`iswprint`](iswprint "cpp/string/wide/iswprint"). | [`isspace`](../byte/isspace "cpp/string/byte/isspace") [`iswspace`](iswspace "cpp/string/wide/iswspace"). | [`isblank`](../byte/isblank "cpp/string/byte/isblank") [`iswblank`](iswblank "cpp/string/wide/iswblank"). | [`isgraph`](../byte/isgraph "cpp/string/byte/isgraph") [`iswgraph`](iswgraph "cpp/string/wide/iswgraph"). | [`ispunct`](../byte/ispunct "cpp/string/byte/ispunct") [`iswpunct`](iswpunct "cpp/string/wide/iswpunct"). | [`isalnum`](../byte/isalnum "cpp/string/byte/isalnum") [`iswalnum`](iswalnum "cpp/string/wide/iswalnum"). | [`isalpha`](../byte/isalpha "cpp/string/byte/isalpha") [`iswalpha`](iswalpha "cpp/string/wide/iswalpha"). | [`isupper`](../byte/isupper "cpp/string/byte/isupper") [`iswupper`](iswupper "cpp/string/wide/iswupper"). | [`islower`](../byte/islower "cpp/string/byte/islower") **`iswlower`**. | [`isdigit`](../byte/isdigit "cpp/string/byte/isdigit") [`iswdigit`](iswdigit "cpp/string/wide/iswdigit"). | [`isxdigit`](../byte/isxdigit "cpp/string/byte/isxdigit") [`iswxdigit`](iswxdigit "cpp/string/wide/iswxdigit"). |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| decimal | hexadecimal | octal |
| 0โ8 | `\x0`โ`\x8` | `\0`โ`\10` | control codes (`NUL`, etc.) | **`โ 0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 9 | `\x9` | `\11` | tab (`\t`) | **`โ 0`** | **`0`** | **`โ 0`** | **`โ 0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 10โ13 | `\xA`โ`\xD` | `\12`โ`\15` | whitespaces (`\n`, `\v`, `\f`, `\r`) | **`โ 0`** | **`0`** | **`โ 0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 14โ31 | `\xE`โ`\x1F` | `\16`โ`\37` | control codes | **`โ 0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 32 | `\x20` | `\40` | space | **`0`** | **`โ 0`** | **`โ 0`** | **`โ 0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 33โ47 | `\x21`โ`\x2F` | `\41`โ`\57` | `!"#$%&'()*+,-./` | **`0`** | **`โ 0`** | **`0`** | **`0`** | **`โ 0`** | **`โ 0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 48โ57 | `\x30`โ`\x39` | `\60`โ`\71` | `0123456789` | **`0`** | **`โ 0`** | **`0`** | **`0`** | **`โ 0`** | **`0`** | **`โ 0`** | **`0`** | **`0`** | **`0`** | **`โ 0`** | **`โ 0`** |
| 58โ64 | `\x3A`โ`\x40` | `\72`โ`\100` | `:;<=>?@` | **`0`** | **`โ 0`** | **`0`** | **`0`** | **`โ 0`** | **`โ 0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 65โ70 | `\x41`โ`\x46` | `\101`โ`\106` | `ABCDEF` | **`0`** | **`โ 0`** | **`0`** | **`0`** | **`โ 0`** | **`0`** | **`โ 0`** | **`โ 0`** | **`โ 0`** | **`0`** | **`0`** | **`โ 0`** |
| 71โ90 | `\x47`โ`\x5A` | `\107`โ`\132` | `GHIJKLMNOP``QRSTUVWXYZ` | **`0`** | **`โ 0`** | **`0`** | **`0`** | **`โ 0`** | **`0`** | **`โ 0`** | **`โ 0`** | **`โ 0`** | **`0`** | **`0`** | **`0`** |
| 91โ96 | `\x5B`โ`\x60` | `\133`โ`\140` | `[\]^_`` | **`0`** | **`โ 0`** | **`0`** | **`0`** | **`โ 0`** | **`โ 0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 97โ102 | `\x61`โ`\x66` | `\141`โ`\146` | `abcdef` | **`0`** | **`โ 0`** | **`0`** | **`0`** | **`โ 0`** | **`0`** | **`โ 0`** | **`โ 0`** | **`0`** | **`โ 0`** | **`0`** | **`โ 0`** |
| 103โ122 | `\x67`โ`\x7A` | `\147`โ`\172` | `ghijklmnop``qrstuvwxyz` | **`0`** | **`โ 0`** | **`0`** | **`0`** | **`โ 0`** | **`0`** | **`โ 0`** | **`โ 0`** | **`0`** | **`โ 0`** | **`0`** | **`0`** |
| 123โ126 | `\x7B`โ`\x7E` | `\172`โ`\176` | `{|}~` | **`0`** | **`โ 0`** | **`0`** | **`0`** | **`โ 0`** | **`โ 0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 127 | `\x7F` | `\177` | backspace character (`DEL`) | **`โ 0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| programming_docs |
cpp std::iswgraph std::iswgraph
=============
| Defined in header `[<cwctype>](../../header/cwctype "cpp/header/cwctype")` | | |
| --- | --- | --- |
|
```
int iswgraph( std::wint_t ch );
```
| | |
Checks if the given wide character has a graphical representation, i.e. it is either a number (`0123456789`), an uppercase letter (`ABCDEFGHIJKLMNOPQRSTUVWXYZ`), a lowercase letter (`abcdefghijklmnopqrstuvwxyz`), a punctuation character(`!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~`) or any graphical character specific to the current C locale.
If the value of `ch` is neither representable as a `wchar_t` nor equal to the value of the macro `WEOF`, the behavior is undefined.
### Parameters
| | | |
| --- | --- | --- |
| ch | - | wide character |
### Return value
Non-zero value if the wide character has a graphical representation character, zero otherwise.
### Notes
[ISO 30112](http://www.open-std.org/JTC1/SC35/WG5/docs/30112d10.pdf) specifies which Unicode characters are include in POSIX graph category.
### Example
```
#include <iostream>
#include <cwctype>
#include <clocale>
int main()
{
wchar_t c = L'\u2602'; // the Unicode character Umbrella ('โ')
std::cout << std::hex << std::showbase << std::boolalpha;
std::cout << "in the default locale, iswgraph(" << (std::wint_t)c << ") = "
<< (bool)std::iswgraph(c) << '\n';
std::setlocale(LC_ALL, "en_US.utf8");
std::cout << "in Unicode locale, iswgraph(" << (std::wint_t)c << ") = "
<< (bool)std::iswgraph(c) << '\n';
}
```
Output:
```
in the default locale, iswgraph(0x2602) = false
in Unicode locale, iswgraph(0x2602) = true
```
### See also
| | |
| --- | --- |
| [isgraph(std::locale)](../../locale/isgraph "cpp/locale/isgraph") | checks if a character is classfied as graphical by a locale (function template) |
| [isgraph](../byte/isgraph "cpp/string/byte/isgraph") | checks if a character is a graphical character (function) |
| [C documentation](https://en.cppreference.com/w/c/string/wide/iswgraph "c/string/wide/iswgraph") for `iswgraph` |
| ASCII values | characters | [`iscntrl`](../byte/iscntrl "cpp/string/byte/iscntrl") [`iswcntrl`](iswcntrl "cpp/string/wide/iswcntrl"). | [`isprint`](../byte/isprint "cpp/string/byte/isprint") [`iswprint`](iswprint "cpp/string/wide/iswprint"). | [`isspace`](../byte/isspace "cpp/string/byte/isspace") [`iswspace`](iswspace "cpp/string/wide/iswspace"). | [`isblank`](../byte/isblank "cpp/string/byte/isblank") [`iswblank`](iswblank "cpp/string/wide/iswblank"). | [`isgraph`](../byte/isgraph "cpp/string/byte/isgraph") **`iswgraph`**. | [`ispunct`](../byte/ispunct "cpp/string/byte/ispunct") [`iswpunct`](iswpunct "cpp/string/wide/iswpunct"). | [`isalnum`](../byte/isalnum "cpp/string/byte/isalnum") [`iswalnum`](iswalnum "cpp/string/wide/iswalnum"). | [`isalpha`](../byte/isalpha "cpp/string/byte/isalpha") [`iswalpha`](iswalpha "cpp/string/wide/iswalpha"). | [`isupper`](../byte/isupper "cpp/string/byte/isupper") [`iswupper`](iswupper "cpp/string/wide/iswupper"). | [`islower`](../byte/islower "cpp/string/byte/islower") [`iswlower`](iswlower "cpp/string/wide/iswlower"). | [`isdigit`](../byte/isdigit "cpp/string/byte/isdigit") [`iswdigit`](iswdigit "cpp/string/wide/iswdigit"). | [`isxdigit`](../byte/isxdigit "cpp/string/byte/isxdigit") [`iswxdigit`](iswxdigit "cpp/string/wide/iswxdigit"). |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| decimal | hexadecimal | octal |
| 0โ8 | `\x0`โ`\x8` | `\0`โ`\10` | control codes (`NUL`, etc.) | **`โ 0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 9 | `\x9` | `\11` | tab (`\t`) | **`โ 0`** | **`0`** | **`โ 0`** | **`โ 0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 10โ13 | `\xA`โ`\xD` | `\12`โ`\15` | whitespaces (`\n`, `\v`, `\f`, `\r`) | **`โ 0`** | **`0`** | **`โ 0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 14โ31 | `\xE`โ`\x1F` | `\16`โ`\37` | control codes | **`โ 0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 32 | `\x20` | `\40` | space | **`0`** | **`โ 0`** | **`โ 0`** | **`โ 0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 33โ47 | `\x21`โ`\x2F` | `\41`โ`\57` | `!"#$%&'()*+,-./` | **`0`** | **`โ 0`** | **`0`** | **`0`** | **`โ 0`** | **`โ 0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 48โ57 | `\x30`โ`\x39` | `\60`โ`\71` | `0123456789` | **`0`** | **`โ 0`** | **`0`** | **`0`** | **`โ 0`** | **`0`** | **`โ 0`** | **`0`** | **`0`** | **`0`** | **`โ 0`** | **`โ 0`** |
| 58โ64 | `\x3A`โ`\x40` | `\72`โ`\100` | `:;<=>?@` | **`0`** | **`โ 0`** | **`0`** | **`0`** | **`โ 0`** | **`โ 0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 65โ70 | `\x41`โ`\x46` | `\101`โ`\106` | `ABCDEF` | **`0`** | **`โ 0`** | **`0`** | **`0`** | **`โ 0`** | **`0`** | **`โ 0`** | **`โ 0`** | **`โ 0`** | **`0`** | **`0`** | **`โ 0`** |
| 71โ90 | `\x47`โ`\x5A` | `\107`โ`\132` | `GHIJKLMNOP``QRSTUVWXYZ` | **`0`** | **`โ 0`** | **`0`** | **`0`** | **`โ 0`** | **`0`** | **`โ 0`** | **`โ 0`** | **`โ 0`** | **`0`** | **`0`** | **`0`** |
| 91โ96 | `\x5B`โ`\x60` | `\133`โ`\140` | `[\]^_`` | **`0`** | **`โ 0`** | **`0`** | **`0`** | **`โ 0`** | **`โ 0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 97โ102 | `\x61`โ`\x66` | `\141`โ`\146` | `abcdef` | **`0`** | **`โ 0`** | **`0`** | **`0`** | **`โ 0`** | **`0`** | **`โ 0`** | **`โ 0`** | **`0`** | **`โ 0`** | **`0`** | **`โ 0`** |
| 103โ122 | `\x67`โ`\x7A` | `\147`โ`\172` | `ghijklmnop``qrstuvwxyz` | **`0`** | **`โ 0`** | **`0`** | **`0`** | **`โ 0`** | **`0`** | **`โ 0`** | **`โ 0`** | **`0`** | **`โ 0`** | **`0`** | **`0`** |
| 123โ126 | `\x7B`โ`\x7E` | `\172`โ`\176` | `{|}~` | **`0`** | **`โ 0`** | **`0`** | **`0`** | **`โ 0`** | **`โ 0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 127 | `\x7F` | `\177` | backspace character (`DEL`) | **`โ 0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
cpp std::iswalpha std::iswalpha
=============
| Defined in header `[<cwctype>](../../header/cwctype "cpp/header/cwctype")` | | |
| --- | --- | --- |
|
```
int iswalpha( std::wint_t ch );
```
| | |
Checks if the given wide character is an alphabetic character, i.e. either an uppercase letter (`ABCDEFGHIJKLMNOPQRSTUVWXYZ`), a lowercase letter (`abcdefghijklmnopqrstuvwxyz`) or any alphabetic character specific to the current locale.
If the value of `ch` is neither representable as a `wchar_t` nor equal to the value of the macro `WEOF`, the behavior is undefined.
### Parameters
| | | |
| --- | --- | --- |
| ch | - | wide character |
### Return value
Non-zero value if the wide character is a alphabetic character, `0` otherwise.
### Notes
[ISO 30112](http://www.open-std.org/JTC1/SC35/WG5/docs/30112d10.pdf) specifies which Unicode characters are include in POSIX alpha category.
### Example
```
#include <iostream>
#include <cwctype>
#include <clocale>
int main()
{
wchar_t c = L'\u0b83'; // Tamil sign Visarga ('เฎ')
std::cout << std::hex << std::showbase << std::boolalpha;
std::cout << "in the default locale, iswalpha(" << (std::wint_t)c << ") = "
<< (bool)std::iswalpha(c) << '\n';
std::setlocale(LC_ALL, "en_US.utf8");
std::cout << "in Unicode locale, iswalpha(" << (std::wint_t)c << ") = "
<< (bool)std::iswalpha(c) << '\n';
}
```
Output:
```
in the default locale, iswalpha(0xb83) = false
in Unicode locale, iswalpha(0xb83) = true
```
### See also
| | |
| --- | --- |
| [isalpha(std::locale)](../../locale/isalpha "cpp/locale/isalpha") | checks if a character is classified as alphabetic by a locale (function template) |
| [isalpha](../byte/isalpha "cpp/string/byte/isalpha") | checks if a character is alphabetic (function) |
| [C documentation](https://en.cppreference.com/w/c/string/wide/iswalpha "c/string/wide/iswalpha") for `iswalpha` |
| ASCII values | characters | [`iscntrl`](../byte/iscntrl "cpp/string/byte/iscntrl") [`iswcntrl`](iswcntrl "cpp/string/wide/iswcntrl"). | [`isprint`](../byte/isprint "cpp/string/byte/isprint") [`iswprint`](iswprint "cpp/string/wide/iswprint"). | [`isspace`](../byte/isspace "cpp/string/byte/isspace") [`iswspace`](iswspace "cpp/string/wide/iswspace"). | [`isblank`](../byte/isblank "cpp/string/byte/isblank") [`iswblank`](iswblank "cpp/string/wide/iswblank"). | [`isgraph`](../byte/isgraph "cpp/string/byte/isgraph") [`iswgraph`](iswgraph "cpp/string/wide/iswgraph"). | [`ispunct`](../byte/ispunct "cpp/string/byte/ispunct") [`iswpunct`](iswpunct "cpp/string/wide/iswpunct"). | [`isalnum`](../byte/isalnum "cpp/string/byte/isalnum") [`iswalnum`](iswalnum "cpp/string/wide/iswalnum"). | [`isalpha`](../byte/isalpha "cpp/string/byte/isalpha") **`iswalpha`**. | [`isupper`](../byte/isupper "cpp/string/byte/isupper") [`iswupper`](iswupper "cpp/string/wide/iswupper"). | [`islower`](../byte/islower "cpp/string/byte/islower") [`iswlower`](iswlower "cpp/string/wide/iswlower"). | [`isdigit`](../byte/isdigit "cpp/string/byte/isdigit") [`iswdigit`](iswdigit "cpp/string/wide/iswdigit"). | [`isxdigit`](../byte/isxdigit "cpp/string/byte/isxdigit") [`iswxdigit`](iswxdigit "cpp/string/wide/iswxdigit"). |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| decimal | hexadecimal | octal |
| 0โ8 | `\x0`โ`\x8` | `\0`โ`\10` | control codes (`NUL`, etc.) | **`โ 0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 9 | `\x9` | `\11` | tab (`\t`) | **`โ 0`** | **`0`** | **`โ 0`** | **`โ 0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 10โ13 | `\xA`โ`\xD` | `\12`โ`\15` | whitespaces (`\n`, `\v`, `\f`, `\r`) | **`โ 0`** | **`0`** | **`โ 0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 14โ31 | `\xE`โ`\x1F` | `\16`โ`\37` | control codes | **`โ 0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 32 | `\x20` | `\40` | space | **`0`** | **`โ 0`** | **`โ 0`** | **`โ 0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 33โ47 | `\x21`โ`\x2F` | `\41`โ`\57` | `!"#$%&'()*+,-./` | **`0`** | **`โ 0`** | **`0`** | **`0`** | **`โ 0`** | **`โ 0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 48โ57 | `\x30`โ`\x39` | `\60`โ`\71` | `0123456789` | **`0`** | **`โ 0`** | **`0`** | **`0`** | **`โ 0`** | **`0`** | **`โ 0`** | **`0`** | **`0`** | **`0`** | **`โ 0`** | **`โ 0`** |
| 58โ64 | `\x3A`โ`\x40` | `\72`โ`\100` | `:;<=>?@` | **`0`** | **`โ 0`** | **`0`** | **`0`** | **`โ 0`** | **`โ 0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 65โ70 | `\x41`โ`\x46` | `\101`โ`\106` | `ABCDEF` | **`0`** | **`โ 0`** | **`0`** | **`0`** | **`โ 0`** | **`0`** | **`โ 0`** | **`โ 0`** | **`โ 0`** | **`0`** | **`0`** | **`โ 0`** |
| 71โ90 | `\x47`โ`\x5A` | `\107`โ`\132` | `GHIJKLMNOP``QRSTUVWXYZ` | **`0`** | **`โ 0`** | **`0`** | **`0`** | **`โ 0`** | **`0`** | **`โ 0`** | **`โ 0`** | **`โ 0`** | **`0`** | **`0`** | **`0`** |
| 91โ96 | `\x5B`โ`\x60` | `\133`โ`\140` | `[\]^_`` | **`0`** | **`โ 0`** | **`0`** | **`0`** | **`โ 0`** | **`โ 0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 97โ102 | `\x61`โ`\x66` | `\141`โ`\146` | `abcdef` | **`0`** | **`โ 0`** | **`0`** | **`0`** | **`โ 0`** | **`0`** | **`โ 0`** | **`โ 0`** | **`0`** | **`โ 0`** | **`0`** | **`โ 0`** |
| 103โ122 | `\x67`โ`\x7A` | `\147`โ`\172` | `ghijklmnop``qrstuvwxyz` | **`0`** | **`โ 0`** | **`0`** | **`0`** | **`โ 0`** | **`0`** | **`โ 0`** | **`โ 0`** | **`0`** | **`โ 0`** | **`0`** | **`0`** |
| 123โ126 | `\x7B`โ`\x7E` | `\172`โ`\176` | `{|}~` | **`0`** | **`โ 0`** | **`0`** | **`0`** | **`โ 0`** | **`โ 0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 127 | `\x7F` | `\177` | backspace character (`DEL`) | **`โ 0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
cpp std::wmemset std::wmemset
============
| Defined in header `[<cwchar>](../../header/cwchar "cpp/header/cwchar")` | | |
| --- | --- | --- |
|
```
wchar_t* wmemset( wchar_t* dest, wchar_t ch, std::size_t count );
```
| | |
Copies the wide character `ch` into each of the first `count` wide characters of the wide character array pointed to by `dest`.
If overflow occurs, the behavior is undefined.
If `count` is zero, the function does nothing.
### Parameters
| | | |
| --- | --- | --- |
| dest | - | pointer to the wide character array to fill |
| ch | - | fill wide character |
| count | - | number of wide characters to fill |
### Return value
Returns a copy of `dest`.
### Notes
This function is not locale-sensitive and pays no attention to the values of the `wchar_t` objects it writes: nulls as well as invalid wide characters are written too.
### Example
```
#include <iostream>
#include <cwchar>
#include <clocale>
#include <locale>
int main()
{
wchar_t ar[4] = {L'1', L'2', L'3', L'4'};
std::wmemset(ar, L'\U0001f34c', 2); // replaces [12] with the ๐ bananas
std::wmemset(ar+2, L'่', 2); // replaces [34] with the ่ bananas
std::setlocale(LC_ALL, "en_US.utf8");
std::wcout.imbue(std::locale("en_US.utf8"));
std::wcout << std::wstring(ar, 4) << '\n';
}
```
Possible output:
```
๐๐่่
```
### See also
| | |
| --- | --- |
| [memset](../byte/memset "cpp/string/byte/memset") | fills a buffer with a character (function) |
| [wmemcpy](wmemcpy "cpp/string/wide/wmemcpy") | copies a certain amount of wide characters between two non-overlapping arrays (function) |
| [fill\_n](../../algorithm/fill_n "cpp/algorithm/fill n") | copy-assigns the given value to N elements in a range (function template) |
| [C documentation](https://en.cppreference.com/w/c/string/wide/wmemset "c/string/wide/wmemset") for `wmemset` |
cpp std::wmemcmp std::wmemcmp
============
| Defined in header `[<cwchar>](../../header/cwchar "cpp/header/cwchar")` | | |
| --- | --- | --- |
|
```
int wmemcmp( const wchar_t* lhs, const wchar_t* rhs, std::size_t count );
```
| | |
Compares the first `count` wide characters of the wide character arrays pointed to by `lhs` and `rhs`. The comparison is done lexicographically.
The sign of the result is the sign of the difference between the values of the first pair of wide characters that differ in the arrays being compared.
If `count` is zero, the function does nothing.
### Parameters
| | | |
| --- | --- | --- |
| lhs, rhs | - | pointers to the wide character arrays to compare |
| count | - | number of wide characters to examine |
### Return value
Negative value if the value of the first differing wide character in `lhs` is less than the value of the corresponding wide character in `rhs`: `lhs` precedes `rhs` in lexicographical order.
`โ0โ` if all `count` wide characters of `lhs` and `rhs` are equal.
Positive value if the value of the first differing wide character in `lhs` is greater than the value of the corresponding wide character in `rhs`: `rhs` precedes `lhs` in lexicographical order.
### Notes
This function is not locale-sensitive and pays no attention to the values of the `wchar_t` objects it examines: nulls as well as invalid wide characters are compared too.
### Example
```
#include <iostream>
#include <string>
#include <cwchar>
#include <locale>
#include <clocale>
void demo(const wchar_t* lhs, const wchar_t* rhs, std::size_t sz)
{
std::wcout << std::wstring(lhs, sz);
int rc = std::wmemcmp(lhs, rhs, sz);
if(rc == 0)
std::wcout << " compares equal to ";
else if(rc < 0)
std::wcout << " precedes ";
else if(rc > 0)
std::wcout << " follows ";
std::wcout << std::wstring(rhs, sz) << " in lexicographical order\n";
}
int main()
{
std::setlocale(LC_ALL, "en_US.utf8");
std::wcout.imbue(std::locale("en_US.utf8"));
wchar_t a1[] = {L'ฮฑ',L'ฮฒ',L'ฮณ'};
constexpr std::size_t sz = sizeof a1 / sizeof *a1;
wchar_t a2[sz] = {L'ฮฑ',L'ฮฒ',L'ฮด'};
demo(a1, a2, sz);
demo(a2, a1, sz);
demo(a1, a1, sz);
}
```
Possible output:
```
ฮฑฮฒฮณ precedes ฮฑฮฒฮด in lexicographical order
ฮฑฮฒฮด follows ฮฑฮฒฮณ in lexicographical order
ฮฑฮฒฮณ compares equal to ฮฑฮฒฮณ in lexicographical order
```
### See also
| | |
| --- | --- |
| [wcscmp](wcscmp "cpp/string/wide/wcscmp") | compares two wide strings (function) |
| [memcmp](../byte/memcmp "cpp/string/byte/memcmp") | compares two buffers (function) |
| [wcsncmp](wcsncmp "cpp/string/wide/wcsncmp") | compares a certain amount of characters from two wide strings (function) |
| [C documentation](https://en.cppreference.com/w/c/string/wide/wmemcmp "c/string/wide/wmemcmp") for `wmemcmp` |
cpp std::wcsxfrm std::wcsxfrm
============
| Defined in header `[<cwchar>](../../header/cwchar "cpp/header/cwchar")` | | |
| --- | --- | --- |
|
```
std::size_t wcsxfrm( wchar_t* dest, const wchar_t* src, std::size_t count );
```
| | |
Transforms the null-terminated wide string pointed to by `src` into the implementation-defined form such that comparing two transformed strings with `[std::wcscmp](wcscmp "cpp/string/wide/wcscmp")` gives the same result as comparing the original strings with `[std::wcscoll](wcscoll "cpp/string/wide/wcscoll")`, in the current C locale.
The first `count` characters of the transformed string are written to destination, including the terminating null character, and the length of the full transformed string is returned, excluding the terminating null character.
If `count` is `โ0โ`, then `dest` is allowed to be a null pointer.
### Notes
The correct length of the buffer that can receive the entire transformed string is `1 + std::wcsxfrm(nullptr, src, 0)`.
This function is used when making multiple locale-dependent comparisons using the same wide string or set of wide strings, because it is more efficient to use `std::wcsxfrm` to transform all the strings just once, and subsequently compare the transformed wide strings with `[std::wcscmp](wcscmp "cpp/string/wide/wcscmp")`.
### Parameters
| | | |
| --- | --- | --- |
| dest | - | pointer to the first element of a wide null-terminated string to write the transformed string to |
| src | - | pointer to the null-terminated wide character string to transform |
| count | - | maximum number of characters to output |
### Return value
The length of the transformed wide string, not including the terminating null-character.
### Example
```
#include <iostream>
#include <cwchar>
int main()
{
std::setlocale(LC_ALL, "sv_SE.utf8");
std::wstring in1 = L"\u00e5r";
std::wstring out1(1+std::wcsxfrm(nullptr, in1.c_str(), 0), L' ');
std::wstring in2 = L"\u00e4ngel";
std::wstring out2(1+std::wcsxfrm(nullptr, in2.c_str(), 0), L' ');
std::wcsxfrm(&out1[0], in1.c_str(), out1.size());
std::wcsxfrm(&out2[0], in2.c_str(), out2.size());
std::wcout << "In the Swedish locale: ";
if(out1 < out2)
std::wcout << in1 << " before " << in2 << '\n';
else
std::wcout << in2 << " before " << in1 << '\n';
std::wcout << "In lexicographical comparison: ";
if(in1 < in2)
std::wcout << in1 << " before " << in2 << '\n';
else
std::wcout << in2 << " before " << in1 << '\n';
}
```
Output:
```
In the Swedish locale: รฅr before รคngel
In lexicographical comparison: รคngel before รฅr
```
### See also
| | |
| --- | --- |
| [strxfrm](../byte/strxfrm "cpp/string/byte/strxfrm") | transform a string so that strcmp would produce the same result as strcoll (function) |
| [do\_transform](../../locale/collate/transform "cpp/locale/collate/transform")
[virtual] | transforms a string so that collation can be replaced by comparison (virtual protected member function of `std::collate<CharT>`) |
| [wcscoll](wcscoll "cpp/string/wide/wcscoll") | compares two wide strings in accordance to the current locale (function) |
| [C documentation](https://en.cppreference.com/w/c/string/wide/wcsxfrm "c/string/wide/wcsxfrm") for `wcsxfrm` |
| programming_docs |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.